Archive for July, 2010

JCommander 1.4

They say that a Java framework is not complete until it provides factories, and since it’s something that JCommander was still lacking, it had to be fixed.

Introducing JCommander 1.4.

Here is what’s new:

  • You can now specify default values in a more flexible way than at field declaration time (documentation).
  • You can use string converter factories instead of specifying converter classes on each @Parameter annotation (documentation).
  • The usage is now prettier:
    Usage: <main class> [options]
      Options:
        -debug          Debug mode (default: false)
        -groups         Comma-separated list of group names to be run
      * -log, -verbose  Level of verbosity (default: 1)
        -long           A long number (default: 0)
    
  • Many bug fixes and a more clever option parsing to cover odd cases.
  • This release actually contains more features but I’m not telling.

All the goodness available at the usual place. Operators are standing by, order now!

Now, *this* is a feature that gets me excited about Firefox 4

App Tabs in Firefox 4 Beta 2 « Alex Faaborg.

Local message bus

Recently, I started wondering how I could improve the TestNG listener architecture.

TestNG exposes a lot of different listeners, which users can specify before starting a test run (using either of the command line, ant, Maven, testng.xml or programmatically).

These listeners tell you whenever:

  • A test succeeds, fails or is skipped.
  • A test method is about to be called and when it returns.
  • A configuration method starts or finishes (there are five types of each: suite, test, class, method and group, and you have a before and an after event for each).
  • A reporter should be notified to update its results (either at the end of the suite run or after each test methd).

All these listeners are captured by different interfaces and they have evolved somewhat organically over these past six years as the needs and requests emerged, showing some overlap in functionalities and also requiring the awkward interface evolution that Java imposes (exhibit A and exhibit B).

One possible solution to such a problem is a message (or event) bus.

Message buses have been around for a very long time and most of my PhD thesis revolved around their usage and their impact on distributed applications. I even wrote one for my PhD called Koala Talk. This was around 1993, almost twenty years ago.

The de facto standard in the Java world is the JMS specification, which has been implemented in many products such as ActiveMQ or RabbitMQ. Both the specification and implementations have been battle tested and proven to be of great usefulness for today’s software.

However, JMS is overkill for what I need to do. First of all in terms of functionalities, but also more simply because I need a local software bus, one that will always be passing messages within the same JVM. No network is necessary.

The message bus model brings a lot of simplification to a listener heavy framework such as TestNG. Instead of having to decide which interface and which method are applicable when, all TestNG needs to do is publish events as a test run is progressing. Where these events get handled and who they eventually reach is resolved outside of the TestNG engine.

Another benefit is that looking at the system in terms of events will allow to remove quite a bit of overlap. For example, in TestNG, you can be notified both when a suite finishes and when your reporter should start doing its work (generating reports). Most of the time, these events coincide.

I started sketching out what such an API could look like and I came up with the following very early draft:

public class App {
  @Subscriber
  public void event1(NotifyEvent ne) {
    System.out.println("event1: " + ne);
  }
}
MessageBus mb = new MessageBus();
mb.register(new App());
mb.post(new NotifyEvent("notify"));

Receivers describe the kind of events they are interested in and publishers simply post these events. With these ideas in mind, I started looking around to see if anything like this exists and I quickly came across EventBus, by Michael Bushe.

EventBus turns out to be remarkably close to what I had in mind, including annotation support and type based dispatching. EventBus also supports all kinds of other mechanisms, some I had in mind (string based publishing with regexp matching, event inheritance) and a few others I didn’t think of (vetos).

EventBus seems to be very extensive, very well designed and tested (nice job, Michael!), but probably too big for what I need. It also contains quite a few ties to Swing because it apparently started as a support library for Swing applications that publish events (something that Swing developers have to deal with all the time). Admittedly, there is a portion of EventBus that seems to be graphic independent, but I haven’t been able to really understand its full extent and whether it’s possible to carve it out at all (I have no interest in dragging in Swing dependencies).

Interestingly, it’s the only library of that type that I was able to find, so before I dig further, has anyone heard of a framework allowing the kind of simple intra JVM publish/subscribe functionality I’m looking for?

JCommander 1.3

