23 June, 2013

HATEOAS using Spring Framework

HATEOAS is a constraint of the REST application architecture which is very often ignored by developers. In many cases this is caused by the lack of support of frameworks used to build and expose RESTful services. In this post I will show how quickly we can add HATEOAS to RESTful web services using Spring Framework. Source code of the demo web application presented below are available for download, run it using mvn tomcat7:run command. Also you can read a nice presentation about why HATEOAS is important.

The Spring HATEOAS Library (currently in Release 0.6) provides API to help creating REST representations that follow the HATEOAS principle. The core problem it tries to address is link creation and representation assembly. Let's see the main steps required for enabling the HATEOAS for a RESTful web service:

02 June, 2013

Transaction synchronization callbacks in Spring Framework

Declarative transaction management simplifies considerably the development. Sometimes you want a little more control over transaction but at the same time you don't want to switch to programmatic transaction management. I'm talking about cases when you want to execute some activities only when transaction was completed successfully. For example: send an email with registration details, update a cache, send a message over network, etc. The tricky part here is that you want to perform these activities from a transactional method (a method marked with @Transactional which automatically will start and end the transaction).

Now let's see how we can achieve this in Spring Framework. TransactionSynchronizationManager is the central helper class that manages resources and transaction synchronizations per thread. It allows to register transaction synchronizations for the current thread if synchronization is active. TransactionSynchronization represents the actual transaction synchronization callback with methods like: afterCommit(), afterCompletion(int status), beforeCommit(boolean readOnly), beforeCompletion(), etc. In order to make things easier for use, we will create an after commit executor which will allow us to execute the code only after a successful commit.

15 September, 2011

Configure Maven to generate classes from XML Schema using JAXB

In my previous post I showed how to create RESTful services using Spring Framework. For representation of resources in XML I used JAXB and I followed the bottom-up approach (I wrote the Java classes and I let to generate XML/XSD from Java classes). In this post I will demonstrate how you can generate the same Java classes (User and UserList) from XML Schema (XSD) during Maven build, therefore using a top-down approach. For generation of Java classes from XML Schema during Maven build I will use Java.net Maven 2 JAXB 2 Plugin.

Along with the default generation of Java classes from XML Schema using xjc tool, I will add the following customizations:

  • Making all the generated classes to implement Serializable (useful when you want to use classes with some remote services: RMI, EJB, etc).
  • Use java.util.Calendar instead of javax.xml.datatype.XMLGregorianCalendar for fields generated from elements of type xs:dateTime.
  • Generated classes should also have a generated toString() method.
  • Classes have to be annotated with XmlRootElement (required by Spring Framework when classes are used to represent state in RESTful services).
  • You can further enhance and customize the generation of Java classes using various plugins.

Project sources are available for download. So let’s start, step by step:

14 September, 2011

CRUD RESTful services using Spring Framework

In this post I will show how to build CRUD (Create, Read, Update, Delete) REST-ful (Representational State Transfer) services using Spring Framework. Spring Framework version used in this example is 3.0.6.RELEASE. Apache Tomcat version used for testing the web services is 6.0.29 (default Tomcat version used by Tomcat Maven Plugin of Apache Maven 2.2.1). Project sources are available for download. So let’s start, step by step:

  1. First we have to define the resource on which the CRUD operation will be performed and how this resource will be represented. In our example we will use a resource that represents a User. The resource will be represented using XML (Extensible Markup Language). At the end of the post I will show how you can switch the resource representation to JSON (JavaScript Object Notation) or any other supported form.
  2. Create a Maven project. We will use Maven for project management and build. Maven POM is shown below:

07 August, 2011

How to generate equals(), hashCode(), toString() and compareTo() using Apache Commons Lang in Eclipse

Apache Commons project represents a set of reusable Java components. Apache Commons Lang is one of the Apache Commons components. It provides much needed additions to the standard JDK's java.lang package. One of its packages, org.apache.commons.lang3.builder contains a set of very useful builders that helps in creating consistent equals(), hashCode(), toString() and compareTo() methods.

