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:

21 August, 2011


Название: Девственность     Жанр: Документальный
Год выпуска: 2009     Производство: Россия
Режиссер: Виталий Манский     Продолжительность: 86 мин.

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.
    @Cache(region = "cache_name", usage = CacheConcurrencyStrategy.TRANSACTIONAL)
    @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.

10 July, 2011

Where to store JavaScript and CSS files for Blogger

If you are a Blogger user, then you already know that currently there is no possibility to upload your custom JavaScript and CSS files. You have to host your files somewhere else and then link them in your blog template. One of the places where you can host your custom JavaScript, CSS and any type of files is Google Code. Google Code, is a free platform to host Open Sources Projects.

You can just simply upload your files and hotlink to them. Main issue in this simple task is that it’s working for JavaScript files but it doesn’t work when hot linking to CSS or Image files. The reason is that, by default when we upload any file to Google Code, it is served as text-plain mime-type. This works with JavaScript files but not with CSS, Image files or HTML files.

Below is a small tutorial showing how to create a new project on Google Code, how to use an SVN client to upload new files to it and how to set the mime-type for these files.