Archive

Archive for the ‘Java’ Category

Bye bye XMLGregorianCalendar (part 2)

Change generated java classes with an XJC plugin.

In the previous post on ‘Bye bye XMLGregorianCalendar‘ I wrote about how you can influence the (un)marshalling of xml to java objects by adding an XmlAdapter to the classpath and an XmlJavaTypeAdapter annotation to a field in the java class. This technique works fine when you are actually writing the java classes your self, but: We don’t do that very often.  One of the main features of XML is that it can be validated against a schema, a contact which defines the valid options and structures with the XML. Most of the times, when we work with XML, there is a schema availabe, either as an standard defined for an industry / product or as part of the contract of a webservice. We can leverage the XSD (XML Schema Definition) to generate Java objects, which represent the elements in XML.

As a part of JAXB, the Java SDK provides ‘xjc’, a Binding Compiler also known as an Xml-to-Java-Compiler. When running the xjc command you need to specify the location of the schema and it will generate a set of appropriate java classes for you. By default, the XJC binding compiler strictly enforces the rules outlined in the Compatibility chapter of the JAXB Specification, which will result in you having fields of the type javax.xml.datatype.XMLGregorianCalendar in your classes. :-(

We don’t want that: We want to use DateTime of JodaTime as the type for our date fields.

By using the “-extension” switch of the xjc command, you are able to influence the process of java generation by activating custom JAXB Vendor Extensions. There are common extensions publically available, but none of those helps with replacing the XMLGregorianCalendar by properly annotated DateTime fields. Therefor you should write your own extension as an xjc plugin.

Writing a custom XJC Plugin.

So we are going to implement our own JodatimeJaxbPlugin, which will change the type of all date fields to DateTime and add the proper XmlJavaTypeAdapter-annotation to those fields. Implementing such an plugin is quite easy, since you just have to extend the com.sun.tools.xjc.Plugin and implement 3 abstract methods.

  1. String getOptionName(), which specifies by which command line argument value this plugin will be triggered. The default conventions is to start your option name with a capital ‘X’ to mark it as custom. For the JodatimeJaxbPlugin we use: ‘XuseJodatime’
  2. String getUsage(), which should return a description of this add-on.
  3. boolean run(Outline outline, Options opt, ErrorHandler errorHandler). The XJC compiler will do it’s internal stuff and then invoke this method to allow the plugin to tweak some of the generated code. The generated code is provided as the ‘outline’ of the generated classes.

The generated code by the XJC compiler is being represented in a com.sun.codemodel.JCodeModel, which allows access to the outlines of generated classes and fields. Our implementation of the plugin iterates over all generated classes, finds the fields within those classes of the type XMLGregorianCalendar and replaces those fields by an appropriate DateTime variant. The JCodeModel API doesn’t allow us to change the type of a generated fields, so we need to remove the old fields and add them again with the proper type. In that process we do want to preserve all metadata (Annotations) of the original fields and of course the getters and setters for those fields should be replaced as well, since the return type and parameter type will changes.

In order make the plugin available to the xjc compiler it has to be on the classpath and it needs to use the ServiceLoader API to register the plugin. Adding a simple text file in META-INF/service-directory with the name ‘com.sun.tools.xjc.Plugin’ and writing the fully qualified class name in that file is sufficient to register the plugin.

Running xjb from maven with the plugin

In order to trigger the custom plugin when the XJC compiler is being run from maven, you need to pass along the options to enable the extension and add the plugin to the classpath. The following sample snippet shows how to configure the maven-jabx-plugin for a custom plugin.

<plugin>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <version>0.8.1</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <extension>true</extension>
    <schemaDirectory>src/main/resources/xsd</schemaDirectory>
    <args>
      <arg>-XuseJodatime</arg>
    </args>
    <plugins>
      <plugin>
        <groupId>nl.iprofs.util.ws.jaxb</groupId>
        <artifactId>jodatime-jabx-plugin</artifactId>
        <version>1.0.0</version>
      </plugin>
     </plugins>
  </configuration>
  <dependencies>
    <dependency>
      <groupId>nl.iprofs.util.ws.jaxb</groupId>
      <artifactId>jodatime-jabx-plugin</artifactId>
      <version>1.0.0</version>
      <scope>runtime</scope>
    </dependency>
  </dependencies>
</plugin>
Categories: Java Tags: , , , , ,

Character Encode your source

09/05/2012 1 comment

When writing source code in your project, you’re always simply writing text and when you’re writing text you are saving this text on your disk in a certain encoding. This is a subtle field in which mistakes are easy and can lead to interesting side effects.

In our project we’ve recently moved from JDK 1.5 to JDK 1.6 and while local builds worked fine, the build server (running on Linux) started complaining:

“Unmappable character for encoding UTF-8” Read more…

Categories: Java Tags: , ,

The art of testing

In a few other posts on this blog I talked about the importance of unit testing and Test-Driven Development (TDD).

TDD helps us to ensure we’ve covered everything in our system by tests. Sure thing if you never write more production code than to satisfy a failing test, you’ve always covered all your production code by tests.

But how do we write a good suite of tests? How do we ensure that our tests help us maintaining the system? And remember, in agile development maintenance starts after the first successful compilation. Read more…

Categories: Java Tags: , , , , ,

Captcha’s in Wicket

In this post I’ll describe how to add a captcha to your web application with Wicket. A captcha is a a type of challenge-response test used to ensure that the response is generated by a person. Adding one thwarts bots sending a large amount of filled in forms to be stored.

This article deals with the best known one: an image with a series of characters and an input field to which the user must fill the characters of the image. First I describe how to do this, using the captcha component that is shipped with Wicket. After that I describe how to add the well known recaptcha. Read more…

Categories: Frontend, Java Tags: , ,

Spring validations, resolving arguments for errors

Using spring web mvc and the spring tags. it is easy to show i18n errors. However, what if you want to pass in parameters to your messages? For instance if you have a general message for a required field that is not set, you don’t want to have a message for each required field, but a general message with a place holder for the name of the field that is missing.
Read more…

Categories: Java Tags: , ,

Twitter 406

Integrating with social sites, such as twitter, seems to be so easy, and it actually can be, once you get the configuration set up correctly. Last day however, I spend most of my time trying to hunt down a 406 error code when trying to login using a twitter account. According to the twitter site I have to :

  • Think of a name for my application, well that was not too hard
  • Enter a description
  • Tell on which domain your twitter application will be hosted, but you can enter a placeholder for this if you don’t know that yet, or want to test

And then you should be set and ready to go. Read more…

Categories: Cloud, Java Tags: , ,

Legacy code: treat it with silk gloves

15/02/2012 3 comments

Legacy code is tough to deal with. It may be the toughest thing we have to deal with in our everyday jobs.

Before we start, let’s align our definition of what legacy code is. Legacy code is untested code. Legacy code may be old, but not necessarily. Unfortunately some projects are actively producing legacy code.

Most programmers have to work with legacy code frequently. Even worse, they often must make changes in the legacy code. They must fix bugs in the legacy code, or change it to implement new features. At the end of last October I started working on a project that at the time, fully consisted of legacy code. I won’t share any specific details about that client and their projects, but I like to share how we work with the legacy code. Read more…

Categories: Java Tags: , , ,

Bye bye XMLGregorianCalendar (part 1)

13/02/2012 1 comment

Introduction.

We all know that working with dates in the Java language isn’t perfect, at least when you just look at the standard JDK. Not only is more then half of them methods in java.util.Date deprecated, but in order to get the Date of a java.util.Calendar you have to use the getTime() method. So when the base object aren’t that well to start with, things can only get worse when you start to mix in more technologies like XML.

When you are getting started with marshalling and unmarshalling java objects to XML you’re bound to run into the javax.xml.datatype.XMLGregorianCalendar. Did you ever try to get the Date value for a field unmarshalled from XML and wrote the following code:

Date date = xmlGregorianCalendar.toGregorianCalendar.getTime();

Why isn’t an XMLGregorianCalendar a GregorianCalendar just like a ArrayList is a List or a HashMap is a Map?

Oke, some smart people discovered these problems as well and started to specify a new Date and Time API (JSR 310).
Their idea are great although an anwser in the original JSR does give me some worries:

2.11 Are there any internationalization or localization issues?
No issues are expected.

In my opinion internationalization and localization are the major issues when working with dates and times, but hey, that’s propably just me.

So the expert group started on 13 februari 2007 and finished the early review on 28 march 2010.
I’m really wondering in which version of the JDK this well be included.
And of course once this has been introducted into the JDK: How long will it take to get it supported as the default datatype for  XML dates?

Solution.

Fortunately there is already a solution available: Joda-Time.
With it’s DateTime, Period, Interval and Duration objects it provided a mature, easy to use and comprehensive feature set.

There is only one slight problem: JAXB doesn’t know anything about Joda-Time and it’s DateTime object.
By default fields in an XML-file with a xsd:datetime type will be unmarshalled to an XMLGregorianCalendar.

In various projects I have seen DateConverter utility classes for conversion from and to the Joda-Time DateTime object.
Wouldn’t it be nice if you just could use the DateTime field and have the conversion be done as some form of ‘custom marshalling‘?
But wait: you can! The JAXB API specifies an XMLAdapter, which “Adapts a Java type for custom marshaling

What we need is an XMLAdapter, which allows us marshal and unmashal between a ValueType and the BoundType.
The ValueType is some class, which JAXB knows how to handle out of the box (Strings, Lists or an Calendar and the BoundType is some type that JAXB doesn’t know how to handle. The Adapter will specify how transform from one type to the other.

So I’ve written a DateTimeAdapter, which unmashals from a Calender to DateTime and marshals a DateTime to a Calendar.

public class DateTimeAdapter extends XmlAdapter {

	@Override
	public DateTime unmarshal(Calendar calendar) throws Exception {
		return new DateTime(
			calendar.get(Calendar.YEAR),
			// Correct for the difference between Joda DateTime
			// and JDK Calendar.
			calendar.get(Calendar.MONTH) + 1,
			calendar.get(Calendar.DATE),
			calendar.get(Calendar.HOUR_OF_DAY),
			calendar.get(Calendar.MINUTE),
			calendar.get(Calendar.SECOND),
			calendar.get(Calendar.MILLISECOND),
			DateTimeZone.forTimeZone(calendar.getTimeZone()));
	}

	@Override
	public Calendar marshal(DateTime v) throws Exception {
		Calendar calendar = Calendar.getInstance(v.getZone().toTimeZone());
		calendar.setTime(v.toDate());
		return calendar;
	}

}

Now the tricky part: You have to tell the XML (un)marshaller that it should use the custom adapter for mashalling certain fields in your objects.
But as you propably could have guessed: the JAXB-API provides a solution for that as well:
Just add an XmlJavaTypeAdapter annotation to the field in your object and the Marshaller and Unmarshaller will invoke the Adapter during the process.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "book", propOrder = {
    "author",
    "title",
    "publicationDate"
})
public class Book {

    @XmlElement(required = true)
    protected String author;
    @XmlElement(required = true)
    protected String title;
    @XmlElement(required = true)
    @XmlSchemaType(name = "date")
    @XmlJavaTypeAdapter(nl.iprofs.util.jaxb.adapter.DateTimeAdapter.class)
    private DateTime publicationDate;

    // Getters and Setters
    .....

}

Part 2: WsImport, Maven and XJC.

In the next blog about this topic I’ll dig into the topic of WsImport with Maven and XJC (XML to Java Compiler) which is being using in generating classes for webservices based upon a WSDL and Schema. If some generator is going to generate the java classes for the SOAP service, I want it to generate fields as DateTime objects and annotate them with my XMLAdapter.
Sound easy, but of course it isn’t just that.

Dependency Injection with Spring

Dependency injection is hot, and Spring Framework is one of the most popular frameworks that facilitates in dependency injection. Why is dependency injection so hot? If almost every programmer is using it, there must be a very good reason.

And there obviously is. The great thing about Object Orientation is polymorphism. Through polymorphism we can depend on abstraction at compile time, and at the concrete implementation at runtime. This is called dependency inversion; we invert the direction of our dependencies. It promotes decoupled systems and greatly reduces compile time, too some extend even in Java. And this is why everybody is so excited about dependency injection; it facilitates dependency inversion.
Read more…

Improving CountdownLatch example from JDK-apidocs

Some time ago I discussed a use case for CountDownLatch, which was a thread safety issue.
If you read that very closely, you might have noticed I did not follow the exact pattern of the API specification of CountDownLatch.
I did that on purpose, because the example from the documentation is not perfect.
Here I will prove this claim and explain my own version.
Read more…

Categories: Java Tags: ,
Follow

Get every new post delivered to your Inbox.