Category Archives: java

JAXB and creating elements from schema types

Working in the Java EE arena usually mean plenty of integrations – with other modules, with client applications, with third party providers, etc. Today, integrations always imply XML, and XML means some sort of definition – XML Schema, RelaxNG or “here is an example and you can figure it out yourself”. Personally I like XML schema – it’s a standard and relatively easy to understand (I know some will argue on this point). The best part is the fact I can use it to create objects for my application and save all the boilerplate marshalling and unmarshalling code. If there is one thing I hate, is to write code that should have be written by the compiler.

My tool of choice in the last few years is JAXB 2. Again, simple to understand, simple to work with, relatively descent documentation and integration with maven. However, there is one nagging problem with JAXB. When I need an element to be the root element of a document, as well as a child element I go into a corner. The trivial thing is to define a type, and then define an element of this type, in the following manner:

<?xml version="1.0" encoding="UTF-8"?>
<schema>
<complexType name="SomeType">
<sequence>
<element name="first-name" type="string"/>
<element name="last-name" type="string"/>
</sequence>
</complexType>
<element name="some-element" type="tns:SomeType"/>
</schema>

Naturally, I want to have the following code to get the simple XML:

SomeType s = new SomeType();
s.setFirstName("David");
s.setLastName("Rabinowitz");
marshaller.marshal(s);

This should yield

<some-element>
<first-name>David</first-name>
<last-name>Rabinowitz</last-name>
<some-element>

Unfortunately, the generated code lacks one important annotation from the generated class – the @XmlRootElement annotation, which lets the JAXB to know that it can use this element as the root element of the XML, and let it know the name of the root element.
Apperently I’m not the only one who have encountered this problem. Once I’ve received an XML schema from a content provider whom I should have written the integration with, and the instructions were: “If you want the sample code to work, generate the classes using XJC, then go to classes X, Y and Z and add the @XmlRootElement annotation to the class”. I can’t say I was very happy with this.

However, in the current schema I design, I found a solution which is not as simple as I wanted it to be, yet it solves the problem. The definition of some-element was changed to inherit from SomeType and now it looks like this:

<complexType name="some-element">
<complexContent>
<extension base="tns:SomeType"/>
</complexContent>
</complexType>

The generated code is quite similar:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "some-element")
public class SomeElement
extends SomeType
{ }

Now, all I need to do replace the first line in the above code sample to:

SomeElement s = new SomeElement();

JMX remote monitoring on Linux

When running Java based application servers such as JBoss or Tomcat it is essential to monitor the status of the process – it’s memory consumption, threads and so on. In order to do that, Sun had introduced the JConsole application in Java 5, and now we have its successor visualvm.

In order to monitor the java process, you need to add the following system properties to the command line:

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

In the visualvm you just use the connection string host:9999.

However, sometimes the RMI listener listens to the wrong IP address, one which is inaccessible to the visualvm. Thanks to Pavel’s tip, I found a  way to overcome this is by adding the following parameters:

-Djava.rmi.server.hostname=$(hostname)
-Djava.rmi.server.useLocalHostname=true

Now it works like a charm!

For completeness, I’d mention you can secure the connection to the JVM, either by requiring user/password or by using SSL. If you are interested, please see this guide.

Live patterns: Switching to the visitor design pattern

For more than a two years now, I’ve been working on the WorldMate Live application. In its essence, it is built around the concept of managing itineraries, and on top of that, it provides plenty of services. The entire system consists of mobile applications, currently BlackBerry and SmartPhones, an Outlook add-in and my team’s part – the web application and the back end services. This intro came so I can describe one of my favourite design decisions we made early during the development, which proved to be very successful over time, and this is the usage of the Visitor design pattern. As you can see in the interface, each itinerary can contain five different types: Car Rental, Flight, Hotel, Meeting and Public Transportation. These types differ from each other in most of their attributes, so no wonder that algorithms that using them need to provide different behaviour for each type. A good example is the algorithm that decide what to display in the UI – the display of a meeting is very different from that of an hotel (register and see!) The traditional way (or C style) to do that is to have some thing like the following:

switch(item.type) {
case CAR_RENTAL: ...
case FLIGHT: ...
...
}

And the Java incarnation of this code also looks like this:

if(item instanceof CarRental) {
...
} else if(item instanceof Flight) {
...
} else ...

