<?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 &#187; Algemeen</title>
	<atom:link href="http://blog.smart-java.nl/blog/index.php/category/algemeen/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smart-java.nl/blog</link>
	<description>Ordina J-Technologies - Java Blog</description>
	<lastBuildDate>Wed, 05 May 2010 20:06:33 +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>How to de-frameset a Web App with Apache Tiles 2</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 15:45:12 +0000</pubDate>
		<dc:creator>Assen Kolov</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tiles]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=995</guid>
		<description><![CDATA[To get rid of FRAMESET, a servlet renders any desired URL embodied in a tiles definition.]]></description>
			<content:encoded><![CDATA[<h3>
The problem</h3>
<p>There&#8217;s is a good old application from the days when struts still had to be invented and framesets weren&#8217;t considered evil. The problems associated with a FRAMESET are another topic, the fact is the application owner wants to get rid of them and asked me to look for a solution that would be unobtrusive and easy to implement, understand and maintain.</p>
<h3>
Current Situation</h3>
<p>The application uses no web-app framework, each Use Case is implemented in a separate servlet,  all of them neatly mapped in the web.xml. The FRAMESET setup is classic: apart from the static elements, the navigation happens in a &#8216;body&#8217; and a &#8216;menu&#8217; frame. The normal flow is to select a command from the menu frame, e.g. Place Order results in (&lt;a href=&#8221;/placeorder&#8221; target=&#8221;&#8216;body&#8221;/&gt;), then submit a few forms in the body frame (&lt;form action=&#8221;/placeorder&#8221; method=&#8221;POST&#8221;&gt;&#8230;&lt;/form&gt;). Without frameset, when a HTTP request for /placeorder reaches the application, we want the servlet response decorated  with the other fragments: menu, header and the rest. The differences are essential: there is just one request/response and all page fragments have to share the same HEAD, CSS etc.</p>
<h3>
Introducing Apache Tiles 2</h3>
<p>The good news is that version 2.x of Apache Tiles, which has started as struts extension, is now framework-independent. It offers support for JSP, Freemarker, and can be used directly from a servlet or filter. First of all, a template is needed to replace the frameset, e.g. main.jsp:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;%@ taglib uri=&quot;http://tiles.apache.org/tags-tiles&quot; prefix=&quot;tiles&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
 &lt;link href=&quot;/online/theme/online.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;
    &lt;script language=&quot;javascript&quot; src=&quot;/online/js/algemeen.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;table border=&quot;1&quot; cellspacing=&quot;0&quot; cellpadding=&quot;0&quot;
 style=&quot;width: 100%; height: 100%&quot;&gt;
 &lt;tr&gt;
  &lt;td colspan=&quot;2&quot;&gt;&lt;tiles:insertAttribute name=&quot;top&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
  &lt;td&gt;&lt;tiles:insertAttribute name=&quot;menu&quot; /&gt;&lt;/td&gt;
  &lt;td&gt;&lt;tiles:insertAttribute name=&quot;body&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
  &lt;td colspan=&quot;2&quot;&gt;&lt;tiles:insertAttribute name=&quot;bottom&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</script></pre>
<p>Based on that template a tile definition can render a decorated view of any servlet output (e.g. /placeorder). A definition per servlet is needed in tiles.xml:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE tiles-definitions PUBLIC
       &quot;-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN&quot;
       &quot;http://tiles.apache.org/dtds/tiles-config_2_0.dtd&quot;&gt;

&lt;tiles-definitions&gt;

 &lt;definition name=&quot;placeorder.tile&quot; template=&quot;/layout/main.jsp&quot;&gt;
  &lt;put-attribute name=&quot;top&quot; value=&quot;/algemeen/onlinetop.html&quot; /&gt;
  &lt;put-attribute name=&quot;menu&quot; value=&quot;/besturing/menu.jsp&quot; /&gt;
  &lt;put-attribute name=&quot;body&quot; value=&quot;/placeorder&quot; /&gt;
  &lt;put-attribute name=&quot;bottom&quot; value=&quot;/algemeen/onlinebottom.html&quot; /&gt;
 &lt;/definition&gt;
&lt;/tiles-definitions&gt;

</script></pre>
<p>This definition still has to be rendered, e.g. from another JSP, let&#8217;s call it placeholder_tiled.jsp:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
    pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;%@ taglib uri=&quot;http://tiles.apache.org/tags-tiles&quot; prefix=&quot;tiles&quot; %&gt;

&lt;tiles:insertDefinition name=&quot;placeorder.tile&quot; /&gt;
</script></pre>
<p>A separate tile definition and a JSP page for each servlet would be too much code repetition. Let&#8217;s see how to the output of any servlet.</p>
<h3>
A View decorating servlet</h3>
<p>I like the idea of having separate URLs for the servlet output and for a composite view of the same output. Thanks to Tiles 2 API, one servlet could provide decorated views of the output of all servlets. In tiles.xml, I added a tile definition with all attributes except body defined:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE tiles-definitions PUBLIC
       &quot;-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN&quot;
       &quot;http://tiles.apache.org/dtds/tiles-config_2_0.dtd&quot;&gt;

&lt;tiles-definitions&gt;
 &lt;definition name=&quot;main.tile&quot; template=&quot;/layout/main.jsp&quot;&gt;
  &lt;put-attribute name=&quot;top&quot; value=&quot;/algemeen/onlinetop.html&quot; /&gt;
  &lt;put-attribute name=&quot;menu&quot; value=&quot;/besturing/menu.jsp&quot; /&gt;
  &lt;!-- name=&quot;body&quot;  not defined --&gt;
  &lt;put-attribute name=&quot;bottom&quot; value=&quot;/algemeen/onlinebottom.html&quot; /&gt;
 &lt;/definition&gt;

&lt;/tiles-definitions&gt;

</script></pre>
<p>Let&#8217;s define a servlet that will fill in the missing body attribute for each URL ending with .tiled:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;servlet&gt;
 &lt;display-name&gt;TilesServlet&lt;/display-name&gt;
 &lt;servlet-name&gt;TilesServlet&lt;/servlet-name&gt;
 &lt;servlet-class&gt;com.assenkolov.common.web.TilesServlet&lt;/servlet-class&gt;
 &lt;init-param&gt;
 &lt;param-name&gt;template.name&lt;/param-name&gt;&lt;param-value&gt;main.tile&lt;/param-value&gt;&lt;/init-param&gt;
 &lt;init-param&gt;
 &lt;param-name&gt;attribute.name&lt;/param-name&gt;&lt;param-value&gt;body&lt;/param-value&gt;&lt;/init-param&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
 &lt;servlet-name&gt;TilesServlet&lt;/servlet-name&gt;
 &lt;url-pattern&gt;*.tiled&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</script></pre>
<p>Finally, the servlet itself:</p>
<pre><script type="syntaxhighlighter" class="brush: java">public class TilesServlet extends HttpServlet {
 private String templateName;
 private String attributeName;

 @Override
 public void init() throws ServletException {
  super.init();
  templateName = getInitParameter("template.name");
  attributeName = getInitParameter("attribute.name");
 }

 @Override
 public void service(HttpServletRequest request, HttpServletResponse response) 
  throws  ServletException, IOException {
   ServletContext servletContext = request.getSession().getServletContext();

   TilesContainer container = ServletUtil.getContainer(servletContext);
   AttributeContext attributeContext = container.startContext(request, response);

   // Remove the ".tiled" suffix from the request path
   String requestPath = request.getServletPath().replace(".tiled", "");
   Attribute attr = new Attribute(requestPath);

   Map<string, attribute=""> attrs = new HashMap<string, attribute="">();
   attrs.put(attributeName, attr);
   attributeContext.addAll(attrs);

   container.render(templateName, request, response);
   container.endContext(request, response);
  }
}
</script></pre>
<p>This servlet always renders the same tiles definition, providing an appropriate body. For example, a request to /showOrder.tiled?orderId=100 would render the output of /showOrder?orderId=100 as the body tile in the tiles definition. No separate tiles definition and JSP for each view are needed.</p>
<h3>
What&#8217;s next?</h3>
<p>All the code above only provides an easy template-decorated view for each servlet output. There is sill a lot of work that has to be done manually:<br />
- move all separate styles, scripts etc. from the separate pages to the template<br />
- requestDispacher.forward in a servlet closes the output stream while it is still needed for the tiles template; all forwards must become includes;<br />
- all navigation javascript referring to top.menu ot top.body has to be refatored manually.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>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>4</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>
		<item>
		<title>Spring Security 3.0 and CAS 3.3.4 integration</title>
		<link>http://blog.smart-java.nl/blog/index.php/2009/12/29/spring-security-3-0-and-cas-3-3-4-integration/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2009/12/29/spring-security-3-0-and-cas-3-3-4-integration/#comments</comments>
		<pubDate>Tue, 29 Dec 2009 08:43:31 +0000</pubDate>
		<dc:creator>Stephan Oudmaijer</dc:creator>
				<category><![CDATA[Algemeen]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=608</guid>
		<description><![CDATA[
JA-SIG Central Authentication Service (CAS) is an enterprise level, open-source, single sign on solution with a Java server component and various client libraries written in a multitude of languages including PHP, PL/SQL, Java, .Net, PHP, Perl and more.
Both Spring Security 3.0 and Spring 3.0 where released this month. Spring Security provides excelent support for CAS. [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://oudmaijer.com/cms/uploads/images/security/cas/casLogo.jpg"/><br />
JA-SIG Central Authentication Service (CAS) is an enterprise level, open-source, single sign on solution with a Java server component and various client libraries written in a multitude of languages including PHP, PL/SQL, Java, .Net, PHP, Perl and more.</p>
<p>Both Spring Security 3.0 and Spring 3.0 where released this month. Spring Security provides excelent support for CAS. In Spring Security 3.0 a couple of CAS integration components have been changed (renamed). The configuration is also a bit different from Spring Security 2.0.x. </p>
<p><b>How CAS works</b><br />
The CAS Server webapp should be deployed on an application server. Applications can use the CAS Server for the authentication process. CAS only provides authentication and no authorisation. The authorisation should be implemented (using Spring Security) by the applications using the CAS Server. </p>
<p><b>How Spring Security fits in</b><br />
Lets say an user tries to access a protected resource within an application using Spring Security. Spring Security intercepts the request and checks if the user should be authenticated. If so, the user is forwarded tot the CAS login page. The users typically enters his username and password and submits it to the CAS server. If the user was successfully authenticated by CAS, the users will be redirected back to the application where it was accessing a protected resource. The redirect URL now contains a ticket generated by CAS. Spring Security will use this ticket to validate against CAS if the ticket is valid for this user. If so, the user details will be loaded by Spring Security. If the user is also authorised to access the protected resource, access will be granted.</p>
<p><b>Configuration</b><br />
For my demo I use the CAS server webapp version 3.3.4. I have it deployed on Apache Tomcat 6.0.20. In the demo I access the CAS Server using HTTP, this should be HTTPS in a production environment! I have deployed the applications using the following URLs:<br/></p>
<li>The CAS Server web application: http://localhost:8080/cas-server-webapp-3.3.4/</li>
<li>The application using CAS: http://localhost:8080/spring-security-cas/</li>
<p>I use Maven2 for managing my dependencies, the following libraries should be added to the pom.xml.</p>
<p><b>Maven2 dependencies</b></p>
<pre class="brush:xml">
<dependencies>
	<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-webmvc</artifactId>
		<version>3.0.0.RELEASE</version>
		<optional>false</optional>
	</dependency>
	<dependency>
		<groupId>org.springframework.security</groupId>
		<artifactId>spring-security-core</artifactId>
		<version>3.0.0.RELEASE</version>
		<optional>false</optional>
	</dependency>
	<dependency>
		<groupId>org.springframework.security</groupId>
		<artifactId>spring-security-config</artifactId>
		<version>3.0.0.RELEASE</version>
		<optional>false</optional>
	</dependency>
	<dependency>
		<groupId>org.springframework.security</groupId>
		<artifactId>spring-security-cas-client</artifactId>
		<version>3.0.0.RELEASE</version>
		<optional>false</optional>
	</dependency>
</dependencies>
</pre>
<p><b>Spring Security configuration</b><br />
Please be aware that the Spring Security reference documentation is <a href="http://jira.springframework.org/browse/SEC-1344">not 100% accurate</a> on the CAS integration.</p>
<pre class="brush:xml">
<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

	<!--
		Enable security, let the casAuthenticationEntryPoint handle all intercepted urls.
		The CAS_FILTER needs to be in the right position within the filter chain.
	-->
	<security:http entry-point-ref="casAuthenticationEntryPoint" auto-config="true">
		<security:intercept-url pattern="/**" access="ROLE_USER"></security:intercept-url>
		<security:custom-filter position="CAS_FILTER" ref="casAuthenticationFilter"></security:custom-filter>
	</security:http>

	<!--
		Required for the casProcessingFilter, so define it explicitly set and
		specify an Id Even though the authenticationManager is created by
		default when namespace based config is used.
	-->
	<security:authentication-manager alias="authenticationManager">
		<security:authentication-provider ref="casAuthenticationProvider"></security:authentication-provider>
	</security:authentication-manager>

	<!--
		This section is used to configure CAS. The service is the
		actual redirect that will be triggered after the CAS login sequence.
	-->
	<bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
<property name="service" value="http://localhost:8080/spring-security-cas/j_spring_cas_security_check"></property>
<property name="sendRenew" value="false"></property>
	</bean>	

        <!--
		The CAS filter handles the redirect from the CAS server and starts the ticket validation.
	-->
	<bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"></property>
	</bean>

	<!--
		The entryPoint intercepts all the CAS authentication requests.
		It redirects to the CAS loginUrl for the CAS login page.
	-->
	<bean id="casAuthenticationEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
<property name="loginUrl" value="http://localhost:8080/cas-server-webapp-3.3.4/login"></property>
<property name="serviceProperties" ref="serviceProperties"></property>
	</bean>

	<!--
		Handles the CAS ticket processing.
	 -->
	<bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<property name="userDetailsService" ref="userService"></property>
<property name="serviceProperties" ref="serviceProperties"></property>
<property name="ticketValidator">
			<bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
				<constructor-arg index="0" value="http://localhost:8080/cas-server-webapp-3.3.4"></constructor>
			</bean>
		</property>
<property name="key" value="cas"></property>
	</bean>

	<!--
		The users available for this application.
	-->
	<security:user-service id="userService">
		<security:user name="user" password="user" authorities="ROLE_USER"></security:user>
	</security:user-service>
</beans>
</pre>
<p><b>web.xml</b></p>
<pre 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>webapp</display-name>

	<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-security.xml</param-value>
	</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>
</pre>
<p>Thats it, try it yourself!</p>
<p><i>Original article posted at: <a href="http://oudmaijer.com/cms/index.php?mact=News,cntnt01,detail,0&#038;cntnt01articleid=21&#038;cntnt01returnid=57">http://oudmaijer.com</a></i></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2009/12/29/spring-security-3-0-and-cas-3-3-4-integration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A lot of exciting new stuff in december: Spring 3.0 &amp; Java EE 6</title>
		<link>http://blog.smart-java.nl/blog/index.php/2009/12/21/a-lot-of-new-stuff-in-december/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2009/12/21/a-lot-of-new-stuff-in-december/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 13:28:13 +0000</pubDate>
		<dc:creator>Stephan Oudmaijer</dc:creator>
				<category><![CDATA[Algemeen]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=598</guid>
		<description><![CDATA[The last month of 2009 has brought some exciting Java news, both Java EE 6 and Spring 3.0 have become final this month!
Spring Framework 3.0 GA
Spring 3.0 GA is compatible with Java EE 6 final in terms of runtime environments now (e.g. on GlassFish v3 as released last week) and supports JPA 2.0 final already [...]]]></description>
			<content:encoded><![CDATA[<p>The last month of 2009 has brought some exciting Java news, both Java EE 6 and Spring 3.0 have become final this month!</p>
<p><strong><a href="http://blog.springsource.com/2009/12/16/spring-framework-3-0-goes-ga/" target="_self">Spring Framework 3.0 GA</a></strong></p>
<p>Spring 3.0 GA is compatible with Java EE 6 final in terms of runtime environments now (e.g. on GlassFish v3 as released last week) and supports JPA 2.0 final already (e.g. using EclipseLink 2.0). We also support the newly introduced <a onclick="javascript:urchinTracker('/outbound/java.sun.com');" href="http://java.sun.com/javaee/6/docs/api/javax/annotation/ManagedBean.html">@ManagedBean</a> (JSR-250 v1.1) annotation for component scanning now, which nicely complements our <a onclick="javascript:urchinTracker('/outbound/java.sun.com');" href="http://java.sun.com/javaee/6/docs/api/javax/inject/Inject.html">@Inject</a> (JSR-330) support for annotation-driven dependency injection.</p>
<p><strong>* Spring expression language (SpEL):</strong> a core expression parser for use in bean definitions, allowing for references to nested bean structures (e.g. properties of other beans) as well as to environmental data structures (e.g. system property values) through a common #{…} syntax in property values.</p>
<p>* <strong>Extended support for annotation-based components:</strong> now with the notion of configuration classes and annotated factory methods (as known from Spring JavaConfig). Spring also allows for injecting configuration values through @Value expressions now, referring to configuration settings via dynamic #{…} expressions or static ${…} placeholders.</p>
<p>* <strong>Powerful stereotype model:</strong> allows for creating &#8217;shortcut&#8217; annotations through the use of meta-annotations, e.g. for default scopes and default transactional characteristics on custom stereotypes. Imagine a custom @MyService annotation indicating @Service, @Scope(&#8220;request&#8221;) and @Transactional(readOnly=true) through a single annotation.</p>
<p>* <strong>Standardized dependency injection annotations:</strong> Spring 3.0 comes with full support for the JSR-330 specification for Dependency Injection in Java – annotation-driven injection via @Inject and its associated qualifier and provider model, as an alternative to Spring&#8217;s own @Autowired and co.</p>
<p>* <strong>Declarative model validation based on constraint annotations:</strong> Spring-style setup of a JSR-303 Bean Validation provider (such as Hibernate Validator 4.0). Comes with an annotation-driven validation option in Spring MVC, exposing a unified view on constraint violations through Spring’s binding result facility.</p>
<p>* <strong>Enhanced binding and annotation-driven formatting</strong>: Converter and Formatter SPIs as an alternative to standard PropertyEditors. Formatting may be driven by annotations in a style similar to JSR-303 constraints, e.g. using @DateTimeFormat. Also, check out the new mvc namespace for convenient setup of formatting and validation in Spring MVC.</p>
<p>* <strong>Comprehensive REST support:</strong> native REST capabilities in Spring MVC, such as REST-style request mappings, URI variable extraction through @PathVariable parameters, and view resolution driven by content negotiation. Client-side REST support is available in the form of a RestTemplate class.</p>
<p>* <strong>Rich native Portlet 2.0 support:</strong> Spring MVC fully supports Portlet 2.0 environments and Portlet 2.0’s new event and resource request model. Includes specialized mapping facilities for typical portlet request characteristics: @ActionMapping, @RenderMapping, @ResourceMapping, @EventMapping.</p>
<p>* <strong>Object/XML Mapping (OXM):</strong> as known from Spring Web Services, now in Spring Framework core. Marshalling and Unmarshaller abstractions with out-of-the-box support for JAXB 2, Castor, etc. Comes with integration options for XML payloads in Spring MVC and Spring JMS.</p>
<p>* <strong>Next-generation scheduling capabilities:</strong> new TaskScheduler and Trigger mechanisms with first-class cron support. Spring 3.0 comes with a convenient task namespace and also supports @Async and @Scheduled annotations now. This can be executed on top of native thread pools or server-managed thread pools.</p>
<p><strong><a href="http://jcp.org/en/jsr/detail?id=316" target="_blank">Java EE 6</a></strong></p>
<p>From <a href="http://weblogs.java.net/blog/robc/archive/2009/12/01/java-ee-6-platform-approved-today">Roberto Chinnici&#8217;s weblog</a>:</p>
<p><em>With the closing of the final approval ballot earlier today, it is now official: the JCP Executive Committee has given a green light to the release of the Java EE 6 platform specification. The final release will happen on December 10, when <a href="https://glassfish.dev.java.net/">GlassFish v3</a> will be available. For more details of the ballot, with comments from several EC members, please refer to <a href="http://jcp.org/en/jsr/results?id=5025" target="_blank">the JCP web site</a>. Of course the excitement of the event drove me to watch live the ballot close at midnight PT and <a href="https://twitter.com/robc2/status/6229390753" target="_blank">tweet</a> about it!</em></p>
<p><em>Several other Java EE component JSRs were approved at the same time: Servlet 3.0, JPA 2.0, EJB 3.1, Connector 1.6, CDI 1.0. All other components, be they full JSRs or maintenance releases (MRs, for insiders), had been previously approved. I should also mention here that, being part of the platform JSR (JSR-316) the Java EE 6 Web Profile too was approved, and so was the Managed Beans 1.0 specification I talked about in prior blog entries. So, yes, now we really have profiles in Java EE: let&#8217;s put them to good use!</em></p>
<p><em>We are going to have more white papers, tutorials, etc. coming up for the final release in a few days. In the meantime, even a casual perusal of the <a href="http://javadoc.glassfish.org/javaee6/apidoc/" target="_blank">javadocs</a> will show a number of new APIs in key areas: JAX-RS, Dependency Injection, CDI, Bean Validation. I see a bright future for these APIs, and fully expect them to become key components of Java EE applications in the coming years. I also happen to think that the level of integration that we achieved between these new APIs and some of the existing ones represents a valuable principle that can guide the evolution of Java EE going forward; certainly I expect future Java EE APIs to be held to the same strict criteria for integration with the rest of the platform that JAX-RS, Bean Validation and CDI were held to in this release.</em></p>
<p>Java EE 6 includes:</p>
<ul>
<li>Java Persistency API 2.0</li>
<li>JavaServer Faces 2.0</li>
<li>Enterprise JavaBeans 3.1</li>
<li>Servlet 3.0</li>
<li>Context and Dependecy Injection (a.k.a. WebBeans)</li>
<li>Dependency Injection (@Inject)</li>
<li>JAX-RS</li>
<li>Web Profile</li>
<li>and much more&#8230;</li>
</ul>
<p>See also this article for more information: <a href="http://java.sun.com/developer/technicalArticles/JavaEE/JavaEE6Overview.html" target="_blank">http://java.sun.com/developer/technicalArticles/JavaEE/JavaEE6Overview.html</a></p>
<p>So if you are bored during the christmas holiday, you can try out the new Java EE 6 features using <a href="https://glassfish.dev.java.net/downloads/v3-final.html">GlassFish v3</a> and <a href="http://netbeans.org/downloads/index.html">NetBeans 6.8</a>. But also <a href="http://www.jetbrains.com/idea/whatsnew/index.html#Java_EE_6_Support" target="_blank">IntelliJ 9 </a>and Eclipse 3.5.1 feature Java EE 6 support.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2009/12/21/a-lot-of-new-stuff-in-december/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sun Certified JSF Developer exam coming up?</title>
		<link>http://blog.smart-java.nl/blog/index.php/2009/12/16/sun-certified-jsf-developer-exam-comming-up/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2009/12/16/sun-certified-jsf-developer-exam-comming-up/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 23:31:17 +0000</pubDate>
		<dc:creator>Ron Thijssen</dc:creator>
				<category><![CDATA[Algemeen]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=590</guid>
		<description><![CDATA[Just received an email message from the jsr-314 mailing list, where Ed Burns states that he will be working on creating the new Sun Certified JSF Developer exam.
Looking foreward on taking this examen when it&#8217;s finished, but first let&#8217;s submit some questions  
I&#8217;m going heads-down trying to help create the new Sun Certified JSF
Developer [...]]]></description>
			<content:encoded><![CDATA[<p>Just received an email message from the jsr-314 mailing list, where Ed Burns states that he will be working on creating the new Sun Certified JSF Developer exam.</p>
<p>Looking foreward on taking this examen when it&#8217;s finished, but first let&#8217;s submit some questions <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<blockquote><p>I&#8217;m going heads-down trying to help create the new Sun Certified JSF<br />
Developer exam (and accompanying course) so I&#8217;ll be slower than usual to<br />
respond to emails.</p>
<p>If you need an immediate response, call me on my phone below.</p>
<p>If you want to help out with the exam, submit questions here:<br />
&lt;<a href="http://bit.ly/jsf2certexam" target="_blank">http://bit.ly/jsf2certexam</a>&gt;.</p>
<p>Thanks for your understanding!</p>
<p>Ed</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2009/12/16/sun-certified-jsf-developer-exam-comming-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
