Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

2013/08/26

JBoss Developer Studio freezes with XSD, WSDL, SwitchYard editors

Recently I started facing a strange issue on my ArchLinux boxes with JBoss Developer Studio (which is an enriched Eclipse under the covers). I was not able to open XSD, WSDL or SwitchYard visual editors. Part of the GUI just froze. Clicking on the close button opened the close dialog which allowed part of the interface to be redrawn.

I was quite desperate about it. It only affected my ArchLinux x86_64 boxes. I used multiple JVMs (Oracle, OpenJDK), different window managers (Fluxbox, Openbox, Gnome Shell). I verified the same Linux kernel in Fedora does not cause the issue. So what now?

What gave me some guidance was this command I found on StackOverflow (you must provide your own process number):

cat /proc/803/maps | awk '{print $6}' | grep '\.so' | sort | uniq

I compared the libraries before and after opening the problematic editor.

39a41,42
> /usr/lib/gtk-2.0/2.10.0/printbackends/libprintbackend-cups.so
> /usr/lib/gtk-2.0/2.10.0/printbackends/libprintbackend-file.so
50a54,56
> /usr/lib/libcom_err.so.2.1
> /usr/lib/libcrypt-2.18.so
> /usr/lib/libcups.so.2

This was a trace of a pretty old Eclipse bug. Surprisingly, the bug is still present in Eclipse Kepler with Gtk 2.24.20.

I tried the suggested workarounds by disabling CUPS server in /etc/cups/client.conf and passing -vmargs -Dorg.eclipse.swt.internal.gtk.disablePrinting to Eclipse. Both helped a little, but did not make Eclipse completely usable.

What really helped me was installing cups-pdf package, enabling CUPS via

systemctl enable cups.service

Then I started the service with

systemctl start cups.service

And configured a PDF printer at localhost:631.