I’m sure that this looks awfully familiar to you. This code has three major problems to it:

  • It is very hard to spot places where one type is not handled – on purpose or by mistake. Since in most cases the actual logic spawns several lines of code it is hard to spot such cases.
  • In case there is a need to add a new type, we need to go over all the places where we need separate logic and add the special case. This is a tedious and error prone process. Furthermore, since it is easy to to forget to throw an UnknownItemTypeException in the end, is will be also easy not to get any exception in places the new type was forgotten.
  • The code is very cumbersome -there are large blocks of code which handle all types, and switch-like ifs (like above) are mixed with other logic control structures.

The solution we chose to all these is to use the visitor design pattern. Using implementations of an ItemVisitor solves these issues:

  • You must always implement all visitXXX() methods. If there’s no need for specific logic for a certain type, then the code clearly shows this by having an empty method. This also adheres to the single choice principle – one of the fundamental principles of software engineering.
  • When new types will be added, then by simply adding new visitNewType() the compiler will notify where all the new logic should be added – since existing visitors won’t have this method.
  • The code is cleaner – instead of having large code block, we have 1-3 lines (depends if we need to return a value from the visitor), and the actual logic is neatly organised into methods

JBoss, EJB3, Hibernate and DLL Hell

For the last year or so, I’ve been working on a project using JBoss and EJB 3.0. As this is a first, no wonder there were some technical difficulties along the way. This post is the first in a series describing the problems we had, and how we overcame them.

The original task was very simple: Let’s create a small application, demonstrating the usage of all the technologies, and start grow our application from there. Starting with running the tutorials coming with the JBoss EJB3 distribution we saw this problem:

--- MBeans waiting for other MBeans ---
ObjectName: persistence.units:jar=tutorial.jar,unitName=tempdb
  State: FAILED
  Reason: java.lang.RuntimeException: java.lang.NoClassDefFoundError:
          org/hibernate/MappingNotFoundException
  I Depend On:
    jboss.jca:service=DataSourceBinding,name=DefaultDS
  Depends On Me:
    jboss.j2ee:jar=tutorial.jar,name=ShoppingCartBean,service=EJB3ObjectName:
           jboss.j2ee:jar=tutorial.jar,name=ShoppingCartBean,service=EJB3
  State: NOTYETINSTALLED  I Depend On:
    persistence.units:jar=tutorial.jar,unitName=tempdb
--- MBEANS THAT ARE THE ROOT CAUSE OF THE PROBLEM ---
ObjectName: persistence.units:jar=tutorial.jar,unitName=tempdb
  State: FAILED
  Reason: java.lang.RuntimeException: java.lang.NoClassDefFoundError:
          org/hibernate/MappingNotFoundException
I Depend On:
    jboss.jca:service=DataSourceBinding,name=DefaultDS
  Depends On Me:
    jboss.j2ee:jar=tutorial.jar,name=ShoppingCartBean,service=EJB3

This was really puzzling. How can JBoss wants us to deploy a small persistence jar, when it can’t satisfy it’s dependencies? Like in most of these cases, it appeared it was another case of DLL hell. The short solution, for JBossAS 4.0.4GA, is as follows: update the modification time of the files (I did it using “touch”, via cygwin), and then run the at install file of the EJB3 package. I might warn you in advance that the rest of this post is full with all the nagging version differences that gave DLL hell its name…

After searching the hibernate API and subversion repository, I’ve found that the relevant class (org.hibernate.MappingNotFoundException) was added to Hibernate in version 3.2.0.cr3 or 3.2.0.cr4. The version that comes with the EJB3 RC9 is cr4. The version I had in the JBossAS (4.0.4GA) is cr2, which lacked that file.

The EJB3 ant installer should have copied the new version to the JBossAS, but unfortunately the modification time of the JBossAS jars was newer than the EJB3, so ant has ignored the copy request.

So this is how the solution works – using “touch” updates the modification time of the EJB3 jars. This makes them newer than those th JBossAS has and then they were copied correctly.

By the way, if you are using JBossAS 4.0.5, you probably don’t want to do this, but rather keep the original Hibernate jars that came with the JBoss. The reason is that JBossAs 4.0.5 contains the final version of Hibernate (3.2.0.ga), which is newer than the one bundled in the EJB3.

Seam @DataModel Factories

Seam has a great feature called DataModel. In a nutshell, you provide a List, and seam populates a dataTable for you. The great thing about it, is you can provide an injection point marked as DataModelSelection, and when the user clicks on one of the dataTable rows, you have the selected object.

Theoreticaly, you can put the @DataModel annotation on a method or on a field. However, as it turns, by declaring a method as DataModel it will be called for each use of the returned list. This can cause big performance issue, as the list generation often requires fetching the data from back end systems such as the database. The sumple solution for this is to declare the list as a member of the backing bean, and add a factory method for it. In this case, the factory method will be called only when the @DataModel List is null.

For code example, have a look here.