Remotely accessing ActiveMQ Java Management Extensions on a shielded server

In this post I will describe how I solved my problem with setting up Java Management Extensions (JMX) on a remote ActiveMQ instance that wasn’t aware of its WAN IP address and had at least one firewall to pass through. This was not just a simple matter of remotely accessing the JMX server, it got a bit more complex. Continue reading

Sharing Comparable properties with generics in Java

What if you need to develop some software to compare houses to each other? A client found a nice Mansion and needs to see a list of similar buildings and the idea is that if he likes a Mansion he won’t like a Flat. So even if both have four rooms and a kitchen, they are not comparable at all. Then how do you implement Comparable in Java 5 and up?

The first thing you’d think of would be to write an explicit version for each instance, but they are all houses and all have rooms. So you might as well create an AbstractHouse class to create a compare function that compares the generic parts of an house. Let’s just focus on the comparison on the number of rooms.

Using the following code for your AbstractHouse will ensure that Mansions can only be compared to Mansions and Flats only to Flats, even if you ignore the generics in your code.

public abstract class AbstractHouse<T extends AbstractHouse> implements Comparable<T> {

    private int noOfRooms;

    public int compareTo (T o) {

        if (!getClass ().isInstance (o))
            throw new ClassCastException ("can't compare " + getClass ().getCanonicalName () + " to " + o.getClass ().getCanonicalName ());

        return this.noOfRooms - other.noOfRooms;
    }
}

As you can see, line 1 locks in the generic part of the Comparable interface, but in case you aren’t really using generics the isInstance check at line 7 will cause a ClassCastException to be thrown. Throwing a ClassCastException is conform to the Comparable interface which states that one can be thrown “… if the specified object’s type prevents it from being compared to this object.” What is left is defining the Mansion class as follows.

public abstract class Mansion extends AbstractHouse<Mansion> implements Comparable<Mansion> {
}

Although I am not sure of the necessity of explicitly stating the Comparable in the class definition, it seems rational to do so. It’s quite possible that the Comparable interface on a super class doesn’t have to mean that all subclasses share the same feature by inheritance, the JavaDocs aren’t clear on this and being explicit about it isn’t harmful.

Gimme everything you got slashes

Today I discovered a new bug. No, not the insect kind. It was a programming error. To be more specific, one that only showed up after fixing another one. Somehow using ‘//whatever’ as an XPath query on any node in a Document will give you all the nodes that match from the Document root. That’s because you said ‘//’, it means ‘I-don’t-know-where-it-is-but-I-want-it’.

Normally I would invoke it on the root of a XML document, so no problem there. But processing a collection of parts in a collection of parts will cause some problems. If you already know about the structure , then there is no need for the gimme-everything-you-got slashes!

Quick dumping of java object properties

When you are programming in Perl there are some nice modules like DDump and DataDump that allow you to do some inspection on your values. It’s useful and probably often used during hacking. Making the transition to Java while still clinging to that way of working might give you some hurdles. For instance, how to get those values. If the toString method is insufficiently implemented to your tastes, but you can’t change it, then you either have to write your own code or dig deep in the Java API. Both quite time-consuming.

The solution is to temporarily make use of either the jYaml library or the java JSON implementation of json.org. The first requires your classes to confirm to the JavaBean specs, which means having a constructor without parameters, setters and getters. The latter just requires an object with getters. In both cases the information you will see is the information the object will expose to the outside, internal state is not available. Should you want internal state then making a dump of the heap seems the only possible option when you are not using an IDE’s debugger.

Using jYaml to dump your object is as easy as doing Yaml.dump(someObject). This will get you a String object containing a Yaml structure including line-breaks. For the JSON implementation using new JSONObject(someObject).toString() to get a String representation. Using toString(int) will give you a formatted JSON structure, with the value of the int being the indent width.

Globally excluding commons-logging

Today I solved a long-lasting annoyance of mine, that lots of Java libraries in the Maven2 repository have a (transitive) dependency on Java Commons Logging (JCL). I prefer to use SLF4J instead, using JCL over SLF4J as implementation of the JCL API. Up till now, or actually 5 minutes ago, I had to do the RSI inducing task of using exclusions on every dependency which transitively depends on JCL. Not entirely error-proof, since forgetting to exclude it on even one dependency can horribly… mess up your day 🙂

Making yet another probably fruitless attempt at finding a solution to this annoyance, I happened to stumble upon a blog post of James Lorenzen. The solution there in part deals with my real problem, not wanting to use a transitive dependency at all but ignoring the bugger. The proposed, and working, solution is to use a scope of provided in your main POM which will root out the problem in sub projects as well. As mentioned, no more of that particular dependency in your distribution or whatever.

This is only part the problem in the case of JCL; I want it entirely out of the picture in my classpath. Here knowing the (dis)advantage of order in a classpath comes in. Of all classes with the same name in the same package on the classpath the classloader will load only the first one, ignoring the others. So how do we get the JCL stuff at the end of our classpath in Maven? Simply by adding it as the last “dependency” in your POM. Yes, not much to it actually.

This revelation really shortens my future POM files, especially in cases where my application consists of frameworks which are split up in many components all depending on that same logging library.

Generics are weird, or I am weird

Yesterday, late afternoon, I stumbled across a compilation problem for one of my unit tests in Java. More specifically, compilation in Eclipse seemed to work fine but using Maven2 and the java compiler included in version 1.6.0_14 it complained about not being able to find the proper method.

Given the two classes below (modified for brevity, of course):

import java.util.*;

public class Foo<t> {
   private List> children = new ArrayList  ();

   public List> getChildren() { return children; }

   public Foo addChild(Foo child) { children.add(child); }
}
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.*;

public class FooTest {
   Foo parent, child;

   @Before
   public void setUp (){
      parent = new Foo ();
      child = new Foo ();
      parent.addChild(child);
   }

   @Test
   public void childAdded(){
      assertThat(parent.getChildren(), hasItem(child));
   }
}

For some reason it seems that omitting the type for Foo at line 7 makes Java drop the type of the getChildren method. The compiler will infer the return type of that method as a List (no generics). The type of the hasItem method from the hamcrest matchers, in line 18, is typed as Matcher. The result, during compilation the compiler will complain about line 18 in the test class. My current settings in Eclipse show this unchecked invocation as a warning. Nevertheless it compiles and runs. The standard Java compiler is very strict in this matter.

The quick solution is simple, just add a type to line 7 or do a cast at line 18. Doing both is overkill, but works too. Adding the type at line 7 is the best choice, because that way there is no need to explicitly cast every call to getChildren where this problem occurs.

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.*;
import org.junit.*;

public class FooTest {
   Foo <Object> parent, child;

   @Before
   public void setUp (){
      parent = new Foo ();
      child = new Foo ();
      parent.addChild(child);
   }

   @Test
   public void childAdded(){
      assertThat((List<Object>) parent.getChildren(), hasItem(child));
   }
}

There might be a way to avoid this inconvenience by some simple changes to the Foo source code, changes I haven’t discovered yet. If there are any then I will find it!