I cannot express my happines about running CUPS on my machine :-(

2013/05/17

Book review: Well-grounded Java developer

Vital techniques of Java 7 and polyglot programming

  • Publisher: Manning
  • Authors: Benjamin J. Evans and Martijn Verburg
  • Ranking: I would definitely recommend this book

Originally, I wanted to write a complete review of this book but I found some really good reviews already available on the internet. What I would like to say is that this book is exactly what the title reads. If you want to be a good Java developer and you mean it, you should know all the information in this book. A great thing about it is that it has a very balanced level of details. The information are presented in a compact well understandable form without wasting the reader's time. So if you did not read it yet, go to the nearest book store or library.

2013/01/03

HashMap serialization issue

Today, we discovered an interesting behaviour in Oracle JDK 7 with my colleague. This also affects OpenJDK 7. There is a change in the implementation of the HashMap serialization. If you serialize and then deserialize a HashMap, two private fields are changed. The first is threshold and the second is table. While these changes do not seem to have any effect on the public behaviour of the class, it makes various testing a little bit harder.

For example, you developed a client/server application that exchanges some objects. These objects might hold some properties in a HashMap. To test the correctness of the communication channel, you send a serialized object from the client to the server. The server deserializes the object, changes an attribute and sends the serialized version back to the client. The client performs the same changes to its version of the object and serializes it too. Then the client compares the serialized byte arrays. With JDK 7 it finds them different and this is a problem in my opinion. Or do you find it a completely insane integration test scenario? I already found it in many projects so I suppose it is not that uncommon and bad.

A reproducer can be found at GitHub. I also logged an issue with Oracle. They are now about to review it. However, I suppose they are not going to fix the issue since it does not influence the public API. Who cares about testers...

2012/07/20

JBoss Technologies 1 in Czech

I would just like to bring your attention to my recent blog post on JBoss. The target audience is the Czech JBoss Community, so the article is in Czech only.

2011/05/17

Accessing ODBC from Java

Connecting to an ODBC database from Java can be a real nightmare. Most solutions suggest using a JDBC-ODBC bridge. So what are real possibilities here? Native JDBC-ODBC bridge by Sun/Oracle sun.jdbc.odbc.JdbcOdbcDriver. Well, there are some limitations like the number of concurrent connections and poor performance. I was not able to find any free (ideally open source) JDBC-ODBC bridge. There are multiple vendors but only one seems to have a de facto standard - Easysoft. They provide trial version of their bridge so you can try the solution before you buy it. Here we realized some troubles in Java Virtual Machine consuming too much memory. I do not want to blame the bridge. It was on a separate machine but we are not able to debug it and see how it works. So not being opensource killed Easysoft's chance to get a new customer.

After all I decided to write a small Java client that would be able to access an ODBC database. We needed just some basic querying capabilities anyway. But this is a little tricky, there is no ODBC communication protocol specification. Eventually, I decided to use unixODBC library using JNI. And here is beginning of the story.

First I designed a client for accessing the database. I had some previous ODBC API knowledge so I designed the client in order to write minimum code in C.

A design note: I failed passing database handles (type void*) between C and Java, so I created an array to store real handles in the C library and pass just an index to the array. This requires tha Java part to remember which handles have been used. There definitely exist a more sophisticated solution but I wanted to query an ODBC database at first. Also note that all data are returned as Strings for simplicity. There is also a shor main() method to test the client.

package org.marvec.odbc;

public class OdbcClient {
   
   private static SortedSet usedHandles = new TreeSet();
   private int handle;
   
   public native void connect(String connection) throws IOException;
   public native void execute(String statement) throws IOException;
   public native int getNumCols();
   public native ColumnMetadata getColMetadata(int col);
   public native boolean fetch();
   public native String getColData(int col) throws IOException;
   public native void freeStatement();
   private native void close();
      
   public OdbcClient() throws IOException {
      int i = 0;
      while (usedHandles.contains(i) && i <= 1024) {
         i++;
      }
      if (i == 1024) {
         throw new IOException("All handles are currently in use. Try to free some handles by disconnecting from ODBC.");
      }
      usedHandles.add(i);
      handle = i;
   }

   public void disconnect() {
      close();
      usedHandles.remove(handle);
   }

   public static class ColumnMetadata {
       public String name;
       public int type;
       public long length;
       public int digits;
       this.nullable = nullable;

       public String toString() {
          return name + ": " + type + "(" + length + ")" + "[" + digits + "]" + (nullable ? "*" : "");
       }
   }

   public static void main(String... args) throws Exception {
       System.loadLibrary(args[0]);
       OdbcClient c = new OdbcClient();
       c.connect("DRIVER={PostgreSQL64};DATABASE=myodbcdb;SERVER=localhost;PORT=35432;Uid=admin;Pwd=admin;");
       c.execute("select * from persons where person_id < 1000");
       System.out.println("Columns: " + c.getNumCols());
       for (int i = 1, j = c.getNumCols(); i <= j; i++) {
           ColumnMetadata meta = c.getColMetadata(i);
           System.out.println("Column " + i + ": " + meta);
       }
       while (c.fetch()) {
           for (int i = 1, j = c.getNumCols(); i <= j; i++) {
               System.out.print(c.getColData(i) + (i == j ? "\n" : ", "));
           }
       }
       c.freeStatement();
       c.disconnect();
   }
}

After compilation, I neede javah utility to obtain a C header file (.h).

javah -jni org.marvec.odbc.OdbcClient

Now the hard C part begins. I'm not a C guru and my compiler reports many warnings about my code. However, it compiles and works. First I copied org_marvec_odbc_OdbcClient.h to org_marvec_odbc_OdbcClient.c and added the shared handle storage to the header file as well as necessary includes. As you can see, we need to remember three different handles for each connection.

#include 
#include 
...
SQLHENV env[1024];
SQLHDBC dbc[1024];
SQLHSTMT stmt[1024];

You might find me wasting some memory but you know, in Java world, there is always enough memory... I will show you only some parts of the solution, link to a complete package is at the end of this post. The most difficult function is getting column metadata that requires creating a new Java object from C.

JNIEXPORT jobject JNICALL Java_org_marvec_odbc_OdbcClient_getColMetadata(JNIEnv *jnienv, jobject obj, jint col) {
    int h = getStaticHandle(jnienv, obj);
    SQLSMALLINT nameLength, dataType, decimalDigits, nullable;
    SQLULEN colSize;
    jstring jstr;
    char name[512];
    
    SQLDescribeCol(stmt[h], (SQLUSMALLINT) col, name, sizeof(name), &nameLength, &dataType, &colSize, &decimalDigits, &nullable);

    jstr = (*jnienv)->NewStringUTF(jnienv, name);

    jclass clazz;
    jmethodID cid;
    jobject meta;

    clazz = (*jnienv)->FindClass(jnienv, "org/marvec/odbc/OdbcClient$ColumnMetadata");
    cid = (*jnienv)->GetMethodID(jnienv, clazz, "", "(Ljava/lang/String;IJIZ)V");
    meta = (*jnienv)->NewObject(jnienv, clazz, cid, jstr, dataType, colSize, decimalDigits, (jboolean) (nullable == SQL_NULLABLE));

    return meta;
}

In some problematic methods I also check for errors using another utility library I mostly copied from Jinput project (see function throwIOException() for example).

JNIEXPORT void JNICALL Java_org_marvec_odbc_OdbcClient_connect(JNIEnv *jnienv, jobject obj, jstring conn) {
    SQLRETURN ret;
    jbyte *str;
    int h = getStaticHandle(jnienv, obj);
    char error[10240];

    jclass cls = (*jnienv)->GetObjectClass(jnienv, obj);

    str = (*jnienv)->GetStringUTFChars(jnienv, conn, NULL);

    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(env[h]));
    SQLSetEnvAttr(env[h], SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
    SQLAllocHandle(SQL_HANDLE_DBC, env[h], &(dbc[h]));
    ret = SQLDriverConnect(dbc[h], NULL, str, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);

    if (!SQL_SUCCEEDED(ret)) {
        extractError(dbc[h], SQL_HANDLE_DBC, error, sizeof(error));
        throwIOException(jnienv, "SQLDriverConnect failed with return value %d:\n%s", ret, error);
    }

    (*jnienv)->ReleaseStringUTFChars(jnienv, conn, str);
}

Now there are some dependencies in the C project. You must have installed the following libraries in your system:

  • unixODBC
  • unixODBC-dev
  • some ODBC driver for your target database like odbc-postgresql
  • libltdl
  • and some common C libraries that are likely to be already present on your computer: pthread, dl

Now you must configure ODBC to provide you the driver (see the first part of the connection string DRIVER=). This is done in /etc/odbcinst.ini and we can configure both 32- and 64-bit versions:

[PostgreSQL]
Description     = PostgreSQL driver for Linux & Win32
Driver          = /usr/lib/odbc/psqlodbca.so
Setup           = /usr/lib/odbc/libodbcpsqlS.so

[PostgreSQL64]
Description     = PostgreSQL driver for Linux & Win32
Driver          = /usr/lib64/odbc/psqlodbca.so
Setup           = /usr/lib64/odbc/libodbcpsqlS.so

To compile the C library I created a small Makefile:

CC=gcc
CFLAGS=-shared -fPIC -w -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux
PROJECT=org_marvec_odbc_OdbcClient

all: $(PROJECT).so

$(PROJECT).so: $(PROJECT).c
        $(CC) $(CFLAGS) util.c $(PROJECT).c -o $(PROJECT).so -lodbc -lpthread -lltdl -ldl
        ln -sf $(PROJECT).so libjavaODBC.so

clean:
        rm $(PROJECT).so libjavaODBC.so

Note the creation of a symbolic link. Java loads libraries on library path with standard name lib[name fo the library].so and only the library name is what you pass as an argument to System.loadLibrary().

Now to run the client just call:

java -Djava.library.path=. org.marvec.odbc.OdbcClient javaODBC

Feel free to download the complete source code at github. The code is provided as is, I do not take any responsibility for any damage it might cause to anybody or anything (including hardware, software, people, animals, etc). For instructions see JBoss Community document.

2010/06/26

Invalid signature file digest for Manifest main attributes

Because of some obvious reasons, security is a must when it comes to computers nowadays. I am not much into security but I had to deal with it anyway. Last couple of days I worked with signed JAR files, when my Java compiler suddenly said: "Invalid signature file digest for Manifest main attributes".

It was because some JAR files were not signed correctly since I needed to remove signatures and my automated tool for signatures removal was broken. Fine, but which files are in a bad condition? I was not able to make my compiler tell me. My class path was like 10kB of text and the day was almost over...

Signatures and certificates in a JAR file are in the META-INF directory. These are files with .SF, .DSA, and .RSA extensions. All one need to do to "unsign" a JAR file is to delete those files. Note that, some information are in MANIFEST.MF as well but it is not necessary to remove them until you want to sign the JAR file again.

It is pretty straight forward so what can be wrong? It was my bad, I assumed that all JAR files in my application use the same certificate file. I did not delete all .RSA files but just something like PRODUCT.RSA.

But it took me a while to realize what is wrong. And here is a command that can help you to recognize a broken JAR file:

find -name *.jar -exec echo {} \; -exec jarsigner -verify {} \;

It is definitely a pity that Java compiler (Sun JDK 1.6) does not print out the problematic file name.

2009/11/28

Image Analysis

Today, I needed to compute an average value of a function. The problem was that the function was a chart in a .gif image.

I run across a great application called ImageJ. It has a pluggable interface, many powerful functions, it is open-source and written in Java. The platform independent distribution has only 3MB.

I opened my image in the application, cropped the unnecessary parts, and used the magic wand to selected the area under the function line. Then I just clicked on measure and got the area of 69035 pixels (btw. this is the value of the integral). I divided the number by the width of the image and got 226. Now I subtracted 226 from the image height and looked at the y-axis for the average value - 8.7...

Disclaimer: ImageJ is being developed at the National Institutes of Health by an employee of the Federal Government in the course of his official duties. Pursuant to Title 17, Section 105 of the United States Code, this software is not subject to copyright protection and is in the public domain. So long and thanks for ImageJ!

2009/09/07

Performance testing: Load generator

Introduction

Performance testing is a wide term, so let me be more specific please: performance testing of a message oriented middleware from the client's point of view. A message oriented middleware can be an Enterprise Service Bus for instance. We tried several implementations - JBoss ESB, WSO2 ESB, and Mule ESB.

What does the "testing from the client's point of view" mean? It means that we don't care about internal processes of the ESB. We just care how long it takes to process our request. It reminds of integration testing in the classical V-Model.

Problem Definition

We were working in a team on the problem and after trying several load generators, we found out that there is none that is generic enough. We wanted to send various types of messages (e.g. JMS, SOAP, files...) in different ways (send all messages at once, find the maximum sustainable speed, run a long-term test...). Apache JMeter approaches the ideal but is still missing some features. Moreover, we experienced high results jitter over time. So we decided to write our own lightweight, easy-to-use load generator. Here are some basic requirements:

  • Stable results.
  • There must be a constant message inflow while received messages are being processed.
  • Messages must be generated by many concurrent clients.
  • Clients must run on remote machines not to influence results.
  • Speed should be measured on the client side for us not to affect the server.

Solution

Message Sender

First, there are different types of messages. So let's have an interface of a component that just sends a particular message.

public interface MessageSender {
  public void setProperty(String prop, String value);
  public void init(String address) throws Exception;
  public void close();
  public Serializable send(Serializable message, 
    Map properties) throws Exception;
  public MessageSender clone();
}

The component should be able to get configured with standard property/value pairs, initialize a connection to a given address, send a serializable message (e.g. a String), and close the connection. Moreover, it can clone itself for us not to have to configure each instance.

There are two important decision points. First, do you want MessageSender to be reusable - to be able to send more than one message? When you are careful enough, you should be able to achieve this. At least, we did not experience any problems with that.

Second, do you want your senders to be thread safe? This is a completely different situation, which is really hard to achieve and keep high performance. An example is sending of JMS messages. JMS session is not thread safe but it takes relatively long time to initialize. You might want to extend the interface and create a ThreadSafeMessageSender.

An example of an HTTPSender is shown below.

public class HTTPSender implements MessageSender {
  private URL url;
  private String method = "POST";

  public void setProperty(String prop, String value) {
    if ("method".equals(prop)) {
      method = value;
    }
  }

  public void init(String address) throws Exception {
    url = new URL(address);
  }

  public void close() {
  }

  public Serializable send(Serializable message, Map properties) throws Exception {
    HttpURLConnection rc = (HttpURLConnection) url.openConnection();
    
    // ... standard HttpUrlConnection usage ...

    return response;
  }

  @Override
  public MessageSender clone() {
    ...
  }
}

Message Generator

Next, there must be a message generator that uses message senders to generate messages in a given way.

public abstract class MessageGenerator {
  protected MessageSender sender;
  protected int threads = 1;

  public void setProperty(String property, String value) {
    if ("threads".equals(property)) {
      threads = Integer.valueOf(value);
    }
  }

  public void init(String address, MessageSender sender) throws Exception {
    this.sender = sender;
    this.sender.init(address);
  }

  public void close() {
    sender.close();
  }

  public abstract void generate(Serializable message, int count) throws Exception;
}

As you can see, an already configured instance of MessageSender must be passed to the MessageGenerator in the init() method. It is not a constructor because some configuration of the generator might be performed first in its descendants. This abstract generator supposes that the message sender is thread safe, because it uses just a single instance to pass all the messages through. Descendants might want to clone this instance in case it were not thread safe.

We used several new features of Java 6 to create a message generator that just sends all the messages to the server in a given number of threads. Let's first examine a sender task that is created per each thread. It uses shared AtomicInteger to keep track of actually sent messages.

public class SenderTask implements Runnable {
  private MessageSender sender; // shared sender
  private Serializable message; // message to send
  private AtomicInteger counter; // shared message counter
  private int count; //  number of messages for this thread

  public SenderTask(AtomicInteger counter, MessageSender sender, 
      String address, Serializable message, int count) 
      throws Exception {
    this.count = count;
    this.sender = sender;
    this.message = message;
    this.counter = counter;

    // expect sender's uninitialized clone
    this.sender.init(address);
  }

  @Override
  public void run() {
    try {
      for (int i = 0; i < count; i++) {
        sender.send(message, null);
        counter.incrementAndGet();
      }
    } catch (Exception e) {
      log.error(e);
    } finally {
      sender.close();
    }
  }
}

In the next listing, there is an implementation of the generate() method. No speed measurement code is included but the main goal here was to show the ExecutorService's usage.

@Override
public void generate(Serializable message, int count) 
    throws Exception {
  List<SenderTask> taskList = 
    new ArrayList<SenderTask>(threads);

  // Let tasks to initialize senders
  for (int i = 0; i < threads; i++) {
    taskList.add(new SenderTask(counter, sender.clone(), 
      address, message, perThreadMessageCount);
  }

  // Submit all tasks for completion
  ExecutorService es = Executors.newFixedThreadPool(threads);
  for (int i = 0; i < threads; i++) {
    es.submit(taskList.get(i));
  }

  // Wait for termination
  es.shutdown();
  boolean terminated = false;
  while (!terminated) {
    // output current state
    // take some sleep
    // updated 'terminated' variable
  }
}

As you can see, clones of the original sender are created for us not to have to take care of the thread safeness. Individual SenderTask instances are created in advance for all sender clones to get initialized. Then the instances are put in an ExecutorService and executed. While we are waiting for all threads to finish, we can periodically output current and overall throughput for instance.

Conclusion

This concept already demonstrated its value in real world scenarios. We were able to write various message senders and generators easily and quickly. Even though it may look simple, there are some factors you must take into consideration.

First is the warm up period of the server. You could either run the test several times and ignore a couple of first runs, or extend the generator to throw in some more messages and do not count them.

Second, always make sure that the client is able to generate messages several times faster than the server is able to process. Otherwise, you measure the client's performance, which is something you do not want probably.

2009/05/13

EJB3: Conscious Session Bean

Last week, I wanted to demonstrate @TransactionAttribute in a session bean using JBoss AS 5.1.0 GA and EJB3. Everything seemed pretty simple...

@Stateless
public class OmnipotentBean implements Omnipotent {
    @TransactionAttribute(REQUIRED)
    public String transactionRequired() throws SystemException {
        try {
            transactionNever();
            System.err.println("No exception occured - ERROR");
        } catch (EJBException e) {
            System.out.println("Expected exception - OK");
        }
    }

   @TransactionAttribute(NEVER)
    public String transactionNever() throws SystemException {
        ...
    }
}

As you can see, I wanted to show that calling a method with a transaction attribute set to NEVER from a method that already runs in a transaction throws an exception. But the exception was not thrown. How come?

Let's start from the client. What kind of object do we get from JNDI when we looked up OmnipotentBean/remote? It was neither OmnipotentBean or its interface. It was a dynamically generated class based on java.lang.reflect.Proxy, which handles all method calls and passes them to the server. You can call its method because it implements Omnipotent interface. Moreover, the call passes through a set of interceptors, which can perform additional work and setup the environment, inlcuding security and transactional interceptors.

The same applies at the server side. What is this inside transactionRequired() method? It is just a OmnipotentBean class instance, thus a simple POJO. We must lookup the EJB through JNDI to get a proxy object for transactional attributes to start working.

Another uncomfortable thing is that we cannot use dependency injection in our session bean to inject its proxy. Not having the bean initialized at the time of its initialization when dependencies are being injected, this is the cause.

So, are all the problems just JBoss AS's whims? What does the specification say? EJB3 - JSR-220 (file EJB Core, page 343):

The following subsections define the responsibilities of the container for managing the invocation of an enterprise bean business method when the method is invoked via the enterprise bean’s business interface (and/or home or component interface), or web service endpoint. The container’s responsibilities depend on the value of the transaction attribute.

Everything is all right. EJB container (i.e., the application server) must manage the invocations of bean's methods only when they are called via the business interface, which is the proxy object.

Maybe this is not suprising to you and you are right. It is very logical. Just bear in mind that a session bean must be conscious of its own business interface when invoking methods of its own.

2009/04/18

RichFaces and Background Gradient

I do not know whose idea it was. Maybe it is there just to demonstrate some advanced RichFaces' abilities but I (in all the humbleness) hate it. I am talking about the background gradient which is by default present at table headers and toolbars. The background is a dynamically generated image and its presence in a web page is caused by XML snippets like the following one (part of richfaces-ui.jar:/org/richfaces/skin.xcss).

<u:style name="background-image">
  <f:resource xmlns:f="http:/jsf.exadel.com/template" f:key="org.richfaces.renderkit.html.GradientA"/>
</u:style>

A friend of mine would call such a beatiful thing a funfair or a fly-by. Apart from the hardcoded gradient background I miss only one thing in RichFaces.

A scrolling text that blinks in Firefox and Opera.

It took me couple of hours to get over the problem, yet I'm not satisfied with either solution I found.

Solution no. 1: Override the default behavior

Your CSS style can be loaded later and override the background you are not satisfied with. This is even "oficially" recommended. The linked page speaks about rich:dataTable so I am adding my part for rich:Toolbar.

.rich-toolbar, .rich-toolbar-item {
    background-image:none;
    background-color:transparent;
}     

You can of course set more convenient background color. The big issue here is that you still have the gradient style configured and loaded by your browser, and the background image generated at the server.

Solution no. 2: Update richfaces-ui.jar

You can grep through all .xcss files inside richfaces-ui.jar and remove the gradient from whatever place you want. You get tinier CSS and less work on the server side. But you have to repeate the procedure every time you want to upgrade RichFaces version. And you also must be careful about your richfaces-ui-without-gradient.jar.

I like neither of the solutions. For my project I went with no. 1 and I hope that there will be a new gradient style to configure in my skin.properties: gradientStyle=NONE.

2009/04/09

TestNG and Group Filters

Recently I solved an interesting problem with test groups in TestNG. To describe the problem, let me describe a sample test class with three methods, which are included into two groups.

public class SampleTest {
  @Test(groups = { "groupA" })
  public void testMethod1() {
    System.out.println("1 in A");
  }

  @Test(groups = { "groupA", "groupB" })
  public void testMethod2() {
    System.out.println("2 in A, B");
  }

  @Test(groups = { "groupB" })
  public void testMethod3() {
    System.out.println("3 in B");
  }
}

Usually, TestNG is called using an Ant task like the following one.

<testng excludedGroups="..." groups="..." ... />

What methods can be executed with various groups and excludedGroups setting presents this table:

MethodsgroupsexcludedGroups
1groupAgroupB
1, 2groupA--
2, 3groupB--
3groupBgroupA
1, 2, 3----

This is pretty logical. But wait, there is a combination missing from that table. What about just the method 2, which is in groupA and groupB? To be honest, I did not find an easy way to achieve this. But there is a workaround. First, you must use an external configuration file for TestNG.

<testng classpathref="...">
  <xmlfileset dir="." includes="testng.xml"/>
</testng>

In this file, you can use Beanshell to enable/disable individual methods.

<suite name="TestSuite">
  <test name="SampleTest">
    <method-selectors>
      <method-selector>
        <script language="beanshell"><![CDATA[
          groups.containsKey("groupA") && groups.containsKey("groupB")
        ]]></script>
      </method-selector>
    </method-selectors>
    <classes>
      <class name="com.blogspot.qecafe.tests.SampleTest" />
    </classes>
  </test>
</suite>

The magic line in Beanshell will cause only methods in both groups to be executed.

There is yet another item missing - 1, 3 combination. You can run it in a similar way just like 2.

2009/04/07

Temptations of Software Engineers

Have you ever been tempted to use a technology just because of the technology itself? Was the technology such a fancy thing that you could not resist? Please do not do that! A result of your work would be barely usable in the real life. Do you know the superior Swiss knife with all the stuff inside? I am in doubt you could ever carve a little wooden ship for your son with it.
Let me tell you a true story of a software engineer and an application he developed.

Once upon a time, there was a guy who decided to learn Java and all its bright features, which brought the light on every programmer's possible problem. He chose a set of features that were most interesting to him including serialization, and multi threading. To be not all alone and to verify his code, he decided to take a community as a hostage. Let's inspect a couple of his mistakes.

First, serialization is good for remote method invocation, for sending objects over network, and even for storing small project configurations into a file. It should not be used as a primary data storage, since there are relational databases for such a purpose. If you wanted to be thread safe in a serialize-everything environment, you must keep all the objects in the memory and (de)serialize them only on an application start/shutdown. It is slow, complicated and inefficient way.

Second, multi threading is a powerful thing but it is like the fire - it can be very dangerous. Threads are not independent processes. You should be careful about them, especially if they are running third party code. Apart of that issue, the biggest problem was that Thread.stop() does not stop a waiting thread on all JVM implementations. It is not good idea to stick to an implementation detail. Later, Thread's methods stop(), suspend(), and resume() have become deprecated because it showed up that they are unsafe.

I could have continue here with similar cases but that should be enough to show what I meant by temptations. If the project were now buried deep in the binary scarp, everything was fine. Unfortunately, the community around it become large and the project is massively used nowadays. And the users must fight with those design issues hidden deep inside of it.

. .