I just released JCommander 1.3, here are the new features:

  • @ResourceBundle is deprecated and replaced with @Parameters:
    @Parameters(resourceBundle = "MessageBundle")
    public class ArgsI18N2New {
      

    I had to deprecate @ResourceBundle because I needed a more general annotation in order to implement the next new feature.

  • You can now use different separators for your options:
    java Main -log:3
    

    or

    java Main -level=42
    

    You define the separator with the @Parameters annotation:

    @Parameters(separators = "=")
    public class SeparatorEqual {
      @Parameter(names = "-level")
      public Integer level = 2;
    }
    
  • Parameters can now be hidden, in which case they will not appear in the usage:
    @Parameter(names = "-debug", description = "Debug mode", hidden = true)
    public boolean debug = false;
    
  • The usage output is now sorted alphabetically and cleanly aligned:
    Usage: [main class] [options] list of files
      Options:
        -b, --bonjour             enable Bonjour.
        -e, --export-preferences  export preferences into the given file.
        -F, --flush-preferences   flush gui preferences.
        -h, --help                show this help.
        -i, --import-preferences  import preferences from the given file.
    

Download either directly or with Maven:

    
    	com.beust
    	jcommander
    	1.3
    

Tags:

Firefox’s “Tab Candy”: pretty, but…

I’m not a big fan of Firefox’s latest experimental feature “Tab Candy” for a couple of reasons.

First, I don’t think that having an application reinvent its own window management system is a step in the direction of better usability. Whatever operating system you are using, it’s already difficult to navigate through windows efficiently as it is, but after some time, you become reasonably proficient with it. And now, you find yourself having to learn yet another window management paradigm, with shortcuts that are by definition different from the ones you are used on the desktop, and a space and interaction logic that is going to be subtly different from the OS.

Second, I tend to use the keyboard to select my windows a lot more than the mouse, so functionalites like Exposé are of no use to me. Tab Candy seems to be no different.

What I really need is an extension that lets me switch to a tab by typing a few letters from either its title or its content. Just now, as I was starting to write this entry, I found myself having to find the article I linked above. I have currently about ten Firefox windows open and each of them has anywhere between one and ten tabs. Finding the correct window required a few Alt-Tab and quite a few Alt-~. And even then, the correct window popped up on my screen several times but I missed it because the tab I was looking for was the fourth in in a group of ten.

What would have been ideal: a text box where I can type “candy” and a drop down containing all the tabs that match the string I just type.

I’m aware of a few Chrome extensions that do this but all of them open a new window when you select the tab, instead of just taking you to the existing one, which defeats the purpose of the idea since it loads the page again and loses the position you were last reading.

Please let me know if you know of any extension that accomplishes what I’m looking for (ideally on Firefox).

MacPaint source code

Apple gracefully donated the source code of MacPaint and QuickDraw to the San Jose Museum of Computer History. For those of you who don’t want to bother with downloading and unzipping, here are the full sources.

JCommander 1.1

Version 1.1 of JCommander is now available, here are the new features:

Type converters

By default, JCommander parses the command line into basic types only (strings, booleans, integers and longs). Very often, your application actually needs more complex types, such as files, host names, lists, etc… You can now write your own type converters by implementing the following interface:

public interface IStringConverter<T> {
  T convert(String value);
}

For example, here is a converter that turns a string into a File:

public class FileConverter implements IStringConverter<File> {
  @Override
  public File convert(String value) {
    return new File(value);
  }
}

Then, all you need to do is declare your field with the correct type and specify the converter as an attribute:

@Parameter(names = "-file", converter = FileConverter.class)
File file;

JCommander ships with a few common converters (e.g. one that turns a comma separated list into a List<String>.

Simple internationalization

The new @ResourceBundle annotation lets you specify the bundle to be used on your parameter class itself. After this, JCommander will use the default locale to resolve your string:

@ResourceBundle("MessageBundle")
public class ArgsI18N2 {
  @Parameter(names = "-host", descriptionKey = "host")
  String hostName;
}

Password parameters

If one of your parameters is a password or some other value that you do not wish to appear in your history or in clear, you can declare it of type password and JCommander will then ask you to enter it in the console:

public class ArgsPassword {
  @Parameter(names = "-password", description = "Connection password", password = true)
  public String password;
}

When you run your program, you will get the following prompt:

Value for -password (Connection password):

You will need to type the value at this point before JCommander resumes.

Installation

JCommander is available either directly or from Maven:

    
      com.beust
      jcommander
      1.1
    

New features in JCommander and Maven availability

I received a good amount of feedback about JCommander, and I’ve been adding a few functionalities these past few days:

  • Support for multiple definition classes. Christian Gruber pointed out that it might be nice to not be restricted to just one class when you declare all your @Parameter fields. For example:

    ArgsMaster.java

    public class ArgsMaster {
      @Parameter(names = "-master")
      public String master;
    }
    

    ArgsSlave.java

    public class ArgsSlave {
      @Parameter(names = "-slave")
      public String slave;
    }
    

    You then pass these objects when you create your JCommander instance, which will collect all the parameter definitions from both objects.

    ArgsMaster m = new ArgsMaster();
    ArgsSlave s = new ArgsSlave();
    String[] argv = { "-master", "master", "-slave", "slave" };
    new JCommander(new Object[] { m , s }, argv);
    Assert.assertEquals(m.master, "master");
    Assert.assertEquals(s.slave, "slave");
    
  • Support for required. For simple applications, you can just declare @Parameter(required = true) and JCommander will enforce that all such parameters are assigned a value (example).
  • Internationalization. You can now use the standard Java resource bundle mechanism to write the descriptions of your options and have JCommander automatically use the translated strings (example).
  • Parameters that take more than one value (arities). This functionality allows you to parse command lines such as:
      java Main -pairs slave master foo.xml
      

    Here, the parameter -pairs needs the next two arguments (example).

All these features are now available in JCommander 1.0, which Maven users can download automatically with the following dependency:


  com.beust
  jcommander
  1.0

Announcing JCommander 1.0

import com.beust.jcommander.Parameter;
public class JCommanderTest {
  @Parameter
  public List<String> parameters = Lists.newArrayList();
  @Parameter(names = { "-log", "-verbose" }, description = "Level of verbosity")
  public Integer verbose = 1;
  @Parameter(names = "-groups", description = "Comma-separated list of group names to be run")
  public String groups;
  @Parameter(names = "-debug", description = "Debug mode")
  public boolean debug = false;
}

Recently, I got tired of having to handle command line parsing manually. I took a look at existing frameworks and all the ones that I found (JOpts, JArgs, commons-cli) suffered from the same limitations that I was trying to avoid: they barely cut down on the boiler plate code and they are not very type safe.
So I came up with my own framework, which I called JCommander.
The snippet of code above should give you a pretty good idea of what JCommander looks like, and if you need more information, just head over to the main site. I have already integrated JCommander in TestNG and it has already reduced the code base to handle this simple task significantly.
Let me know what you think.