In this post, I will show how to generate equals(), hashCode(), toString() and compareTo() methods using Apache Commons Lang builders in Eclipse. For demonstrations I will use the latest stable release - Apache Commons Lang 3.0. Note that Lang 3.0 uses a different package (org.apache.commons.lang3) than its predecessors (org.apache.commons.lang). All the examples presented in this post will work also with the previous Apache Commons Lang releases; just change the package name from lang3 to lang.

Native Support

Eclipse supports out of the box generation of equals(), hashCode() and toString() methods. But only the generation of toString() can be configured to use different builders. Below is shown how to configure Eclipse to use ToStringBuilder to generate toString() methods.

31 July, 2011

How to register Infinispan listeners in Spring when using Infinispan as 2LC for Hibernate

In this post I will show how to register Infinispan listeners in Spring when Infinispan is used as second level cache (2LC) for Hibernate. So let’s start:
  1. Annotate your entity classes as cacheable. Pay attention to the cache region name ("cache_name") specified in the region attribute of Cache annotation.
    @Entity
    @Cache(region = "cache_name", usage = CacheConcurrencyStrategy.TRANSACTIONAL)
    @Cacheable
    @Table(name = "ENTITY_TABLE")
    public class MyEntity implements Serializable {
        // entity fields
    }
    
  2. Write your custom InfinispanRegionFactory as it is shown below. It extends from Hibernate InfinispanRegionFactory and its logic is very simple. The only thing which it does is to register listeners after its start. Pay attention to the named cache ("cache_name") to which listeners are registered. It should be the same as the cache region name used by your entities.

How to extract type arguments from parameterized (generic) class

A nice thing about parameterized classes in Java is that you can extract and access information about class type arguments at runtime (for an explanation about parameters and arguments see Parameters and arguments). Let’s say that we have an abstract parameterized superclass that has a method which provides some common functionality to all its subclasses. And inside that method we wanted to know what is the class type argument specified by the subclass.

public abstract class GenericAbstractSuperclass<T> {
    public void foo() {
        // here we wanted to know what is the class type argument
    }
}

public class GenericClass1 extends GenericAbstractSuperclass<Integer> {
    // subclass methods
}

public class GenericClass2 extends GenericAbstractSuperclass<String> {
    // subclass methods
}

In above example, method foo() has to access class type argument. In case of GenericClass1 it has to get Integer and in case of GenericClass2 it has to get String. Below is listed a utility class that can accomplish this.

25 July, 2011

java.math.BigDecimal performance

These days I had to do some monetary calculations in Java. This reminded me again about primitive double type and that it is absolutely the worst thing you can use when dealing with money. As you know, primitive double don't necessarily give you the right value, only the value that can be stored in a binary number format (any decimal number is represented by an approximated value). Whilst, java.math.BigDecimal gives you the required precision, its performance is very poor comparable to primitive types.

Below are few simple tests that are measuring BigDecimal performance based on a simple computation x2 + y2 which is performed in a loop 250000 times. In order to exclude the JVM warm-up cost, each test was executed 10 times. The execution time was calculated as average of all executions except first execution (exec2 + exec3 + … + exec10) / 9.

19 June, 2011

Export FreeMind mind map as Java Applet

FreeMind is a free mind-mapping software written in Java. In this post I will show how to export FreeMind mind maps as Java Applet, describe issues which you can encounter during this process and give some hints on a how to better package exported mind maps.

Let’s start with creating a test mind map. Suppose we have the following mind map:

Test Mind Map

FreeMind has plenty of options for exporting mind maps. For example the image which you see above was created using Export as PNG option (File -> Export -> As PNG…). Your next question might be: Why to export mind maps as Java Applet if there are so many other options? Here is the answer. Even if FreeMind has many options for exporting mind maps, most of them are not suitable for publishing on the Internet (especially for big mind maps). Starting with FreeMind 0.9.0 two new export options were added: Flash and Java Applet. These two options can be used to bring mind maps into the Internet.