<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>blog.smart-java.nl</title>
	<atom:link href="http://blog.smart-java.nl/blog/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smart-java.nl/blog</link>
	<description>Ordina J-Technologies - Java Blog</description>
	<lastBuildDate>Tue, 09 Mar 2010 07:30:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Hibernate, lazy loading and inheritance</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 12:35:15 +0000</pubDate>
		<dc:creator>gnoij</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Java API]]></category>
		<category><![CDATA[Object Relational Mapping]]></category>
		<category><![CDATA[ClassCastException]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[lazy loading]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=956</guid>
		<description><![CDATA[A common problem with typecasting a lazy loaded entity to its child is a ClassCastException. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.
Suppose we have a class B which extends A and a class C which has class A as a member as shown below.

public [...]]]></description>
			<content:encoded><![CDATA[<p>A common problem with typecasting a lazy loaded entity to its child is a <em>ClassCastException</em>. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.</p>
<p>Suppose we have a class <em>B</em> which extends <em>A</em> and a class <em>C</em> which has class <em>A</em> as a member as shown below.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class A {

    private Long id;

    private String name;

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    public Long getId() { return id; }
}

public class B extends A {

    private String somethingElse;

    public String getSomethingElse() { return somethingElse; }

    public void setSomethingElse(String something) { this.somethingElse = something; }

}

public class C {

    private Long id;

    private A a;

    public A getA() { return a; }

    public void setA(A a) { this.a = a; }

    public Long getId() { return id; }
}
</script></pre>
<p>The following test will fail with a<em> ClassCastException</em> on the last line.</p>
<pre><script type="syntaxhighlighter" class="brush: java">public void testClassCastException() {

	B b = new B();
	b.setName("B");
	b.setSomethingElse("test");

	C c = new C();
	c.setA(b);

	save(c);
	// just for testing purposes we clear the session, so
	// c is actually loaded from the database
	clearSession(); 

	c = retrieve(C.class, c.getId());
	b = (B) c.getA();
}
</script></pre>
<p><em> The methods save(), clearSession() and retrieve() are just helper methods which implement the Hibernate session methods save(), clear() and get().</em></p>
<p>A search on the Internet shows a couple of solutions for this problem.</p>
<ol>
<li><a href="http://sysin.wordpress.com/2009/02/27/hibernate-inheritance-classcastexception-part-1/">Using interfaces as a proxy in the hibernate mappings</a>. This will result in accessing the object through its interface only so all methods must be exposed in the interface. I don&#8217;t want to expose every public or protected method in the interface which are not intended for use by external parties.</li>
<li><a href="https://www.hibernate.org/280.html">Using the Visitor Pattern to access the correct childclass</a>. This means that users of these objects must write a lot of code just to use some getters. I don&#8217;t want to burden someone else with a local Hibernate problem.</li>
<li>Using <em>((HibernateProxy)object).getHibernateLazyInitializer().getImplementation()</em> whenever a typecast of an object to its child class is needed.</li>
</ol>
<p>All of the solutions mentioned above are not suitable for me so I decided on another solution which is a variant of solution 3.</p>
<p>With a slight modification of the method <em>getA()</em> in class <em>C</em>, exposing the <em>HibernateProxy</em> is avoided.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    public A getA() { return deProxy(a); }

    protected  <T extends Object> T deProxy(T object) {
        if (object instanceof HibernateProxy) {
            return (T)((HibernateProxy)object).getHibernateLazyInitializer().getImplementation();
        }
        return object;
    }
</script></pre>
<p>Now the test completes without failure.</p>
<p>This has to be done for every getter which can return a lazy loaded proxy.</p>
<p>And if you (like me) don&#8217;t want Hibernate code in your domain model, you can move this code to the persistence layer and use dependency injection to use it.</p>
<p>It&#8217;s still not an elegant solution (IMHO there isn&#8217;t one), but its the best usable for me.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Unified Expression Language in Maven-Jetty-Plugin</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/02/27/using-unified-expression-language-in-maven-jetty-plugin/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/02/27/using-unified-expression-language-in-maven-jetty-plugin/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 15:51:57 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[jetty]]></category>
		<category><![CDATA[JSF 2.0]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[maven-jetty-run]]></category>
		<category><![CDATA[UEL]]></category>
		<category><![CDATA[unified expression language]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=927</guid>
		<description><![CDATA[I like the maven-jetty-plugin. If I download an Open Source project, I usually first look for this baby, because it allows me to quickly run the code in a tested environment. This saves me from a lot of configuration, which would otherwise cause me to lose interest. This often doesn&#8217;t take long&#8230;  
Also, you [...]]]></description>
			<content:encoded><![CDATA[<p>I like the maven-jetty-plugin. If I download an Open Source project, I usually first look for this baby, because it allows me to quickly run the code in a tested environment. This saves me from a lot of configuration, which would otherwise cause me to lose interest. This often doesn&#8217;t take long&#8230; <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Also, you can completely configure the server in your POM, centralizing configuration and making it thus easy to store server settings in version control. Also, the mvn-jetty-plugin benefits from your existing Maven project configuration, like <code>dependencyManagement</code>.</p>
<p>Some of my buddies at Apache even use the maven-jetty-plugin on a daily basis for their real work. I never got this far, mostly because I&#8217;m more familiar with Tomcat, but also because I didn&#8217;t really see it as a mature development tool. However, today I decided to give it a chance.</p>
<p><strong>The first attempt</strong><br />
So, I created a simple webapp in my favorite IDE: <a href="http://www.jetbrains.com/idea/">IntelliJ IDEA</a> and added a Maven2 POM to enable Maven2 support. All well so far.</p>
<p>This was the initial version of my POM:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>zzz</groupId>
    <artifactId>zzz</artifactId>
<packaging>war</packaging>
    <version>0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-api</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-impl</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.2.GA</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.10</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.com/maven2</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <finalName>ueltest</finalName>
<plugins>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
<plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.14</version>
                <configuration>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                    <stopKey>foo</stopKey>
                    <stopPort>9999</stopPort>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</script></pre>
<p>All was fine, my test app was running, but I needed to enable <a href="http://www.mojavelinux.com/blog/archives/2009/08/why_you_didnt_know_the_unified_el_is_being_updated/">Unified EL</a> to test <a href="http://myfaces.apache.org/">MyFaces</a> <a href="http://java.sun.com/javaee/6/docs/api/javax/faces/validator/BeanValidator.html">BeanValidator</a>.</p>
<p><strong>Adding UEL libraries</strong><br />
So, I added a dependency to the UEL API and Impl in my POM, but there was an issue. Every web container already provides the old Expression Language in the jsp-api.jar. So I&#8217;m not allowed to package my own EL libraries.</p>
<p>However, I&#8217;m quite stubborn, so I tried anyway:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
...
<dependencies>
    ...
    <dependency>
        <groupId>javax.el</groupId>
        <artifactId>el-api</artifactId>
        <version>2.2.1-b01</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>el-impl</artifactId>
        <version>2.1.2-b05</version>
        <scope>runtime</scope>
    </dependency>
    ...
</dependencies>
...
</script></pre>
<p>So, let&#8217;s give it a try:
<pre>mvn jetty:run-exploded</pre>
<p> (MyFaces 2.0 requires exploded deployment in Jetty).</p>
<p>Result? BOOOM!</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
java.lang.LinkageError: loader constraint violation: loader (instance of org/mortbay/jetty/webapp/We
bAppClassLoader) previously initiated loading for a different type with name "javax/el/ExpressionFac
tory"
</script></pre>
<p><strong>The fix, replacing libraries</strong><br />
The error is completely appropriate. You&#8217;re just not allowed to package your own version of the servlet libraries. That&#8217;s the job of the servlet container. Failing to do so will result in the error shown above.</p>
<p>So we need to fix this issue by somehow replacing the Jetty libraries or at least changing the way Jetty loads its jsp-api.jar. This is no trivial task however, since jetty is initialized by Maven and doesn&#8217;t have a fixed directory structure on disk.</p>
<p>So we need to have some way in Maven to configure the Jetty libraries.</p>
<p>First, <strong><em>Jetty doesn&#8217;t have an endorsed mechanism</em></strong>, so that&#8217;s a no-go.</p>
<p>But the fix is actually quite easy, just pass some dependencies into the jetty plugin in the POM.</p>
<p>The final POM looks like this:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>zzz</groupId>
    <artifactId>zzz</artifactId>
<packaging>war</packaging>
    <version>0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-api</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-impl</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.2.GA</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.10</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>2.2.1-b01</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.com/maven2</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>glassfish</id>
            <url>http://download.java.net/maven/2</url>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>
<pluginRepositories>
<pluginRepository>
            <id>jboss-plugins</id>
            <url>http://repository.jboss.com/maven2</url>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <finalName>test</finalName>
<plugins>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
<plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.14</version>
                <configuration>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                    <stopKey>foo</stopKey>
                    <stopPort>9999</stopPort>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>javax.servlet.jsp</groupId>
                        <artifactId>jsp-api</artifactId>
                        <version>2.2</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>javax.el</groupId>
                        <artifactId>el-api</artifactId>
                        <version>2.2.1-b01</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.glassfish.web</groupId>
                        <artifactId>el-impl</artifactId>
                        <version>2.2.1-b01</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.mortbay.jetty</groupId>
                        <artifactId>jsp-2.1</artifactId>
                        <version>6.1.14</version>
                        <scope>provided</scope>
                        <exclusions>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>jsp-api-2.1</artifactId>
                            </exclusion>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>start</artifactId>
                            </exclusion>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>jetty-annotations</artifactId>
                            </exclusion>
                        </exclusions>
                    </dependency>
                </dependencies>
</plugin>
        </plugins>
    </build>
</project>
</script></pre>
<p>As you can see, Maven takes care of the heavy lifting. You only need to specify your dependencies and they will override any dependencies with the same groupId, artifactId and type.</p>
<p>So, now I don&#8217;t have any reason not to use mvn-jetty-run to test my code!</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/02/27/using-unified-expression-language-in-maven-jetty-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>REST made easy with Java EE 6 and JAX-RS 1.1</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 06:34:25 +0000</pubDate>
		<dc:creator>Stephan Oudmaijer</dc:creator>
				<category><![CDATA[Java EE]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=893</guid>
		<description><![CDATA[In my previous post I wrote about Spring 3.0 and how Spring MVC enables REST services in Spring 3.0. Java EE 6 adds support for RESTfull services by adding JAX-RS to the specification. In this post I will show how JAX-RS 1.1 will make your life easy when writing RESTfull services for JEE 6. 
GlassFish [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://oudmaijer.com/cms/index.php?mact=News,cntnt01,detail,0&#038;cntnt01articleid=23">my previous post</a> I wrote about Spring 3.0 and how Spring MVC enables REST services in Spring 3.0. Java EE 6 adds support for RESTfull services by adding JAX-RS to the specification. In this post I will show how JAX-RS 1.1 will make your life easy when writing RESTfull services for JEE 6. </p>
<p><a href="https://glassfish.dev.java.net/">GlassFish v3</a> is an open source application server and is the first compatible implementation of the Java EE 6 platform specification. To test the examples in this article I will assume that you use GlassFish (or any other JEE6 enabled application server) to run the examples.</p>
<p><b>Maven2 dependencies</b></p>
<p>Lets start with the Maven dependencies, you can add them all to the <code>pom.xml</code> of your war. I have also included Sun&#8217;s Maven2 repository for downloading the JEE6 dependencies like the javaee-api and Sun&#8217;s JAX-RS 1.1 implementation called Jersey.</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
...
<repository>
    <id>maven2-repository.dev.java.net</id>
    <name>Java.net Repository for Maven</name>
    <url>http://download.java.net/maven/2/</url>
</repository>
...
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.1.5</version>
    <scope>provided</scope>
</dependency>
...
</script></pre>
<p>Both dependencies are scoped as provided because GlassFish already ships with these libraries. In fact, my war file is not bigger than 22kb. JEE6 allowes developers to package full blown JEE application as a web archive file, there is no need for an enterprise archive anymore. This makes JEE6 applications really light weight. </p>
<p><b>JAX-RS RESTfull services in JEE6</b></p>
<p>JAX-RS supports configuration through annotations, just like the Spring 3.0 REST annotations. Annotations can be added to both classes and methods. Classes in JAX-RS can be POJO`s. One thing about JAX-RS is that it does not integrate well with other JEE specification, for example the JSR-330 annotations for dependency injection are not supported by JAX-RS (yet), but there is a workaround <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Because of the flexibility of JAX-RS it is possible to annotate EJB SessionBean or CDI components with JAX-RS annotations. So when a bean with JAX-RS annotation is packaged in a war file, the annotations are automatically picked up by the JAX-RS implementation (Jersey in this case). Since EJB3.1 SessionBeans and CDI components support all of the dependency injection features offered by JEE6, JAX-RS now does too! </p>
<p>Below is an example JAX-RS annotated class. The goal of this RESTfull service is to expose two methods of the ProductService through a RESTfull interface. The ProductService is injected using the @Inject annotation. </p>
<p>In JAX-RS the @Path annotation is used to map an URI to a REST service. In the example below I&#8217;ve defined the @Path annotation on the class, this will map all the URIs starting with /product to this class. I also defined the @ManagedBean (CDI) annotation on the class for the @Inject to work properly. </p>
<p>There are two methods within the service which are annotated with @Path, @GET and @Produces. The @Path is the same as with the class, but in this case it maps URI&#8217;s to a method. The URI of a method is relative to URI specified in the @Path annotation<br />
on the class. So the following URLs are mapped in this example:</p>
<li>/product/category/{categoryId} which returns all products in a category</li>
<li>/product/categories which returns all product categories</li>
<p>JAX-WS allowes for mapping HTTP methods like GET, PUT, POST and DELETE to Java methods with the @GET, @PUT, @POST and @DELETE annotations. In this example only the GET method is used. In RESTfull service the HTTP GET is used to retrieve data. To map a GET request to a method you can simply annotate a method with @GET.</p>
<p>The @Produces annotation specifies the Mime-Type of the response data the methods produces. In this example the methods both produce XML data, therefore we need to set the Mime-Type to application/xml. When returning an Object from a method annotated with @Produces, JAX-RS trieds to find an appropriate converter to produces the output. In this case I will use JAXB will to marshall the Objects to XML (see below).</p>
<pre><script type="syntaxhighlighter" class="brush: java">
package com.oudmaijer.webshop.web.rest;

import com.oudmaijer.webshop.domain.Category;
import com.oudmaijer.webshop.domain.Product;
import com.oudmaijer.webshop.service.ProductService;

import javax.annotation.ManagedBean;
import javax.inject.Inject;
import javax.naming.NamingException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.util.List;

/**
 * Rest service for Products.
 * 
<p/>
 * User: sou12983
 * Date: 18-feb-2010
 * Time: 10:15:04
 */
@Path(value = "/product")
@ManagedBean
public class ProductRestlet {

    @Inject
    private ProductService productService;

    /**
     * Returns all the product categories in XML format.
     *
     * @return
     * @throws NamingException
     */
    @GET
    @Path("/categories")
    @Produces("application/xml")
    public List<Category> getCategories() throws NamingException {
        return productService.getCategories();
    }

    /**
     * Returns all the products in a specified category.
     *
     * @param categoryId
     * @return
     * @throws NamingException
     */
    @GET
    @Path("/category/{categoryId}")
    @Produces("application/xml")
    public List<Product> getProducts(@PathParam(value = "categoryId") Long categoryId) throws NamingException {
        return productService.getProducts(categoryId);
    }
}
</script></pre>
<p><b>JAXB marshalling</b></p>
<p>In order for JAXB to marshall the Objects returned, we need to specify JAXB annotations on the Objects returned from the methods.<br />
In this example I&#8217;ve added @XmlRootElement to the returned Objects to simply marshall the entire Object to XML.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
package com.oudmaijer.webshop.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Product {
...
}

package com.oudmaijer.webshop.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Category{
...
}
</script></pre>
<p><b>Adding Jersey to the web deployment descriptor: web.xml</b></p>
<p>For JAX-RS to work we still need to add a Servlet to the web.xml which maps URL&#8217;s to the services. In this case we need to add the JerseyServlet to the web.xml. In the servlet-mapping all /rest/ URL patterns are mapped to Jersey. We can access the REST services using the following URIs: /rest/product/etc.</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

<servlet>
    <servlet-name>JerseyServlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>JerseyServlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

</web-app>
</script></pre>
<p><b>Conclusion</b></p>
<p>When building RESTfull services on an JEE6 enabled application server, JAX-RS really makes things easy. You will have to decide for your specific case if you want to use Spring or JAX-RS.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>DefaultMessageListenerContainer troubles in Websphere</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/02/03/defaultmessagelistenercontainer-troubles-in-websphere/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/02/03/defaultmessagelistenercontainer-troubles-in-websphere/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 14:19:57 +0000</pubDate>
		<dc:creator>Michel.Schudel</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[jms]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[Websphere]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=859</guid>
		<description><![CDATA[Using the Spring DefaultMessageListenerContainer makes it easy for you to connect to a jms resource like a Queue so you can pick up messages from that queue.
Using this container in Websphere (6.0, 6.1, 7) some problems occur when you want to do the following:

You use a resource environment reference for your destination, specified in the [...]]]></description>
			<content:encoded><![CDATA[<p>Using the Spring <code>DefaultMessageListenerContainer</code> makes it easy for you to connect to a jms resource like a Queue so you can pick up messages from that queue.</p>
<p>Using this container in Websphere (6.0, 6.1, 7) some problems occur when you want to do the following:</p>
<ul>
<li>You use a resource environment reference for your destination, specified in the web.xml, for the Destination.</li>
<li>You use the property <code>destinationName</code> on the <code>DefaultMessageListenerContainer</code> in combination with a <code>JndiDestinationResolver</code> to look up your resource environment reference like this: <code>java:comp/env/jms/(your destination)</code></li>
</ul>
<p><strong>problem</strong><br />
When you try to start the application, you will get an exception like this: <code>javax.naming.NameNotFoundException: Name "comp/env/jms/(your destination)" not found in context "java:".</code>, although you are sure that your resource environment reference is defined correctly.</p>
<p><strong>cause</strong><br />
The cause of this problem lies in the fact that the lookup occurs in a Thread started by the <code>DefaultMessageListenerContainer</code>, which is unmanaged by Websphere. This thread will not have the jndi queue bindings in its <code>InitialContext</code>.</p>
<p><strong>solution</strong><br />
You can either:</p>
<ol>
<li>Specifiy the jndi object beforehand with a <code>JndiObjectFactoryBean</code>, or a <code><br />
  &lt;jee:jndi-lookup id="myqueue" jndi-name="java:comp/env/jms/(your destination)"/&gt;</code>, and then<br />
  setting the <code>destination</code> property of the <code>DefaultMessageListenerContainer</code> to the ref <code>myqueue</code>, so no actual lookup occurs within the thread of the listener itself.</li>
<li>
  Delegate the listener&#8217;s thread to Websphere with the help of the Spring class <code>WorkManagerTaskExecutor</code>. You can then set the property <code>taskExecutor</code> on the message listener container to reference this class. See the <a href="http://www.ibm.com/developerworks/websphere/techjournal/0609_alcott/0609_alcott.html">IBM article here </a> for details on how to do this.
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/02/03/defaultmessagelistenercontainer-troubles-in-websphere/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JSF 2.0: The most simple CDI integration use cases</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/31/jsf-2-0-the-most-simple-cdi-integration-use-cases/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/31/jsf-2-0-the-most-simple-cdi-integration-use-cases/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 19:45:47 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[JSF 2.0]]></category>
		<category><![CDATA[Producer methods]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=851</guid>
		<description><![CDATA[If you have (just like me) been following the Web Beans and Contexts and Dependency Injection (CDI) work, you might be thinking (also just like I did): &#8220;That CDI is heavily over-engineered&#8221;. My &#8220;moment of clarity&#8221; was a year ago, at DeVoxx 2008.
It was a talk by Pete Muir of JBoss. He was showing a [...]]]></description>
			<content:encoded><![CDATA[<p>If you have (just like me) been following the Web Beans and <a href="http://jcp.org/en/jsr/detail?id=299">Contexts and Dependency Injection</a> (CDI) work, you might be thinking (also just like I did): &#8220;That CDI is heavily over-engineered&#8221;. My &#8220;moment of clarity&#8221; was a year ago, at <a href="http://devoxx.com/">DeVoxx</a> 2008.</p>
<p>It was a <a href="http://parleys.com/#sl=1&#038;st=5&#038;id=1386">talk by Pete Muir of JBoss</a>. He was showing a really simple use case and tried to implement it using CDI. The talk was really technology driven and I hated it. Why? Because it wasn&#8217;t an improvement compared with the existing technologies. He wrote an application, containing several interfaces, classes (this is not bad) and custom annotations. If the goal was to show some kind of geniosity, it was a good talk. But if the goal was to show how this new technology would make our lives better&#8230; then sorry, he failed miserably.</p>
<p>More than a year further, there have been a lot of movements on the CDI front. And, as an <a href="http://myfaces.apache.org/">Apache MyFaces</a> developer, I&#8217;m of course very interested how to use CDI in a JSF 2.0 application. And as an Apache fanboy, I of course prefer Apache software, in this case MyFaces with <a href="http://openwebbeans.apache.org/">OpenWebBeans</a> and <a href="http://openjpa.apache.org/">OpenJPA</a>.</p>
<p><b>Configuration</b><br />
Since OpenWebBeans is still under development, you need to do some additional steps to get it to work.</p>
<p>The following POM should get you up and running quickly in Tomcat:</p>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;org.apache.myfaces&lt;/groupId&gt;
    &lt;artifactId&gt;myfaces-example-ebanking&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;packaging&gt;war&lt;/packaging&gt;

    &lt;dependencies&gt;
        &lt;!-- Compile dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.myfaces.core&lt;/groupId&gt;
            &lt;artifactId&gt;myfaces-api&lt;/artifactId&gt;
            &lt;version&gt;${myfaces-version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.myfaces.core&lt;/groupId&gt;
            &lt;artifactId&gt;myfaces-impl&lt;/artifactId&gt;
            &lt;version&gt;${myfaces-version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.openjpa&lt;/groupId&gt;
            &lt;artifactId&gt;openjpa-all&lt;/artifactId&gt;
            &lt;version&gt;${openjpa-version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;commons-digester&lt;/groupId&gt;
            &lt;artifactId&gt;commons-digester&lt;/artifactId&gt;
            &lt;version&gt;2.0&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.openwebbeans&lt;/groupId&gt;
            &lt;artifactId&gt;openwebbeans-impl&lt;/artifactId&gt;
            &lt;version&gt;${openwebbeans.version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.openwebbeans&lt;/groupId&gt;
            &lt;artifactId&gt;openwebbeans-jsf&lt;/artifactId&gt;
            &lt;version&gt;${openwebbeans.version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.geronimo.specs&lt;/groupId&gt;
            &lt;artifactId&gt;geronimo-interceptor_1.1_spec&lt;/artifactId&gt;
            &lt;version&gt;1.0.0-EA1-SNAPSHOT&lt;/version&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.annotation&lt;/groupId&gt;
            &lt;artifactId&gt;jsr250-api&lt;/artifactId&gt;
            &lt;version&gt;1.0&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;!-- Test dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;version&gt;${junit-version}&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;repositories&gt;
        &lt;repository&gt;
            &lt;id&gt;Apache MyFaces beta&lt;/id&gt;
            &lt;name&gt;Apache MyFaces beta&lt;/name&gt;
            &lt;url&gt;http://people.apache.org/~lu4242/myfaces200beta&lt;/url&gt;
        &lt;/repository&gt;
    &lt;/repositories&gt;

    &lt;properties&gt;
        &lt;myfaces-version&gt;2.0.0-beta&lt;/myfaces-version&gt;
        &lt;openwebbeans.version&gt;1.0.0-SNAPSHOT&lt;/openwebbeans.version&gt;
        &lt;openjpa-version&gt;2.0.0-M3&lt;/openjpa-version&gt;
        &lt;junit-version&gt;4.7&lt;/junit-version&gt;
    &lt;/properties&gt;
&lt;/project&gt;
</pre>
<p>Note some of the additional dependencies required to run in Tomcat, as opposed to a full blown appserver.</p>
<p>Also, at the moment you need to <b>build OpenWebBeans from source manually</b>. The geronimo-interceptor_1.1_spec dependency will be downloaded to your local Maven repository on a &#8220;mvn install&#8221;. OpenJPA is not needed for this simple use case, but I use it in my project.</p>
<p><b>Code</b><br />
And then, the real code:</p>
<pre class="brush:java">
public class WebUtils {
    private static volatile String basePath;

    @Produces @Named public String getBasePath() {
        if (basePath == null) {
            basePath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        }
        return basePath;
    }
}
</pre>
<p>This class contains a so-called Producer Method. As the name suggests, it produces stuff. In this case, it produces a String with Dependent scope. This means the method will be invoked every time the variable is needed. EL expressions or injection are the most common cases for this.</p>
<p>I&#8217;m caching the return value, though it&#8217;s not necessary, since getting the context path is pretty cheap.</p>
<p>The view could look like this (snippet):</p>
<pre class="brush:xml">
...
&lt;link href="#{basePath}/style/default.css" rel="stylesheet" type="text/css" /&gt;
...
</pre>
<p>Another implementation could put the variable into the Application scope, like this:</p>
<pre class="brush:java">
public class WebUtils {
    @Produces @Named @ApplicationScoped public String getBasePath() {
        return FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
    }
}
</pre>
<p>As easy it might seem, the approaches shown above require some responsibility from the programmer though. With producer methods, it becomes really <b>easy to mess things up</b>. After all, you&#8217;re effectively creating <b>globals</b>. Tool support may help you here though. For example, the Dependency Analyzer in IntelliJ IDEA 9.0.1 already contains pretty decent <a href="http://www.jetbrains.com/idea/whatsnew/index.html#Java_EE_6_Support">support for JSF 2.0</a> and CDI. And, knowing the reputation of the JetBrains folks, I&#8217;m sure they come up with even more fancy stuff.</p>
<p><b>A more classic implementation</b><br />
A more classic implementation could look like the following:</p>
<pre class="brush:java">
@Named
@ApplicationScoped
public class WebBean {
    private static volatile String basePath;

    public String getBasePath() {
        if (basePath == null) {
            basePath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        }
        return basePath;
    }
}
</pre>
<p>I&#8217;m not using producer methods anymore. The WebBean is now a CDI-managed bean.</p>
<p>The client code becomes slightly more verbose, but who cares? I&#8217;ll put the client code in a generic template anyway!:</p>
<pre class="brush:xml">
...
&lt;link href="#{webBean.basePath}/style/default.css" rel="stylesheet" type="text/css" /&gt;
...
</pre>
<p><b>Wrapping up</b><br />
I haven&#8217;t even showed the complete tip of the iceberg. CDI offers several ways to write code and we&#8217;ve yet to find out the (anti) patterns.</p>
<p>I would like to point you to the <a href="http://openwebbeans.apache.org">OpenWebBeans documentation</a> for more info, but unfortunately this is still under development. The good news is that JBoss Weld already has extensive <a href="http://docs.jboss.org/weld/reference/1.0.0/en-US/html/">documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/31/jsf-2-0-the-most-simple-cdi-integration-use-cases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSF 2.0: Maximum flexibility with System Events</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/24/jsf-2-0-maximum-flexibility-with-system-events/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/24/jsf-2-0-maximum-flexibility-with-system-events/#comments</comments>
		<pubDate>Sun, 24 Jan 2010 15:41:31 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=812</guid>
		<description><![CDATA[JSF 2.0 adds a lot of interesting features. Andy Schwartz provides an extensive overview on his blog.
On this blog, I&#8217;d like to elaborate a bit further on the interesting features JSF 2.0 has to offer.
JSF 2.0: System Events
JSF 2.0 comes with a useful feature, called System events. System events are predefined events that are published [...]]]></description>
			<content:encoded><![CDATA[<p>JSF 2.0 adds a lot of interesting features. Andy Schwartz provides an extensive overview on his <a href="http://andyschwartz.wordpress.com/2009/07/31/whats-new-in-jsf-2/">blog</a>.</p>
<p>On this blog, I&#8217;d like to elaborate a bit further on the interesting features JSF 2.0 has to offer.</p>
<p><b>JSF 2.0: System Events</b><br />
JSF 2.0 comes with a useful feature, called System events. System events are predefined events that are published at predefined points in the lifecycle.<br />
System events are either global or component system events.</p>
<p><b>Global system events</b><br />
An example of a global system  event is PostConstructApplicationEvent, which is published when all configuration is done. It can be seen as a JSF replacement for ServletContextListener.</p>
<p>Listener registration is done by invoking Application.subscribeToEvent(Class&lt;? extends SystemEvent&gt; type, SystemEventListener listener).</p>
<p><b>Component system events</b><br />
Component system events only apply to the component to which the listener is attached.</p>
<p>An example of a component system event is PreRenderComponentEvent. This event is published to the appropriate component when it&#8217;s about to be rendered.</p>
<p>Listener registration is done by invoking UIComponent.subscribeToEvent(Class&lt;? extends SystemEvent&gt; type, ComponentSystemEventListener listener).</p>
<p><b>&lt;f:event /&gt; tag</b><br />
The JSF 2.0 spec also defines the &lt;f:event /&gt; tag, which needs to be nested inside a component tag in the web page. This tag is used to make listener registration easier. Just nest the tag inside a component tag in your Facelet, specify the event to listen to and specify a MethodExpression to your listener method and everything works.</p>
<p><b>An example</b><br />
Below is an example of an e-banking login page. It uses a challenge-response authentication mechanism, so it generates a &#8220;random&#8221; challenge when the page is loaded. Because users can navigate to the login page directly (GET-request), we can&#8217;t rely on an action method to be invoked first, so let&#8217;s fix this using system events.</p>
<p><b>First, a bit of history</b><br />
I&#8217;ve always hated to write &#8220;the first&#8221; page in JSF. Since JSF short circuits the lifecycle in the case of a GET request, you don&#8217;t really have an appropriate hook for page initialization, making it difficult to create a dynamic landing page.</p>
<p>One could write &#8220;lazy getters&#8221;:</p>
<pre class="brush:java">
public class MyBackingBean {
    private List<Account> accounts;

    public List<Account> getAccounts() { // Yuck
        if (accounts == null) {
            // Do some expensive database query
            accounts = doSomeWork();
        }
        return accounts;
    }
}
</pre>
<p>It&#8217;s quite obvious this is extremely nasty. You don&#8217;t know when the getter is invoked (EL triggers the invocation), and that if-null check is also ugly. Btw. getters with logic are ugly anyway&#8230;</p>
<p>JSF 1.2 offered a slightly more elegant option with @PostConstruct:</p>
<pre class="brush:java">
public class MyBackingBean {
    private List<Account> accounts;

    @PostConstruct
    public void init() {
        accounts = doSomeWork();
    }

    public List<Account> getAccounts() { // Still not good
        return accounts;
    }
}
</pre>
<p>This is a bit better, but still not very good. The exact point of invocation within the lifecycle is still not obvious. But at least we now know the init() method won&#8217;t be invoked multiple times.</p>
<p>There are other ways to tackle this issue, for example, using a PhaseListener, or using a framework like Seam, but that has issues of its own.</p>
<p><b>Back to the event example</b><br />
Below is a snippet of my login page.</p>
<pre class="brush:html">
&lt;h:form&gt;
  &lt;dl&gt;
    &lt;dt&gt;&lt;h:outputLabel value="Customer ID" for="customerId" /&gt;&lt;/dt&gt;
    &lt;dd&gt;&lt;h:inputText id="customerId" value="#{loginBean.customerId}" required="true" /&gt;&lt;/dd&gt;
    &lt;dt&gt;&lt;h:outputLabel value="Challenge" for="challenge" /&gt;&lt;/dt&gt;
    &lt;dd&gt;&lt;h:outputText id="challenge" value="#{loginBean.challenge}"&gt;
      &lt;f:event name="preRenderComponent" listener="#{loginBean.generateChallenge}" /&gt;
    &lt;/h:outputText&gt;&lt;/dd&gt;
    &lt;dt&gt;&lt;h:outputLabel value="Response (always 123456)" for="response" /&gt;&lt;/dt&gt;
    &lt;dd&gt;&lt;h:inputSecret id="response" value="#{loginBean.response}" required="true" /&gt;&lt;/dd&gt;
    &lt;dt&gt; &lt;/dt&gt;
    &lt;dd&gt;&lt;h:commandButton value="Login" action="#{loginBean.loginUsingTokenGenerator}" /&gt;&lt;/dd&gt;
  &lt;/dl&gt;
&lt;/h:form&gt;
</pre>
<p>As you can see, the above snippet contains the challenge response login form. Line 7 is the interesting one. It registers a PreRenderComponentEvent listener method on the LoginBean.</p>
<p>The LoginBean is shown next (snippet&#8230;).</p>
<pre class="brush:java">
@Named
@SessionScoped
public class LoginBean implements Serializable {
    private Integer customerId;
    private Integer challenge;
    private Integer response;
    private @Inject LoginService loginService;
    private Customer customer;
    // Getters and setters

    public void generateChallenge(ComponentSystemEvent event) throws AbortProcessingException {
        this.challenge = loginService.generateChallenge();
    }

    public String loginUsingTokenGenerator() {
        customer = loginService.loginUsingTokenGenerator(customerId, challenge, response);
        if (customer == null) {
            FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(
                        "Username and/or password is incorrect or your account has been disabled"));
            return null;
        } else {
            return "/pages/homepage.xhtml?faces-redirect=true";
        }
    }
}
</pre>
<p>Don&#8217;t mind the annotations, they come from CDI (<a href="http://jcp.org/en/jsr/detail?id=330">JSR-330</a> a.k.a. <a href="http://openwebbeans.apache.org/">Contexts and Dependency Injection</a>). The only thing to remember from these is that this class is a Session scoped managed bean which gets a LoginService injected. Note that I would also prefer ViewScoped, instead of SessionScoped.</p>
<p>Also, don&#8217;t mind the return values in loginUsingTokenGenerator. This is also a new feature in JSF 2.0, called Implicit Navigation.</p>
<p>Note the generateChallenge() method. The throws clause is not mandatory. The argument type must be ComponentSystemEvent though.</p>
<p><b>Wrapping up</b><br />
As you can see, System events and the &lt;f:event /&gt; tag provide a convenient way to hook in custom logic on a per-component basis.</p>
<p>And, because we&#8217;re back to normal OO programming, instead of getter hacking, unit testing the LoginBean is easy as pie!</p>
<p>Pretty neat huh?! <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/24/jsf-2-0-maximum-flexibility-with-system-events/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>java.util.Calendar.getActualMaximum returns strange results</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 15:55:15 +0000</pubDate>
		<dc:creator>Peter Schuler</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[Java language]]></category>
		<category><![CDATA[Bug]]></category>
		<category><![CDATA[Calendar]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=643</guid>
		<description><![CDATA[At the end of last year I encountered something odd in the java.util.Calendar. Now is odd behavior nothing to be surprised of in the Java Calendar but this particular oddness was really hard to spot.
I will therefore share it with you.
The code
Let&#8217;s first look a some code dealing with getting the last day of the [...]]]></description>
			<content:encoded><![CDATA[<p>At the end of last year I encountered something odd in the java.util.Calendar. Now is odd behavior nothing to be surprised of in the Java Calendar but this particular oddness was really hard to spot.</p>
<p>I will therefore share it with you.</p>
<p><strong>The code</strong></p>
<p>Let&#8217;s first look a some code dealing with getting the last day of the month:</p>
<pre class="brush:java">public class CalendarTest {
  public static void main(String[] args) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, Calendar.FEBRUARY);
    int maxDayOfMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);

    System.out.println("last day of month = " + maxDayOfMonth);
  }
}</pre>
<p>Please read the java doc for <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#getActualMaximum(int)">Calendar.getActualMaximum()</a>:</p>
<blockquote><p>Returns the maximum value that the specified calendar field could have, given the time value of this Calendar. For example, the actual maximum value of the MONTH field is 12 in some years, and 13 in other years in the Hebrew calendar system.</p></blockquote>
<p>So the code above can print two different values right &#8230;? 28 or 29 depending on the whether this year is a leap year. As you could have guessed that is another unexpected possibility. I can also print 31. Yes&#8230; really.</p>
<p>I all depends on the date on which this code is executed.</p>
<p>The problem is that Calendar.getInstance() will return a Calendar filled with the current date/time. Let&#8217;s assume the above code runs on the last day of January. The call to getInstance() will return 31-01-2009. The next step puts the month to February. This will result in a overflow as 31-02-2009 is invalid. Because of this Calendar will move the date to 3-03-2000. And March has 31 days.</p>
<p>There is a <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4452473">bug report (status: Closed, Not a Defect</a>) in the SDN which told me that the observed behavior was correct. I was not the <a href="http://forums.sun.com/thread.jspa?threadID=5422080">first</a> person surprised by this and I&#8217;m guessing I will not be the last.</p>
<p>I was &#8230;</p>
<ol>
<li>&#8230; lucky I wrote a decent unit test.</li>
<li>&#8230; lucky to be running said unit test om 31 December.</li>
<li>&#8230; unlucky for having to work on the last day of the year.</li>
</ol>
<p>Otherwise the bug I created would properly have slipped through the QA cycles and would have ended up in production. There it would only be visible on the last three days of every month if someone would specify a date in February.</p>
<p><strong>What about lenient?</strong><br />
The Calendar.setLenient function does protect against invalid input. Let&#8217;s quote the the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#setLenient(boolean)">Calendar java doc</a> about Leniency:</p>
<blockquote><p><strong>Leniency</strong><br />
Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.</p>
<p>When a Calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its calendar fields. For example, a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month. A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.</p></blockquote>
<p>So lenient does protect against the programmer/user creating a invalid date in a way that the following code will result in an exception:</p>
<pre class="brush:java">    Calendar c = Calendar.getInstance();
    c.setLenient(false);
    c.set(Calendar.MONTH, Calendar.FEBRUARY);
    c.set(Calendar.DAY_OF_MONTH, 31);
    System.out.println(c.getTime());</pre>
<p>But the exception is only thrown when c.getTime() is called. Calls to getActualMaximum() still work and return 31. So lenient is not useful here.</p>
<p><strong>Lessons learned</strong></p>
<p>The quick fix for this problem is to set the DAY_OF_MONTH to 1 (or any number between 1 and 28) <strong>before</strong> setting the month.</p>
<p>I also learned that Calendar.setLenient() will not protect you from this error. It will only stop you from getting an invalid Date. It does not protect against overflows.</p>
<p><strong>Sould I use JODA time?</strong></p>
<p>At the end of this post I have a question for you. I have no experience with JODA time always preferring to use the standard Date/Time API unless there was a problem. But perhaps I should reverse my views and use JODA time unless I&#8217;m not allowed too? What do you think &#8230; is it time to stop  using the default Calendar API and use JODA time instead? Or should I wait for Java 7 with <a href="http://jcp.org/en/jsr/detail?id=310">JSR 310</a>?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spring 3.0: REST services with Spring MVC</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/16/spring-3-0-rest-services-with-spring-mvc/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/16/spring-3-0-rest-services-with-spring-mvc/#comments</comments>
		<pubDate>Sat, 16 Jan 2010 12:50:22 +0000</pubDate>
		<dc:creator>Stephan Oudmaijer</dc:creator>
				<category><![CDATA[Algemeen]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=739</guid>
		<description><![CDATA[Spring 3.0 has support for REST style WebServices, the Spring MVC controllers facilitate the functionality. In this example I will show an example of how to implement a basic REST service that uses XML marshalling to sent information over HTTP. Disclamier: this is not an in depth tutorial for building REST style WebServices.
The Spring MVC [...]]]></description>
			<content:encoded><![CDATA[<p>Spring 3.0 has support for REST style WebServices, the Spring MVC controllers facilitate the functionality. In this example I will show an example of how to implement a basic REST service that uses XML marshalling to sent information over HTTP. Disclamier: this is not an in depth tutorial for building REST style WebServices.</p>
<p><b>The Spring MVC controller</b></p>
<p>The Spring 3.0 REST support relies havily on Spring MVC. We should use the Controller class for implementing a REST style WeService. To declare a Controller I use the Spring annotation based configuration. In this example the ProductRestService class is annotated with @Controller annotation. In order for Spring to pick-up the annotation Spring needs to be configured to scan for annotation (see the Spring configuration section).</p>
<p>REST uses templates that describe the URI to be used to invoke a WebService method. These URI templates can contain variable placeholders which allow for passing information to the WebService. The URI should typically contain all the information required for invoking a WebService method. </p>
<p>The @RequestMapping annotation allowes you to define the URI and HTTP method that are mapped to a method. In this example I have annotated the ProductRestService.getProductById(Long productId) with the @RequestMapping.<br />
The value of the @RequestMapping, in this case: /products/{productId}    , defines the URI that is mapped to this method. The productId variable needs to be defined when invoking the method and will be resolved automatically by Spring MVC with the value from the request URI. You can use the @PathVariable to inject the value of the productId variable directly into a method parameter.</p>
<p>The @ResponseBody annotation tells Spring to marshall the return value of the method to the HTTP response body. Spring allowes you to configure HTTP message converters that take care of conversion of the return value to a format which is accepted by the client. In this example the return value will be marshalled to XML using XStream. </p>
<pre class="brush: java">
package com.oudmaijer.spring.rest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *  This is an example REST style MVC controller. It serves as an
 *  endpoint for retrieving Product Objects.
 */
@Controller
public class ProductRestService {

    /**
     * This method returns a specific Product. The URI to request a Product is
     * specified in the @RequestMapping.
     *
     * @param productId the identifier of the requested product
     * @return a Product
     */
    @RequestMapping(value="/products/{productId}", method = RequestMethod.GET)
    @ResponseBody
    public Product getProductById(@PathVariable Long productId) {
        Product p = new Product();
        p.setId(productId);
        return p;
    }

}
</pre>
<p><b>Spring configuration</b></p>
<p>The configuration is where all the magic happens. It is important to define the &lt;mvc:annotation-driven /&gt; element at the end of the configuration file or else Spring will not register the marshallingHttpMessageConverter. It took me some time to figure this out ;(</p>
<p>You need to add the MessageConverters to the configuration in order to get the OXM marshalling to work. Spring uses the requests <a target="new" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">Accept</a> header to determine which converter to use.</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<!-- Enable annotation scanning. -->
	<context:component-scan base-package="com.oudmaijer.spring.rest" />

	<!-- Define the OXM marshaller which is used to convert the Objects <-> XML. -->
	<bean id="oxmMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller" />

	<bean id="marshallingHttpMessageConverter"
		class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="oxmMarshaller" />
<property name="unmarshaller" ref="oxmMarshaller" />
	</bean>

	<!-- Required for REST services in order to bind the return value to the ResponseBody. -->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
			<util:list id="beanList">
				<ref bean="marshallingHttpMessageConverter" />
			</util:list>
		</property>
	</bean>

	<!-- Should be defined last! -->
	<mvc:annotation-driven />

</beans>
</script>
</pre>
<p><b>Maven2 dependencies</b></p>
<p>You need to add a couple of Maven2 dependencies to get the project up and running. Below is the entire pom.xml.</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.oudmaijer.spring.rest</groupId>
    <artifactId>spring-3.0-rest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
    <build>
<plugins>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <!-- http://maven.apache.org/plugins/maven-compiler-plugin/ -->
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
            <optional>false</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.0.0.RELEASE</version>
            <optional>false</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.0.RELEASE</version>
            <optional>false</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.0.0.RELEASE</version>
            <optional>false</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>3.0.0.RELEASE</version>
            <optional>false</optional>
        </dependency>
        <dependency>
            <groupId>xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.2.2</version>
            <optional>false</optional>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>        
    </dependencies>
</project>
</script></pre>
<p><b>Web deployment descriptor: web.xml</b></p>
<p>Last but not least the web.xml. Since the REST support in Spring is based on Spring MVC you need to define the DispatcherServlet. Make sure to map the correct URL pattern to the DispatcherServlet.</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    id="WebApp_ID" version="2.5">
  <display-name>spring-3.0-rest</display-name>
  <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/META-INF/spring/*.xml</param-value>
  </context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
      <servlet-name>DispatcherServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>DispatcherServlet</servlet-name>
      <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>
</script></pre>
<p><b>Invoking the service</b></p>
<p>This example only supports the HTTP GET method. If you want to test or build a client that uses REST WebServices you should use the RestTemplate in Spring. We can easily validate if the example WebService is running by accessing the service through Firefox. This will result in the following response.</p>
<p><img src="http://oudmaijer.com/cms/uploads/images/development/spring-rest/spring-rest.png"/></p>
<p>For more information on REST support in Spring 3.0 please refer to the <a target="_new" href="http://www.springsource.org/documentation">Spring reference documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/16/spring-3-0-rest-services-with-spring-mvc/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mockito</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/15/mockito/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/15/mockito/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 12:42:49 +0000</pubDate>
		<dc:creator>Sander Abbink</dc:creator>
				<category><![CDATA[Algemeen]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=545</guid>
		<description><![CDATA[If you want to test objects in isolation it is often usefull to use Mocks. Here is how you can do this with the Mockito framework.
First the maven dependency:

 org.mockito
  mockito-all
  1.8.1

If you don&#8217;t use a Maven plugin in let&#8217;s say Eclipse, then you can create a directory testlib which contains the jar. [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to test objects in isolation it is often usefull to use Mocks. Here is how you can do this with the Mockito framework.</p>
<p>First the maven dependency:</p>
<pre class="brush:java">
 <groupId>org.mockito</groupId>
  <artifactId>mockito-all</artifactId>
  <version>1.8.1</version>
</pre>
<p>If you don&#8217;t use a Maven plugin in let&#8217;s say Eclipse, then you can create a directory testlib which contains the jar. Add this jar to the buildpath (this won&#8217;t affect the Maven build).</p>
<p>It is also handy to use the following static imports:</p>
<pre class="brush:java">
   import static org.mockito.Mockito.*;
   import static org.junit.Assert.*;
</pre>
<p>Tip for Eclipse: if you want to prevent organize imports (ctrl+shift+o) to resolve the static imports:  java -> code style -> organize imports -> Number of static imports needed for (set to 1).</p>
<p>Creating a Mock object:</p>
<pre class="brush:java">
   List mockedlist = mock(ArrayList.class);
   mockedlist.add("Hello");
   String value = mockedlist.get(0);
   mockedlist.get(5);
</pre>
<p>All the methods in ArrayList are mocked. So the String &#8220;Hello&#8221; won&#8217;t actually be added to the List (e.g. value == null). Also get(5) won&#8217;t throw an IndexOutOfBoundsException.</p>
<p>You can also stub method calls, like this:</p>
<pre class="brush:java">
   List mockedlist = mock(ArrayList.class);
   when(mockedlist.get(0)).thenReturn("Hello");
</pre>
<p>Or verify invocations:</p>
<pre class="brush:java">
   String value = "Hello";
   verify(mockedlist).get(0);
   verify(mockedlist).add(eq(value));
   verifyNoMoreInteractions(mockedlist);
</pre>
<p>eq is a method in the Matchers class. It will verify that an object is added to the mocked List which is equal to the String &#8220;Hello&#8221;. If you use a Matcher for one argument in a method, then you have to use a Matcher for all the other arguments too.</p>
<p>See javadoc for the other Matchers methods <a href="http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Matchers.html">http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Matchers.html</a></p>
<p>You can also write your own Matcher, although this is rarely neccesary. An example:</p>
<pre class="brush:java">
class IsStringEqualButNotSame extends ArgumentMatcher {
    private String originalString;

    public IsStringEqualButNotSame (String originalString) {
	    this.originalString= originalString;
    }

    public boolean matches(Object value) {
	    return ((String)value).equals(originalString) &amp;&amp; value != originalString;
    }
}
    String value = "Hello";
    verify(mockedlist).add(argthat(new IsStringEqualButNotSame(value));
</pre>
<p>This Matcher will match if a String is logically equal but the object is not the same. Not the best example <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  but you can make Matchers this way.</p>
<p>Spying on real objects. You can spy a real object to verify interactions or to stub only one particular method. An example:</p>
<pre class="brush:java">
  List myList = new ArrayList&lt;&gt;()
  List myListSpy = spy(myList);
  myListSpy.get(5);    // will throw IndexOutOfBoundsException

  when(myListSpy.get(5)).thenReturn("Hello"); // will throw IndexOutOfBoundsException
</pre>
<p>If you stub a method like the example above the real method will still be called. You must use a slightly different syntax for this:</p>
<pre class="brush:java">
    doReturn("Hello").when(myListSpy.get(5));
</pre>
<p>Additional sources:</p>
<li><a href="http://mockito.org/">Mockito site</a></li>
<li><a href="http://code.google.com/p/mockito/wiki/MockitoVSEasyMock">Mockito vs EasyMock</a></li>
<p>Not really related to Mockito. If you annotate a method with @Before this method will be called before every unittest in the class.<br />
If you annotate a method with @BeforeClass this method will only be called once. This method must be static.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/15/mockito/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JPA Optimisitic locking versus Pessimistic locking</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/14/jpa-optimisitic-locking-versus-pessimitic-locking/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/14/jpa-optimisitic-locking-versus-pessimitic-locking/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 16:18:36 +0000</pubDate>
		<dc:creator>Peter Schuler</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Java API]]></category>
		<category><![CDATA[Object Relational Mapping]]></category>
		<category><![CDATA[JPA 2.0]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[Pessimitic Locking]]></category>
		<category><![CDATA[Versioning]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=629</guid>
		<description><![CDATA[As promised in my previous post I will blog some more about JPA and how to use it. In this post I will go into the locking features of JPA 2.0 including the new pessimistic lock options.
This post will:

introduce the new locking features of the JPA;
introduce both pessimistic locking and optimitic locking concepts;
give a quick [...]]]></description>
			<content:encoded><![CDATA[<p>As promised in my <a href="http://blog.smart-java.nl/blog/index.php/2009/12/11/jpa-2-0-finally-final/">previous post</a> I will blog some more about JPA and how to use it. In this post I will go into the locking features of JPA 2.0 including the new pessimistic lock options.</p>
<p>This post will:</p>
<ul>
<li>introduce the new locking features of the JPA;</li>
<li>introduce both pessimistic locking and optimitic locking concepts;</li>
<li>give a quick recap about JPA versioning;</li>
<li>talk about the connection between locking and design;</li>
<li>and finally compare both locking strategies.</li>
</ul>
<p><strong>JPA 2.0 now supports Pessimistic Locking:<br />
</strong></p>
<p>A great omission of JPA 1.0 was the lack of pessimistic locking. Therefore it was necessary to fall back on the support of the underlying implementation to use the JPA is situation where pessimistic locking was required. This can happen when JPA shares a database with another process which does not know or supports versioning based optimistic locking.</p>
<p>JPA 2.0 now supports the following locking modes:</p>
<ul>
<li>OPTIMISTIC                                    (==READ in JPA 1.0)</li>
<li>OPTIMISTIC_FORCE_INCREMENT         (==WRITE in JPA 1.0)</li>
<li>PESSIMISTIC_READ</li>
<li>PESSIMISTIC_WRITE</li>
<li>PESSIMISTIC_FORCE_INCREMENT       (A hybrid of both strategies)</li>
<li>READ                                               (kept around for backward compatibility)</li>
<li>WRITE                                             (kept around for compatibility)</li>
</ul>
<p>Object can be locked by using the find() or refresh() operation of the EntityManager. For example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Order order <span style="color: #339933;">=</span> entityManager.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span>Order.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #cc66cc;">10</span>, LockModeType.<span style="color: #006633;">PESSIMISTIC_READ</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SELECT ID, PRODUCT, AANTAL, VERSION, orderId FROM ORDER_TABLE WHERE <span style="color: #009900;">&#40;</span>orderId <span style="color: #339933;">=</span> <span style="color: #339933;">?</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">FOR</span> UPDATE.</pre></div></div>

<p>As you can see the FOR UPDATE is added to the select query telling the database to get an exclusive lock on this selected row.</p>
<p>You can also use the lock() method on the entityManager and specify a Lock Mode on Queries (JPQL / Named and Criteria).</p>
<p>Now that we know how to unleash the power of pessimistic locking we need to learn how to use it well.</p>
<p><strong>Locking Strategies: a quick recap….</strong></p>
<p>Locking is a means to prevent data form becoming corrupted because two different processes are editing the same data. If we use locking correctly no two processes can edit (or if required) access the same data. Thus data can never be inconsistent.</p>
<p>As already mentioned there are two locking strategies: optimistic locking and pessimistic locking. I will describe both strategies and give an overview of their pro’s and con’s.</p>
<p><strong>Pessimistic locking</strong></p>
<p>This strategy is the standard locking provided by the database. It will protect data by limiting access to a single process. This is achieved by keeping track of all the currently active locks. If another process wants to access locked data it will have to wait until the other process releases the lock. Of course this introduces a whole range of potential errors like lock timeouts and deadlocks.</p>
<p>This locking strategy is called pessimistic because of the assumption that locking is always necessary to avoid corruption. Based on that assumption it introduces significant overhead in order to keep track of which process is assessing which data. Compare pessimistic locking to a traffic light. It will only allow vehicles to pass when it knows for sure that no one will be in the way.</p>
<p>Using pessimistic locking has some pro’s:</p>
<ul>
<li>The database is in charge and protects your data. Independent from application logic.</li>
<li>A process or thread can only proceed if it has the right locks. Thus it is guaranteed that there will be no conflicts once the lock is acquired.</li>
<li>Processes are put on hold until they can acquire the lock. (This blessing can also be a curse because a process can overwrite data the moment the lock is released. This feels like a missing update but is technically the correct behaviour. But as long as you read and write in the same transction you&#8217;re data is never stale.)</li>
</ul>
<p>No pro’s without con’s:</p>
<ul>
<li>Keeping track of all those locks introduces significant overhead. Even if there is no data being accessed simultaneous the database still locks.</li>
<li>The locking can lead to deadlocks and lock time out. These errors are hard to recover from and take a long time before the calling process is informed.</li>
<li>Must be supported by the database.</li>
</ul>
<p>So pessimistic locking depends on the database restricting access to data. But this comes at high overhead and hard-to-recover errors.</p>
<p><strong>Optimistic locking</strong></p>
<p>As pessimistic locking is embedded in the DBMS, optimistic locking is a strategy that by-passes the database. It will detect conflicts only when they occur. This is done introducing a version number to every table you want to protect. If you read data you will get the version number. If you alter the data you first check the version number again, and when holding the previous read value, update the record and increment the version number. If some one has “changed the data right from under you” you will see a different version number and know that there is a conflict. I will refer to the optimistic lock procedure as check&amp;update.</p>
<p>This strategy is called optimistic because it never bothers to lock. It assumes that process will not bother each other until they do.</p>
<p>Using optimistic locking has some big pro’s:</p>
<ul>
<li>There is no (at least very little) overhead involved in locking.</li>
<li>Optimistic locking is fast and easy to use, especially because it works implicitly. If you specify a @Version the upate&amp;check will be performed automatically.</li>
<li>It’s very efficient.</li>
<li>It is database independent. No special features are required.</li>
</ul>
<p>There are also some drawbacks:</p>
<ul>
<li>It will only detect conflicts, not prevent them. When it occurs it’s the application that must resolve the conflict. For example by showing the user a diff or an option to override the current version in the database.</li>
<li>If a conflict occurs only one process is allowed to proceed. The others have their database transaction rolled back. This is far more expensive than waiting until you get the database lock.</li>
<li>It will only work if everyone accessing the database plays by the versioning rules. The database does not enforce it.</li>
<li>It can be considered ‘unfair’ as the process that writes the data first wins, opposed to the process that first acquired the lock.</li>
<li>Sometimes optimistic locking is not sufficient. Locking a complete table to protect against insert for example.</li>
</ul>
<p>So optimistic locking depends on the calling processes to respect the versioning rules. This makes it possible to detect conflicts and eliminates the need to keep of all the locks and gives Optimistic locking a huge advantage.</p>
<p>However when conflicts occurs it is up to the application to patch things up.</p>
<p><strong>JPA support for optimistic locking</strong></p>
<p>JPA supports optimistic locking based on versioning right from the first release. All you need to do is declare an attribute of your class with a @Version annotation.</p>
<p>For example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">  @<span style="color: #003399;">Entity</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Order <span style="color: #009900;">&#123;</span>
&nbsp;
      @id @GeneratedValue
      <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> id<span style="color: #339933;">;</span>
&nbsp;
      @Version
      <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> version<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The above code will result in a Order table with a primary key and version column. JPA will check and update the version after every change to Order.</p>
<p>More on JPA versioning can be found <a href="http://wiki.eclipse.org/EclipseLink/Examples/JPA/Locking">here</a>.</p>
<p><strong>Lock scope.</strong></p>
<p>At first glance versioning seems to be the preferred strategy. It’s easy to use and with little overhead. However there is one more aspect to take into account when dealing with locking. That is what I call ‘the lock scope’.</p>
<p>Versioning will only lock (check&amp;update) records that were changed. Databases will only lock records you tell it to lock by doing a SELECT … FOR UPDATE. Both procedures prevent processes from corrupting the database. But it will not prevent breaking business rules!<br />
Let’s look at the following example:<br />
<a href="http://blog.smart-java.nl/blog/wp-content/uploads/2010/01/Order_OrderLine.png"><img class="size-full wp-image-662 alignnone" title="The order model" src="http://blog.smart-java.nl/blog/wp-content/uploads/2010/01/Order_OrderLine.png" alt="" /></a><br />
This is a typical Order-&gt;OrderLine example. Order has a set of OrderLines which keep a price and quantity for every single item in Order. Let’s assume that there is a business rule that the total amount of money of an Order must stay below $10.000. This is easily achieved by adding a check on order to make sure that every addition/alteration of OrderLines will not break this rule.<br />
A problem occurs when another process comes in and adds OrderLines to an Order at the same time. No single process knows all OrderLines. To make the check work in a concurrent environment you need to make the OrderLine updates in a serial order. In other words: the Order needs to be locked before any additions can be made to OrderLines. This ensures that the business rule can be enforced.</p>
<p>The JPA can achieve this by using one of the two lock levels: OPTIMISTC_FORCE_INCREMENT or PESSIMITC_WRITE. Both will give you a exclusive lock to make sure no other process can edit the same data.</p>
<p>This example illustrates that there are situations in which you need to think ahead about locking. Both versioning and database locks won’t help you out-of-the-box . You need to determine the right lock scope. Determining the lock scope is a business question and needs to be defined based on the functional design and then translated to technical requirements.</p>
<p><strong>Choosing a locking Strategy.</strong></p>
<p>Ok .. now you know about the pro’s and con’s of both locking strategies. You know how to use them technically and you know you need to think about the lock scope. So which strategy is for winners?</p>
<p>As you probably have guessed there is no straightforward answer.</p>
<p>Optimistic locking has little overhead and is easy to use, especially because it works implicitly in JPA. But you need to make sure that everyone using the database uses the same versioning approach. It’s also more expensive in terms of conflict resolving.</p>
<p>Optimistic locking is the preferred strategy if:</p>
<ul>
<li>You’re application has a private database.</li>
<li>All the applications using the database know and use versioning.</li>
<li>It is unlikely that there will be a lot of conflicts. (eg. Users editing the same data.)</li>
</ul>
<p>Pessimistic locking will protect data on the database level. It will prevent conflicts by putting the process in a queue to wait for the lock. If there are a lot of collisions this gives a better change of more processes making it through. However having to keep a large lock administration involves a lot of overhead even if there a no conflicts.</p>
<p>So pessimistic locking it the preferred strategy if:</p>
<ul>
<li>Other non-versionized processes will edit the data you need to lock.</li>
<li>You predict / see that there will be a lot of colissions.</li>
</ul>
<p>For those among us unable to choose, JPA offers a hybrid solution. If you use the lock option PESSIMISTIC_FORCE_INCREMENT both Pessimitic and Optimisic locks are acquired at the same time. Offcourse you&#8217;re cutting of both your hands when using this option for every database call&#8230;. &#8220;Just to be sure .. &#8220;. You&#8217;ll end up with the bad from both locking strategies. But this hybird option can be a life saver when a particular table or operation must be protected at a database level and still has to participate in versionized transactions.</p>
<p><strong>More information on locking</strong></p>
<ul>
<li><a href="http://weblogs.java.net/blog/caroljmcdonald/archive/2009/07/jpa_20_concurre.html">JPA 2.0 Concurrency and locking</a> &#8211; Shows transcipts of most lokcing possibilities.</li>
<li><a href="http://www.avaje.org/occ.html">Explanation of Optimistic Concurrency Checking</a> &#8211; Talks some more about optimisitic locking.</li>
</ul>
<p>And don’t forget to think about the lock scope!</p>
<p>This is the second installment of my blogs about the JPA. Next time we’ll go into the new Criteria API of JPA 2.0.</p>
<ul>
<li><span style="font-size: 10px;">Special thanks to Martijn Blankestijn for the Order example and Jouke Stoel for test reading.</span></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/14/jpa-optimisitic-locking-versus-pessimitic-locking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
