<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6753769565491687768</id><updated>2012-01-24T19:06:29.508+01:00</updated><category term='hades'/><category term='logging'/><category term='perf4j'/><category term='quartz'/><category term='design patterns'/><category term='javascript'/><category term='jfreechart'/><category term='jaxb'/><category term='mule'/><category term='h2'/><category term='books'/><category term='junit'/><category term='spring mvc'/><category term='maven'/><category term='tomcat'/><category term='struts2'/><category term='apache cxf'/><category term='gorm'/><category term='freemarker'/><category term='grails'/><category term='commons'/><category term='transactions'/><category term='ejb'/><category term='wicket'/><category term='spring'/><category term='cglib'/><category term='jolokia'/><category term='sun'/><category term='javarebel'/><category term='logback'/><category term='warsaw-jug'/><category term='bezpieczeństwo'/><category term='nosql'/><category term='tdd'/><category term='performance'/><category term='bpmn'/><category term='review'/><category term='jmx'/><category term='activiti'/><category term='hibernate'/><category term='spring-js'/><category term='scala'/><category term='refactoring'/><category term='wadl'/><category term='esb'/><category term='hamcrest'/><category term='aop'/><category term='monitoring'/><category term='aspectj'/><category term='web services'/><category term='mongodb'/><category term='slf4j'/><category term='concurrency'/><category term='jmeter'/><category term='log4j'/><category term='rest'/><category term='intellij idea'/><category term='jquery'/><category term='highcharts'/><category term='ddd'/><category term='ehcache'/><category term='jpa'/><category term='groovy'/><category term='logback-feed'/><category term='servlets'/><category term='jboss'/><category term='certyfikacja'/><category term='jruby'/><category term='jqgrid'/><category term='testing'/><category term='jqplot'/><category term='conferences'/><title type='text'>NoBlogDefFound</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>69</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-5305414479093175056</id><published>2012-01-24T18:57:00.000+01:00</published><updated>2012-01-24T19:06:29.515+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='wadl'/><category scheme='http://www.blogger.com/atom/ns#' term='rest'/><category scheme='http://www.blogger.com/atom/ns#' term='jaxb'/><title type='text'>Gentle introduction to WADL (in Java)</title><content type='html'>WADL (&lt;a href="http://en.wikipedia.org/wiki/Web_Application_Description_Language"&gt;Web Application Description Language&lt;/a&gt;) is to REST what WSDL is to SOAP. The mere existence of this language causes a lot of controversy (see: &lt;a href="http://bitworking.org/news/193/Do-we-need-WADL"&gt;Do we need WADL?&lt;/a&gt; and &lt;a href="http://bill.burkecentral.com/2009/05/21/to-wadl-or-not-to-wadl/"&gt;To WADL or not to WADL&lt;/a&gt;). I can think of few legitimate use cases for using WADL, but if you are here already, you are probably not seeking for yet another discussion. So let us move forward to the WADL itself.&lt;br /&gt;&lt;br /&gt;In principle WADL is similar to WSDL, but the structure of the language is much different. Whilst WSDL defines a flat list of messages and operations either consuming or producing some of them, WADL emphasizes the hierarchical nature of RESTful web services. In REST, the primary artifact is the resource. Each resource (noun) is represented as an URI. Every resource can define both CRUD operations (verbs, implemented as HTTP methods) and nested resources. The nested resource has a strong relationship with a parent resource, typically representing an ownership.&lt;br /&gt;&lt;br /&gt;A simple example would be &lt;code&gt;http://example.com/api/books&lt;/code&gt; resource representing a list of books. You can (HTTP) GET this resource, meaning to retrieve the whole list. You can also GET the &lt;code&gt;http://example.com/api/books/7&lt;/code&gt; resource, fetching the details of 7th book inside &lt;code&gt;books&lt;/code&gt; resource. Or you can even PUT new version or DELETE the resource altogether using the same URI. You are not limited to a single level of nesting: GETting &lt;code&gt;http://example.com/api/books/7/reviews?page=2&amp;amp;size=10&lt;/code&gt; will retrieve the second page (up to 10 items) of reviews of 7th book. Obviously you can also place other resources next to &lt;code&gt;books&lt;/code&gt;, like &lt;code&gt;http://example.com/api/readers&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;The requirement arose to formally and precisely describe every available resource, method, request and response, just like WSDL guys were able to do. WADL is one of the options to describe “available URIs", although some believe that well-written REST service should be self-descriptive (see &lt;a href="http://en.wikipedia.org/wiki/HATEOAS"&gt;HATEOAS&lt;/a&gt;). Nevertheless here is a simple, empty WADL document:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&amp;lt;application xmlns="http://wadl.dev.java.net/2009/02"&amp;gt;&lt;br /&gt;    &amp;lt;resources base="http://example.com/api"/&amp;gt;&lt;br /&gt;&amp;lt;/application&amp;gt;&lt;br /&gt;&lt;/pre&gt;Nothing fancy here. Note that the &lt;code&gt;&amp;lt;resources&amp;gt;&lt;/code&gt; tag defines base API address. All named resources, which we are just about to add, are relative to this address. Also you can define several &lt;code&gt;&amp;lt;resources&amp;gt;&lt;/code&gt; tags to describe more than one APIs. So, let's add a simple resource:&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml; highlight: 3"&gt;&amp;lt;application xmlns="http://wadl.dev.java.net/2009/02"&amp;gt;&lt;br /&gt;    &amp;lt;resources base="http://example.com/api"&amp;gt;&lt;br /&gt;        &amp;lt;resource path="books"&amp;gt;&lt;br /&gt;            &amp;lt;method name="GET"/&amp;gt;&lt;br /&gt;            &amp;lt;method name="POST"/&amp;gt;&lt;br /&gt;        &amp;lt;/resource&amp;gt;&lt;br /&gt;    &amp;lt;/resources&amp;gt;&lt;br /&gt;&amp;lt;/application&amp;gt;&lt;br /&gt;&lt;/pre&gt;This defines resource under &lt;code&gt;http://example.com/api/books&lt;/code&gt; with two methods possible: GET to retrieve the whole list and POST to create (add) new item. Depending on your requirements you might want to allow DELETE method as well (to delete &lt;b&gt;all&lt;/b&gt; items), and it is the responsibility of WADL to document what is allowed.&lt;br /&gt;&lt;br /&gt;Remember our example at the beginning: &lt;code&gt;/books/7&lt;/code&gt;? Obviously 7 is just an example and we won't declare every possible book id in WADL. Instead there is a handy placeholder syntax:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml; highlight: [5,6]"&gt;&amp;lt;application xmlns="http://wadl.dev.java.net/2009/02"&amp;gt;&lt;br /&gt;    &amp;lt;resources base="http://example.com/api"&amp;gt;&lt;br /&gt;        &amp;lt;resource path="books"&amp;gt;&lt;br /&gt;            &amp;lt;method name="GET"/&amp;gt;&lt;br /&gt;            &amp;lt;resource path="{bookId}"&amp;gt;&lt;br /&gt;                &amp;lt;param required="true" style="template" name="bookId"/&amp;gt;&lt;br /&gt;                &amp;lt;method name="GET"/&amp;gt;&lt;br /&gt;            &amp;lt;/resource&amp;gt;&lt;br /&gt;        &amp;lt;/resource&amp;gt;&lt;br /&gt;    &amp;lt;/resources&amp;gt;&lt;br /&gt;&amp;lt;/application&amp;gt;&lt;br /&gt;&lt;/pre&gt;There are two important aspects you should note: first, The &lt;code&gt;{bookId}&lt;/code&gt; place-holder was used in place of &lt;i&gt;nested&lt;/i&gt; resource. Secondly, to make it clear, we are documenting this place-holder using &lt;code&gt;&amp;lt;param/&amp;gt;&lt;/code&gt; tag. We will see soon how it can be used in combination with methods. Just to make sure you are still with me, the document above describes &lt;code&gt;GET /books&lt;/code&gt; and &lt;code&gt;GET /books/some_id&lt;/code&gt; resources.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml; highlight: [12,13, 19]"&gt;&amp;lt;application xmlns="http://wadl.dev.java.net/2009/02"&amp;gt;&lt;br /&gt;    &amp;lt;resources base="http://example.com/api"&amp;gt;&lt;br /&gt;        &amp;lt;resource path="books"&amp;gt;&lt;br /&gt;            &amp;lt;method name="GET"/&amp;gt;&lt;br /&gt;            &amp;lt;resource path="{bookId}"&amp;gt;&lt;br /&gt;                &amp;lt;param required="true" style="template" name="bookId"/&amp;gt;&lt;br /&gt;                &amp;lt;method name="GET"/&amp;gt;&lt;br /&gt;                &amp;lt;method name="DELETE"/&amp;gt;&lt;br /&gt;                &amp;lt;resource path="reviews"&amp;gt;&lt;br /&gt;                    &amp;lt;method name="GET"&amp;gt;&lt;br /&gt;                        &amp;lt;request&amp;gt;&lt;br /&gt;                            &amp;lt;param name="page" required="false" default="1" style="query"/&amp;gt;&lt;br /&gt;                            &amp;lt;param name="size" required="false" default="20" style="query"/&amp;gt;&lt;br /&gt;                        &amp;lt;/request&amp;gt;&lt;br /&gt;                    &amp;lt;/method&amp;gt;&lt;br /&gt;                &amp;lt;/resource&amp;gt;&lt;br /&gt;            &amp;lt;/resource&amp;gt;&lt;br /&gt;        &amp;lt;/resource&amp;gt;&lt;br /&gt;        &amp;lt;resource path="readers"&amp;gt;&lt;br /&gt;            &amp;lt;method name="GET"/&amp;gt;&lt;br /&gt;        &amp;lt;/resource&amp;gt;&lt;br /&gt;    &amp;lt;/resources&amp;gt;&lt;br /&gt;&amp;lt;/application&amp;gt;&lt;br /&gt;&lt;/pre&gt;The web service is getting complex, however it describes quite a lot of operations. First of  all &lt;code&gt;GET /books/42/reviews&lt;/code&gt; is a valid operation. But the interesting part is the nested &lt;code&gt;&amp;lt;request/&amp;gt;&lt;/code&gt; tag. As you can see we can describe parameters of each method independently. In our case optional &lt;code&gt;query&lt;/code&gt; parameters (as opposed to &lt;code&gt;template&lt;/code&gt; parameters used previously for URI place-holders) were defined. This gives the client additional knowledge about acceptable &lt;code&gt;page&lt;/code&gt; and &lt;code&gt;size&lt;/code&gt; query parameters. This means that &lt;code&gt;/books/7/reviews?page=2&amp;amp;size=10&lt;/code&gt; is a valid resource identifier. And did I mention that every resource, method and parameter can have documentation attached as per the WADL specification?&lt;br /&gt;&lt;br /&gt;We will stop here and only mention about remaining pieces of WADL. First of all, as you have probably guessed so far, there is also a &lt;code&gt;&amp;lt;response/&amp;gt;&lt;/code&gt; child tag possible for each &lt;code&gt;&amp;lt;method/&amp;gt;&lt;/code&gt;. Both request and response can define exact grammar (e.g. in XML Schema) that either the request or the response must follow. The response can also document possible HTTP response codes. But since we will be using the knowledge you have gained so far in a code-first application, I intentionally left the &lt;code&gt;&amp;lt;grammars/&amp;gt;&lt;/code&gt; definition. WADL is agile and it allows you to define as little (or as much) information as you need.&lt;br /&gt;&lt;br /&gt;So we know the basics of WADL, now we would like to use it, maybe as a consumer or as a producer in a Java-based application. Fortunately there is a &lt;a href="http://www.w3.org/Submission/wadl/wadl.xsd"&gt;&lt;code&gt;wadl.xsd&lt;/code&gt;&lt;/a&gt; XML Schema description of the language itself, which we can use to generate JAXB-annotated POJOs to work with (using &lt;code&gt;xjc&lt;/code&gt; tool in the JDK):&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: plain"&gt;$ wget http://www.w3.org/Submission/wadl/wadl.xsd&lt;br /&gt;$ xjc wadl.xsd&lt;br /&gt;&lt;/pre&gt;And there it... hangs! The life of a software developer is full of challenges and non-trivial problems. And sometimes it is just an annoying network filter that makes suspicious packets (together with half hour of your life) disappear. It is not hard to spot the problem, once you recall that article written around 2008: &lt;a href="http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic/"&gt;W3C’s Excessive DTD Traffic&lt;/a&gt;:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;  &amp;lt;xs:import namespace="http://www.w3.org/XML/1998/namespace" &lt;br /&gt;    schemaLocation="http://www.w3.org/2001/xml.xsd"/&amp;gt; &lt;br /&gt;&lt;/pre&gt;Accessing &lt;a href="http://www.w3.org/2001/xml.xsd"&gt;&lt;code&gt;xml.xsd&lt;/code&gt;&lt;/a&gt; from the browser returns an HTML page instantly, but &lt;code&gt;xjc&lt;/code&gt; tool waits forever. Downloading this file locally and correcting the &lt;code&gt;schemaLocation&lt;/code&gt; attribute in &lt;code&gt;wadl.xsd&lt;/code&gt; helped. It's always the little things...&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: plain"&gt;$ xjc wadl.xsd &lt;br /&gt;parsing a schema... &lt;br /&gt;compiling a schema... &lt;br /&gt;net/java/dev/wadl/_2009/_02/Application.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Doc.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Grammars.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/HTTPMethods.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Include.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Link.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Method.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/ObjectFactory.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Option.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Param.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/ParamStyle.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Representation.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Request.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Resource.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/ResourceType.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Resources.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/Response.java &lt;br /&gt;net/java/dev/wadl/_2009/_02/package-info.java&lt;/pre&gt;Since we'll be using these classes in a maven based project (and I hate committing generated classes to source repository), let's move &lt;code&gt;xjc&lt;/code&gt; execution to maven lifecycle:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml; highlight: [27, 28]"&gt;&amp;lt;plugin&amp;gt;&lt;br /&gt;    &amp;lt;groupId&amp;gt;org.codehaus.mojo&amp;lt;/groupId&amp;gt;&lt;br /&gt;    &amp;lt;artifactId&amp;gt;jaxb2-maven-plugin&amp;lt;/artifactId&amp;gt;&lt;br /&gt;    &amp;lt;version&amp;gt;1.3&amp;lt;/version&amp;gt;&lt;br /&gt;    &amp;lt;dependencies&amp;gt;&lt;br /&gt;        &amp;lt;dependency&amp;gt;&lt;br /&gt;            &amp;lt;groupId&amp;gt;net.java.dev.jaxb2-commons&amp;lt;/groupId&amp;gt;&lt;br /&gt;            &amp;lt;artifactId&amp;gt;jaxb-fluent-api&amp;lt;/artifactId&amp;gt;&lt;br /&gt;            &amp;lt;version&amp;gt;2.0.1&amp;lt;/version&amp;gt;&lt;br /&gt;            &amp;lt;exclusions&amp;gt;&lt;br /&gt;                &amp;lt;exclusion&amp;gt;&lt;br /&gt;                    &amp;lt;groupId&amp;gt;com.sun.xml&amp;lt;/groupId&amp;gt;&lt;br /&gt;                    &amp;lt;artifactId&amp;gt;jaxb-xjc&amp;lt;/artifactId&amp;gt;&lt;br /&gt;                &amp;lt;/exclusion&amp;gt;&lt;br /&gt;            &amp;lt;/exclusions&amp;gt;&lt;br /&gt;        &amp;lt;/dependency&amp;gt;&lt;br /&gt;    &amp;lt;/dependencies&amp;gt;&lt;br /&gt;    &amp;lt;executions&amp;gt;&lt;br /&gt;        &amp;lt;execution&amp;gt;&lt;br /&gt;            &amp;lt;goals&amp;gt;&lt;br /&gt;                &amp;lt;goal&amp;gt;xjc&amp;lt;/goal&amp;gt;&lt;br /&gt;            &amp;lt;/goals&amp;gt;&lt;br /&gt;        &amp;lt;/execution&amp;gt;&lt;br /&gt;    &amp;lt;/executions&amp;gt;&lt;br /&gt;    &amp;lt;configuration&amp;gt;&lt;br /&gt;        &amp;lt;arguments&amp;gt;-Xfluent-api&amp;lt;/arguments&amp;gt;&lt;br /&gt;        &amp;lt;bindingFiles&amp;gt;bindings.xjb&amp;lt;/bindingFiles&amp;gt;&lt;br /&gt;        &amp;lt;packageName&amp;gt;net.java.dev.wadl&amp;lt;/packageName&amp;gt;&lt;br /&gt;    &amp;lt;/configuration&amp;gt;&lt;br /&gt;&amp;lt;/plugin&amp;gt;&lt;br /&gt;&lt;/pre&gt;Well, &lt;code&gt;pom.xml&lt;/code&gt; isn't the most concise format ever... Never mind, this will generate WADL XML classes during every build, before the source code is compiled. I also love the &lt;code&gt;fluent-api&lt;/code&gt; plugin that adds &lt;code&gt;with*()&lt;/code&gt; methods along with ordinary setters, returning &lt;code&gt;this&lt;/code&gt; to allow chaining. Pretty convenient. Finally we define more pleasant package name for generated artifacts (if you find &lt;code&gt;net.java.dev.wadl._2009._02&lt;/code&gt; package name pleasant enough, you can skip this step) and add &lt;code&gt;Wadl&lt;/code&gt; prefix to all generated classes &lt;code&gt;bindings.xjb&lt;/code&gt; file:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml; highlight: [10, 11, 12]"&gt;&amp;lt;jxb:bindings version="1.0"&lt;br /&gt;  xmlns:jxb="http://java.sun.com/xml/ns/jaxb"&lt;br /&gt;  xmlns:xs="http://www.w3.org/2001/XMLSchema"&lt;br /&gt;  xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"&lt;br /&gt;  jxb:extensionBindingPrefixes="xjc"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;jxb:bindings schemaLocation="../xsd/wadl.xsd" node="/xs:schema"&amp;gt;&lt;br /&gt;        &amp;lt;jxb:schemaBindings&amp;gt;&lt;br /&gt;            &amp;lt;jxb:nameXmlTransform&amp;gt;&lt;br /&gt;                &amp;lt;jxb:typeName prefix="Wadl"/&amp;gt;&lt;br /&gt;                &amp;lt;jxb:anonymousTypeName prefix="Wadl"/&amp;gt;&lt;br /&gt;                &amp;lt;jxb:elementName prefix="Wadl"/&amp;gt;&lt;br /&gt;            &amp;lt;/jxb:nameXmlTransform&amp;gt;&lt;br /&gt;        &amp;lt;/jxb:schemaBindings&amp;gt;&lt;br /&gt;    &amp;lt;/jxb:bindings&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/jxb:bindings&amp;gt;&lt;br /&gt;&lt;/pre&gt;We are now ready to produce and consume WADL in XML format using JAXB and POJO classes. Equipped with that knowledge and the foundation we are ready to develop some interesting library – which will be the subject of the next article.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-5305414479093175056?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/5305414479093175056/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2012/01/gentle-introduction-to-wadl-in-java.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/5305414479093175056'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/5305414479093175056'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2012/01/gentle-introduction-to-wadl-in-java.html' title='Gentle introduction to WADL (in Java)'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-2249268021103317775</id><published>2011-12-20T19:44:00.000+01:00</published><updated>2012-01-04T09:16:18.051+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='hibernate'/><category scheme='http://www.blogger.com/atom/ns#' term='jmx'/><category scheme='http://www.blogger.com/atom/ns#' term='quartz'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='ehcache'/><title type='text'>Enabling JMX in Hibernate, EhCache, Quartz, DBCP and Spring</title><content type='html'>Continuing our journey with JMX (see: &lt;a href="http://nurkiewicz.blogspot.com/2011/03/jolokia-highcharts-jmx-for-human-beings.html"&gt;...JMX for human beings&lt;/a&gt;) we will learn how to enable JMX support (typically statistics and monitoring capabilities) in some popular frameworks. Most of this information can be found on project's home pages, but I decided to collect it with few the addition of some useful tips.&lt;br /&gt;&lt;h4&gt;Hibernate (with Spring support)&lt;/h4&gt;Exposing &lt;a href="http://www.hibernate.org/"&gt;Hibernate&lt;/a&gt; statistics with JMX is pretty &lt;a href="http://community.jboss.org/wiki/PublishingStatisticsThroughJMX"&gt;simple&lt;/a&gt;, however some nasty workarounds are requires when JPA API is used to obtain underlying &lt;code&gt;SessionFactory&lt;/code&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;class JmxLocalContainerEntityManagerFactoryBean() extends LocalContainerEntityManagerFactoryBean {&lt;br /&gt; override def createNativeEntityManagerFactory() = {&lt;br /&gt;  val managerFactory = super.createNativeEntityManagerFactory()&lt;br /&gt;  registerStatisticsMBean(managerFactory)&lt;br /&gt;  managerFactory&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; def registerStatisticsMBean(managerFactory: EntityManagerFactory) {&lt;br /&gt;  managerFactory match {&lt;br /&gt;   case impl: EntityManagerFactoryImpl =&amp;gt;&lt;br /&gt;    val mBean = new StatisticsService();&lt;br /&gt;    mBean.setStatisticsEnabled(true)&lt;br /&gt;    mBean.setSessionFactory(impl.getSessionFactory);&lt;br /&gt;    val name = new ObjectName("org.hibernate:type=Statistics,application=spring-pitfalls")&lt;br /&gt;    ManagementFactory.getPlatformMBeanServer.registerMBean(mBean, name);&lt;br /&gt;   case _ =&amp;gt;&lt;br /&gt;  }&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Note that I have created a subclass of Springs built-in &lt;code&gt;LocalContainerEntityManagerFactoryBean&lt;/code&gt;. By overriding &lt;code&gt;createNativeEntityManagerFactory()&lt;/code&gt; method I can access &lt;code&gt;EntityManagerFactory&lt;/code&gt; and by trying to downcast it to &lt;code&gt;org.hibernate.ejb.EntityManagerFactoryImpl&lt;/code&gt; we were able to register Hibernate Mbean.&lt;br /&gt;One more thing has left. Obviously we have to use our custom subclass instead of &lt;code&gt;org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean&lt;/code&gt;. Also, in order to collect the actual statistics instead of just seeing zeroes all the way down we must set the &lt;code&gt;hibernate.generate_statistics&lt;/code&gt; flag.&lt;br /&gt;&lt;pre class="brush: scala; highlight: [3, 12]"&gt;@Bean&lt;br /&gt;def entityManagerFactoryBean() = {&lt;br /&gt; val entityManagerFactoryBean = new JmxLocalContainerEntityManagerFactoryBean()&lt;br /&gt; entityManagerFactoryBean.setDataSource(dataSource())&lt;br /&gt; entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter())&lt;br /&gt; entityManagerFactoryBean.setPackagesToScan("com.blogspot.nurkiewicz")&lt;br /&gt; entityManagerFactoryBean.setJpaPropertyMap(&lt;br /&gt;  Map(&lt;br /&gt;   "hibernate.hbm2ddl.auto" -&amp;gt; "create",&lt;br /&gt;   "hibernate.format_sql" -&amp;gt; "true",&lt;br /&gt;   "hibernate.ejb.naming_strategy" -&amp;gt; classOf[ImprovedNamingStrategy].getName,&lt;br /&gt;   "hibernate.generate_statistics" -&amp;gt; true.toString&lt;br /&gt;  ).asJava&lt;br /&gt; )&lt;br /&gt; entityManagerFactoryBean&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Here is a sample of what can we expect to see in JvisualVM (don't forget to install all plugins!):&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-5130t6qf51M/TvDWCiDfjXI/AAAAAAAAAgc/_p5Ta0fcSpc/s1600/Hibernate.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="377" src="http://2.bp.blogspot.com/-5130t6qf51M/TvDWCiDfjXI/AAAAAAAAAgc/_p5Ta0fcSpc/s640/Hibernate.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;In addition we get a nice Hibernate logging:&lt;br /&gt;&lt;pre class="brush: plain"&gt;HQL: select generatedAlias0 from Book as generatedAlias0, time: 10ms, rows: 20&lt;br /&gt;&lt;/pre&gt;&lt;h4&gt;EhCache&lt;/h4&gt;Monitoring caches is very important, especially in application where you expect values to generally be present there. I tend to query the database as often as needed to avoid unnecessary method arguments or local &lt;i&gt;caching&lt;/i&gt;. Everything to make code as simple as possible. However this approach only works when caching on the database layer works correctly. Similar to Hibernate, enabling JMX monitoring in &lt;a href="http://ehcache.org/"&gt;EhCache&lt;/a&gt; is a two-step process. First you need to expose provided &lt;code&gt;MBean&lt;/code&gt; in &lt;code&gt;MBeanServer&lt;/code&gt;:&lt;br /&gt;&lt;pre class="brush: scala; highlight: 11"&gt;@Bean(initMethod = "init", destroyMethod = "dispose")&lt;br /&gt;def managementService = new ManagementService(ehCacheManager(), platformMBeanServer(), true, true, true, true, true)&lt;br /&gt;&lt;br /&gt;@Bean def platformMBeanServer() = ManagementFactory.getPlatformMBeanServer&lt;br /&gt;&lt;br /&gt;def ehCacheManager() = ehCacheManagerFactoryBean.getObject&lt;br /&gt;&lt;br /&gt;@Bean def ehCacheManagerFactoryBean = {&lt;br /&gt; val ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean&lt;br /&gt; ehCacheManagerFactoryBean.setShared(true)&lt;br /&gt; ehCacheManagerFactoryBean.setCacheManagerName("spring-pitfalls")&lt;br /&gt; ehCacheManagerFactoryBean&lt;br /&gt;}&lt;/pre&gt;Note that I explicitly set &lt;code&gt;CacheManager&lt;/code&gt; name. This is not required but this name is used as part of the Mbean name and a default one contains &lt;code&gt;hashCode&lt;/code&gt; value, which is not very pleasant. The final touch is to enable statistics on a cache basis:&lt;br /&gt;&lt;pre class="brush: xml; highlight: 8"&gt;&amp;lt;cache name="org.hibernate.cache.StandardQueryCache"&lt;br /&gt;    maxElementsInMemory="10000"&lt;br /&gt;    eternal="false"&lt;br /&gt;    timeToIdleSeconds="3600"&lt;br /&gt;    timeToLiveSeconds="600"&lt;br /&gt;    overflowToDisk="false"&lt;br /&gt;    memoryStoreEvictionPolicy="LRU"&lt;br /&gt;    statistics="true"&lt;br /&gt;/&amp;gt;&lt;br /&gt;&lt;/pre&gt;Now we can happily monitor various caching characteristics of every cache separately:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://3.bp.blogspot.com/-rCKlm6Se-ck/TvDWFyeODYI/AAAAAAAAAgs/75jOfXf7EyQ/s1600/ehcache.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="378" src="http://3.bp.blogspot.com/-rCKlm6Se-ck/TvDWFyeODYI/AAAAAAAAAgs/75jOfXf7EyQ/s640/ehcache.png" width="640" /&gt;&lt;/a&gt; &lt;br /&gt;&lt;br /&gt;As we can see the percentage of cache misses increases. Never a good thing. If we don't enable cache statistics, enabling JMX is still a good idea since we get a lot of management operations for free, including flushing and clearing caches (useful during debugging and testing).&lt;br /&gt;&lt;h4&gt;Quartz scheduler&lt;/h4&gt;In my humble opinion &lt;a href="http://quartz-scheduler.org/"&gt;Quartz scheduler&lt;/a&gt; is very underestimated library, but I will write an article about it on its own. This time we will only learn how to monitor it via JMX. Fortunately it's as simple as adding:&lt;br /&gt;&lt;pre class="brush: plain"&gt;org.quartz.scheduler.jmx.export=true&lt;br /&gt;&lt;/pre&gt;To &lt;code&gt;quartz.properties&lt;/code&gt; file. The JMX support in Quartz could have been slightly broader, but still one can query e.g. which jobs are currently running. By the way the new major version of Quartz (2.x) brings very nice DSL-like support for scheduling:&lt;br /&gt;&lt;pre class="brush: scala"&gt;val job = newJob(classOf[MyJob])&lt;br /&gt;val trigger = newTrigger().&lt;br /&gt;  withSchedule(&lt;br /&gt;   repeatSecondlyForever()&lt;br /&gt;  ).&lt;br /&gt;  startAt(&lt;br /&gt;   futureDate(30, SECOND)&lt;br /&gt;  )&lt;br /&gt;scheduler.scheduleJob(job.build(), trigger.build())&lt;br /&gt;&lt;/pre&gt;&lt;h4&gt;Apache Commons DBCP&lt;/h4&gt;Apache Commons &lt;a href="http://commons.apache.org/dbcp/"&gt;DBCP&lt;/a&gt; is the most reasonable JDBC pooling library I came across. There is also &lt;a href="http://sourceforge.net/projects/c3p0/"&gt;c3p0&lt;/a&gt;, but it doesn't seem like it's actively developed any more. &lt;a href="http://people.apache.org/%7Efhanik/jdbc-pool/jdbc-pool.html"&gt;Tomcat JDBC Connection Pool&lt;/a&gt; looked promising, but since it's bundled in Tomcat, your JDBC drivers can no longer be packaged in WAR.&lt;br /&gt;The only problem with DBCP is that it does not support JMX. At all (see this &lt;a href="https://issues.apache.org/jira/browse/DBCP-292"&gt;two and a half year old&lt;/a&gt; issue). Fortunately this can be easily worked around. Besides we will learn how to use Spring built-in JMX support.&lt;br /&gt;Looks like the standard &lt;a href="http://commons.apache.org/dbcp/apidocs/org/apache/commons/dbcp/BasicDataSource.html"&gt;&lt;code&gt;BasicDataSource&lt;/code&gt;&lt;/a&gt; has all what we need, all we have to do is to expose existing metrics via JMX. With Spring it is dead-simple – just subclass BasicDataSource and add &lt;code&gt;@ManagedAttribute&lt;/code&gt; annotation over desired attributes:&lt;br /&gt;&lt;pre class="brush: scala"&gt;@ManagedResource&lt;br /&gt;class ManagedBasicDataSource extends BasicDataSource {&lt;br /&gt;&lt;br /&gt;    @ManagedAttribute override def getNumActive = super.getNumActive&lt;br /&gt;    @ManagedAttribute override def getNumIdle = super.getNumIdle&lt;br /&gt;    @ManagedAttribute def getNumOpen = getNumActive + getNumIdle&lt;br /&gt;    @ManagedAttribute override def getMaxActive: Int= super.getMaxActive&lt;br /&gt;    @ManagedAttribute override def setMaxActive(maxActive: Int) {&lt;br /&gt;        super.setMaxActive(maxActive)&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @ManagedAttribute override def getMaxIdle = super.getMaxIdle&lt;br /&gt;    @ManagedAttribute override def setMaxIdle(maxIdle: Int) {&lt;br /&gt;        super.setMaxIdle(maxIdle)&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @ManagedAttribute override def getMinIdle = super.getMinIdle&lt;br /&gt;    @ManagedAttribute override def setMinIdle(minIdle: Int) {&lt;br /&gt;        super.setMinIdle(minIdle)&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @ManagedAttribute override def getMaxWait = super.getMaxWait&lt;br /&gt;    @ManagedAttribute override def setMaxWait(maxWait: Long) {&lt;br /&gt;        super.setMaxWait(maxWait)&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @ManagedAttribute override def getUrl = super.getUrl&lt;br /&gt;    @ManagedAttribute override def getUsername = super.getUsername&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Here are few data source metrics going crazy during load-test:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://4.bp.blogspot.com/-JIYH78v8Szw/TvDWFBssJHI/AAAAAAAAAgk/pGTrLYdWtFE/s1600/dbcp.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="588" src="http://4.bp.blogspot.com/-JIYH78v8Szw/TvDWFBssJHI/AAAAAAAAAgk/pGTrLYdWtFE/s640/dbcp.png" width="640" /&gt;&lt;/a&gt; &lt;br /&gt;&lt;br /&gt;JMX support in the Spring framework itself is pretty simple. As you have seen above exposing arbitrary attribute or operation is just a matter of adding an annotation. You only have to remember about enabling JMX support using either XML or Java (also see: &lt;a href="https://jira.springsource.org/browse/SPR-8943"&gt;SPR-8943 : Annotation equivalent to &amp;lt;context:mbean-export/&amp;gt; with @Configuration&lt;/a&gt;):&lt;br /&gt;&lt;pre class="brush: xml"&gt;&amp;lt;context:mbean-export/&amp;gt;&lt;br /&gt;&lt;/pre&gt;or:&lt;br /&gt;&lt;pre class="brush: scala"&gt;@Bean def annotationMBeanExporter() = new AnnotationMBeanExporter()&lt;br /&gt;&lt;/pre&gt;This article wasn't particularly exciting. However, the knowledge of JMX metrics will enable us to write simple yet fancy dashboards in no time. Stay tuned!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-2249268021103317775?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/2249268021103317775/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/12/enabling-jmx-in-hibernate-ehcache-qurtz.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2249268021103317775'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2249268021103317775'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/12/enabling-jmx-in-hibernate-ehcache-qurtz.html' title='Enabling JMX in Hibernate, EhCache, Quartz, DBCP and Spring'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-5130t6qf51M/TvDWCiDfjXI/AAAAAAAAAgc/_p5Ta0fcSpc/s72-c/Hibernate.png' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-4456248775897338627</id><published>2011-11-15T22:27:00.001+01:00</published><updated>2011-11-17T19:31:29.910+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='hibernate'/><category scheme='http://www.blogger.com/atom/ns#' term='h2'/><category scheme='http://www.blogger.com/atom/ns#' term='transactions'/><category scheme='http://www.blogger.com/atom/ns#' term='jpa'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='testing'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Spring pitfalls: transactional tests considered harmful</title><content type='html'>&lt;div&gt;One of the Spring killer-features is anin-container &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html"&gt;integrationtesting&lt;/a&gt;. While EJB lacked this functionality for many years (JavaEE 6 finally &lt;a href="http://www.adam-bien.com/roller/abien/entry/embedding_ejb_3_1_container"&gt;addresses&lt;/a&gt;this, however I haven't, &lt;i&gt;ekhem&lt;/i&gt;, tested it), Spring from the verybeginning allowed you to test the full stack, starting from web tier,through services all the way down to the database.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Database is the problematic part. Firstyou need to use in-memory self-contained database like &lt;a href="http://www.h2database.com/"&gt;H2&lt;/a&gt;to decouple your tests from an external database. Spring helps withthis to a great degree, especially now with profiles and &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/jdbc.html#jdbc-embedded-database-support"&gt;embeddeddatabase support&lt;/a&gt;. The second problem is more subtle. Whiletypical Spring application is almost completely stateless (for betteror worse), database is inherently stateful. This complicatesintegration testing since the very first principle of writing testsis that they should be independent on each other and repeatable. Ifone test writes something to the database, another test may fail;also the same test may fail on subsequent call due to databasechanges.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Obviously Spring &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html#testcontext-tx"&gt;handlesthis problem&lt;/a&gt; as well with a very neat trick: prior to runningevery test Spring starts a new transaction. The whole test (includingits setup and tear down) runs within the same transaction which is...rolled back at the end. This means all the changes made during thetest are visible in the database just like if they were persisted.However rollback after every test wipes out all the changes and thenext test works on a clean and freshdatabase. Brilliant!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Unfortunatelythis is not yet another article about Spring integration testingadvantages. I think I have written hundreds if not thousands of suchtests and I truly appreciate the transparent support Spring frameworkgives. But I also came across numerous quirks and inconsistenciesintroduces by this comfortable feature. To make matters worse, veryoften so-called transactional tests are actually &lt;b&gt;hidingerrors&lt;/b&gt;convincing the developer that the software works, while it failsafter deployment! Here is a non-exhaustive but eye-opening collectionof issues:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Test&lt;br /&gt;public void shouldThrowLazyInitializationExceptionWhenFetchingLazyOneToManyRelationship() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  final Book someBook = findAnyExistingBook();&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  try {&lt;br /&gt;    someBook.reviews().size();&lt;br /&gt;    fail();&lt;br /&gt;  } catch(LazyInitializationException e) {&lt;br /&gt;    //then&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Thisis a known issue with Hibernate and spring integration testing. &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;Book&lt;/span&gt;is a database entity with one-to-many, lazy by default, relationshipto &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;Reviews&lt;/span&gt;. &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;findAnyExistingBook()&lt;/span&gt; simply reads a test book from atransactional service. Now a bit of theory: as long as an entity isbound to a &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;session&lt;/span&gt; (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;EntityManager&lt;/span&gt; if using JPA), it can lazily andtransparently load relationships. In our case it means: as long as itis within a scope of a transaction. The moment an entity leaves atransaction, it becomes detached. At this lifecycle stage an entityis no longer attached to a &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;session&lt;/span&gt;/&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;EntityManager&lt;/span&gt; (which has beencommitted and closed already) and any approach to fetch lazyproperties throws the dreadful &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;LazyInitializationException&lt;/span&gt;. Thisbehaviour is actually standardized in JPA (except the exception classitself, which is vendor specific).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Inour case we are callling &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;.reviews()&lt;/span&gt; (Scala-style “getter”, wewill translate our test case to ScalaTest soon as well) and expectingto see the Hibernate exception. However the exception is not thrownand the application keeps going. That's because the whole test isrunning within a transaction and the Book entity never gets out oftransactional scope. Lazy loading &lt;i&gt;always&lt;/i&gt;works in Spring integration tests.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://draft.blogger.com/blogger.g?blogID=6753769565491687768" name="__DdeLink__5_174853039"&gt;&lt;/a&gt;Tobe fair, we will never see tests like this in real life (unless youare testing to make sure that a given collection is lazy –unlikely). In real life we are testing business logic which justworks in tests. However after deploying we start experiencing&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;LazyInitializationException&lt;/span&gt;. But we tested it! Not only Springintegration testing support &lt;b&gt;hidthe problem&lt;/b&gt;,but it also encourages the developer to throw in &lt;a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.html" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;OpenSessionInViewFilter&lt;/a&gt;or &lt;a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.html" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;OpenEntityManagerInViewFilter&lt;/a&gt;.In other words: our test not only didn't discover a bug in our code,but it also significantly worsen our overall architecture andperformance. Not what I would expect.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Mytypical workflow these days while implementing some end-to-endfeature is to write back-end tests, implement the back-end includingREST API and when everything runs smoothly deploy it and proceed withthe GUI. The latter is written using AJAX/JavaScript completely so Ionly need to deploy once and replace cheap client-side files often.At this stage I don't want to go back to the server to fixundiscovered bugs.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Suppressing &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt; LazyInitializationException&lt;/span&gt; is among the most knownproblems with Spring integration testing. But this is just a tip ofan iceberg. Here is a bit more complex example (it uses JPA again,but this problems manifests itself with plain JDBC and any otherpersistence technology as well):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Test&lt;br /&gt;public void externalThreadShouldSeeChangesMadeInMainThread() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  final Book someBook = findAnyExistingBook();&lt;br /&gt;  someBook.setAuthor("Bruce Wayne");&lt;br /&gt;  bookService.save(someBook);&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  final Future&amp;lt;Book&amp;gt; future = executorService.submit(new Callable&amp;lt;Book&amp;gt;() {&lt;br /&gt;    @Override&lt;br /&gt;    public Book call() throws Exception {&lt;br /&gt;      return bookService.findBy(someBook.id()).get();&lt;br /&gt;    }&lt;br /&gt;  });&lt;br /&gt;&lt;br /&gt;  //then&lt;br /&gt;  assertThat(future.get().getAuthor()).isEqualTo("Bruce Wayne");&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In the first step we are loading some book from the database andmodifying the author, saving an entity afterwards. Then we load thesame entity by id in another thread. The entity is already saved soit is guaranteed that the thread should see the changes. This is notthe case however, which is proved by the failing assertion in thelast step. What happened?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Wehave just observed “&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;I&lt;/span&gt;” in &lt;a href="http://en.wikipedia.org/wiki/ACID"&gt;ACID&lt;/a&gt;transaction properties. Changes made by the test thread are notvisible to other threads/connections until the transaction iscommitted. But we know the test transaction commits! This smallshowcase demonstrates how hard it is to write multi-threadedintegration tests with transactional support. I learnt the hard wayfew weeks ago when I wanted to integration-test &lt;a href="http://www.quartz-scheduler.org/"&gt;Quartz&lt;/a&gt;scheduler with &lt;a href="http://www.quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/tutorial-lesson-09" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;JDBCJobStore&lt;/a&gt;enabled. No matter how hard I tried the jobs were never fired. Itturned out that I was scheduling a job in Spring-managed test withinthe scope of a Spring transaction. Because the transaction was nevercommitted, the external scheduler and worker threads couldn't see thenew job record in the database. And how many hours have you spentdebugging such issues?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Talking about debugging, the same problem pop up whentrouble-shooting database-related test failures. I can add thissimple H2 web console (browse to &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;localhost:8082&lt;/span&gt;) bean to my testconfiguration:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;@Bean(initMethod = "start", destroyMethod = "stop")&lt;br /&gt;def h2WebServer() = Server.createWebServer("-webDaemon", "-webAllowOthers")&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But I will never see changes made by my test while stepping throughit. I cannot run the query manually to find out why it returns wrongresults. Also I cannot modify the data on-the-fly to have a fasterturn-around while trouble-shooting. My database lives in a differentdimension.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Please read the next test carefully, it's not long:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Test&lt;br /&gt;public void shouldNotSaveAndLoadChangesMadeToNotManagedEntity() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  final Book unManagedBook = findAnyExistingBook();&lt;br /&gt;  unManagedBook.setAuthor("Clark Kent");&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  final Book loadedBook = bookService.findBy(unManagedBook.id()).get();&lt;br /&gt;&lt;br /&gt;  //then&lt;br /&gt;  assertThat(loadedBook.getAuthor()).isNotEqualTo("Clark Kent");&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Weare loading a book and modifying an author &lt;b&gt;without&lt;/b&gt;explicitly persisting it. Then we are loading it again from thedatabase and making sure that the change was &lt;b&gt;not&lt;/b&gt;persisted. Guess what, somehow we have updated the object!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Ifyou are experienced JPA/Hibernate user you know exactly how couldthat happen. Remember when I was describing attached/detachedentities above? When an entity is still attached to the underlying&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;EntityManager&lt;/span&gt;/&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;session&lt;/span&gt; it has other powers as well. JPA provider isobligated to track the changes made to such entities andautomatically propagate them to the database when entity becomesdetached (so-called &lt;i&gt;dirtychecking&lt;/i&gt;).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This means that an idiomatic way to work with JPA entitiesmodifications is to load an object from a database, perform necessarychanges using setters and... that's it. When the entity becomesdetached, JPA will discover it was modified and issue an UPDATE foryou. No &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;merge()&lt;/span&gt;/&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;update()&lt;/span&gt; needed, cute object abstraction. This worksas long as an entity is managed. Changes made to detached entity aresilently ignored because JPA provider knows nothing about suchentities. Now the best part – you almost never know if your entityis attached or not because transaction management is transparent andalmost invisible. This means that it is way too easy to only modifyPOJO instance in-memory while still believing that changes arepersistent and vice-versa!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Can we test it? Of course, we just did – and failed. In our testabove transaction spans across the whole test method, so every entityis managed. Also due to Hibernate L1 cache we get the exact same bookinstance back, even though no database update has been yet issued.This is another case where transactional tests are hiding problemsrather than revealing them (see &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt; LazyInitializationException&lt;/span&gt;example). Changes are propagated to the database as expected in thetest, but silently ignored after deployment...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;BTWdid I mention that all tests so far are passing once you get rid of&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;@Transactional &lt;/span&gt;annotation over test case class? Have a look, sourcesas always are &lt;a href="https://github.com/nurkiewicz/spring-pitfalls/tree/transactional-tests"&gt;available&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://draft.blogger.com/blogger.g?blogID=6753769565491687768" name="__DdeLink__27_174853039"&gt;&lt;/a&gt;Thisone is exciting. I have a transactional &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;deleteAndThrow(book)&lt;/span&gt; businessmethod that deletes given book and throws &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;OppsException&lt;/span&gt;. Here is mytest that passes, proving the code is correct:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Test&lt;br /&gt;public void shouldDeleteEntityAndThrowAnException() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  final Book someBook = findAnyExistingBook();&lt;br /&gt;&lt;br /&gt;  try {&lt;br /&gt;    //when&lt;br /&gt;    bookService.deleteAndThrow(someBook);&lt;br /&gt;    fail();&lt;br /&gt;  } catch (OppsException e) {&lt;br /&gt;    //then&lt;br /&gt;    final Option&amp;lt;Book&amp;gt; deletedBook = bookService.findBy(someBook.id());&lt;br /&gt;    assertThat(deletedBook.isEmpty()).isTrue();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://draft.blogger.com/blogger.g?blogID=6753769565491687768" name="__DdeLink__29_174853039"&gt;&lt;/a&gt;TheScala's &lt;a href="http://www.scala-lang.org/api/current/scala/Option.html" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;Option&amp;lt;Book&amp;gt;&lt;/a&gt;is returned (have you noticed how nicely Java code interacts withservices and and entities written in Scala?) instead of &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;null&lt;/span&gt;.&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;deletedBook.isEmpty()&lt;/span&gt; yielding &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;true&lt;/span&gt; means that no result was found.So it seems like our code is correct: the entity was deleted and theexception thrown. Yes, you are correct, it fails silently afterdeployment again! This time Hibernate L1 cache knows that thisparticular instance of book was deleted so it returns null evenbefore flushing changes to the database. However &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;OppsException&lt;/span&gt; thrownfrom the services rolls back the transaction, discarding DELETE! Butthe test passes, only because Spring manages this tiny extratransaction and the assertion happens within that transaction.Milliseconds later transaction rolls back, resurrecting deletedentity.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Obviouslythe solution was to add &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;noRollbackFor&lt;/span&gt; attribute for &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;OppsException&lt;/span&gt;(this is an actual bug I found in my code after droppingtransactional tests in favour to other solution which is yet to beexplained). But this is not the point. The point is – &lt;b&gt;canyou really afford to write and maintain tests that are generatingfalse-positives, convincing you that your application is workingwhereas it's not?&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Oh, and did I mention that transacational tests are actually leakinghere and there and won't prevent you from modifying the testdatabase? The second test fails, can you see why?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Test&lt;br /&gt;public void shouldStoreReviewInSecondThread() throws Exception {&lt;br /&gt;  final Book someBook = findAnyExistingBook();&lt;br /&gt;&lt;br /&gt;  executorService.submit(new Callable&amp;lt;Review&amp;gt;() {&lt;br /&gt;    @Override&lt;br /&gt;    public Review call() throws Exception {&lt;br /&gt;      return reviewDao.save(new Review("Unicorn", "Excellent!!!1!", someBook));&lt;br /&gt;    }&lt;br /&gt;  }).get();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;@Test&lt;br /&gt;public void shouldNotSeeReviewStoredInPreviousTest() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  final Iterable&amp;lt;Review&amp;gt; reviews = reviewDao.findAll();&lt;br /&gt;&lt;br /&gt;  //then&lt;br /&gt;  assertThat(reviews).isEmpty();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Once again threading gets into the way. It gets even more interestingwhen you try to clean up after external transaction in backgroundthread that obviously was committed. The natural place would be todelete created Review in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;@After&lt;/span&gt; method. But &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;@After&lt;/span&gt; is executed withinthe same test transaction, so the clean up will be... rolled back.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Of course I am not here to complain and grumble about my favouriteapplication stack weaknesses. I am here to give solutions and hints.Our goal is to get rid of transactional tests altogether and onlydepend on application transactions. This will help us to avoid allthe aforementioned problems. Obviously we cannot drop testindependence and repeatability features. Each test has to work on thesame database to be reliable. First, we will translate JUnit test toScalaTest. In order to have Spring dependency-injection support weneed this tiny trait:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;trait SpringRule extends Suite with BeforeAndAfterAll { this: AbstractSuite =&amp;gt;&lt;br /&gt;&lt;br /&gt;  override protected def beforeAll() {&lt;br /&gt;    new TestContextManager(this.getClass).prepareTestInstance(this)&lt;br /&gt;    super.beforeAll();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now it's about time to reveal my idea(if you are impatient, full &lt;a href="https://github.com/nurkiewicz/spring-pitfalls/tree/non-transactional-tests"&gt;sourcecode is here&lt;/a&gt;). It's far from being ingenious or unique, but Ithink it deserves some attention. Instead of running everything inone huge transaction and rolling it back, just let the tested code tostart and commit transactions wherever and whenever it needs and hasconfigured. This means that the data &lt;b&gt;is&lt;/b&gt;actually written to the database and persistence works exactly thesame as it would after the deployment. Where's the catch? We mustsomehow clean up the mess after each test...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Turns out it's not that complicated. Just take a dump of a cleandatabase and import it after each test! The dump contains all thetables, constraints and records present right after the deploymentand application start-up but before the first test run. It's liketaking a backup and restoring from it! Look how simple it is with H2:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;trait DbResetRule extends Suite with BeforeAndAfterEach with BeforeAndAfterAll { this: SpringRule =&amp;gt;&lt;br /&gt;&lt;br /&gt;  @Resource val dataSource: DataSource = null&lt;br /&gt;&lt;br /&gt;  val dbScriptFile = File.createTempFile(classOf[DbResetRule].getSimpleName + "-", ".sql")&lt;br /&gt;&lt;br /&gt;  override protected def beforeAll() {&lt;br /&gt;    new JdbcTemplate(dataSource).execute("SCRIPT NOPASSWORDS DROP TO '" + dbScriptFile.getPath + "'")&lt;br /&gt;    dbScriptFile.deleteOnExit()&lt;br /&gt;    super.beforeAll()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  override protected def afterEach() {&lt;br /&gt;    super.afterEach()&lt;br /&gt;    new JdbcTemplate(dataSource).execute("RUNSCRIPT FROM '" + dbScriptFile.getPath + "'")&lt;br /&gt;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;trait DbResetSpringRule extends DbResetRule with SpringRule&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;TheSQL dump (see H2 &lt;a href="http://www.h2database.com/html/grammar.html#script" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;SCRIPT&lt;/a&gt;command) is taken once and exported to temporary file. Then the SQLscript file is executed after each test. Believe it or not, that'sit! Our test is no longer transactional (so all Hibernate andmulti-threading corner-cases are discovered and tested) while wedidn't sacrifice the ease of transactional-tests setup (no extraclean up needed). Also I can finally look at the database contentswhile debugging! Here is one of the previous tests in action:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;@RunWith(classOf[JUnitRunner])&lt;br /&gt;@ContextConfiguration(classes = Array[Class[_]](classOf[SpringConfiguration]))&lt;br /&gt;class BookServiceTest extends FunSuite with ShouldMatchers with BeforeAndAfterAll with DbResetSpringRule {&lt;br /&gt;&lt;br /&gt;  @Resource&lt;br /&gt;  val bookService: BookService = null&lt;br /&gt;&lt;br /&gt;  private def findAnyExistingBook() = bookService.listBooks(new PageRequest(0, 1)).getContent.head&lt;br /&gt;&lt;br /&gt;  test("should delete entity and throw an exception") {&lt;br /&gt;    val someBook = findAnyExistingBook()&lt;br /&gt;&lt;br /&gt;    intercept[OppsException] {&lt;br /&gt;      bookService.deleteAndThrow(someBook)&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    bookService findBy someBook.id should be (None)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Keep in mind that this is not a library/utility, but an idea. Foryour project you might choose slightly different approach and tools,but the general idea still applies: let your code run in the exactsame environment as after deployment and clean up the mess frombackup afterwards. You can achieve the exact same results with JUnit,&lt;a href="http://hsqldb.org/"&gt;HSQLDB&lt;/a&gt; or whatever you prefer. Of course you can add some cleveroptimizations as well – mark or discover tests that are notmodifying the database, choose faster dump, import approaches, etc.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To be honest, there are some downsides as well, here are a few fromtop of my head:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;ul&gt;&lt;li&gt;&lt;div&gt;&lt;i&gt;Performance&lt;/i&gt;. While it is not obvious that this approach is significantly slower than rolling back transactions all the time (some databases are particularly slow at rollbacks), it is safe to assume so. Of course in-memory databases might have some unexpected performance characteristics, but be prepared for a slowdown. However I haven't observed huge difference (maybe around 10%) per 100 tests in a small project.&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div&gt;&lt;i&gt;Concurrency&lt;/i&gt;. You can no longer run tests concurrently. Changes made by one thread (test) are visible by others, making test execution unpredictable. This becomes even more painful with regards to aforementioned performance problems.&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That would be it. If you are interested give this approach a chance.It may take some time to adopt your existing test base, butdiscovering even one hidden bug is worth it, don't you think? Andalso be aware of other &lt;a href="http://nurkiewicz.blogspot.com/2011/10/spring-pitfalls-proxying.html"&gt;springpitfalls&lt;/a&gt;.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-4456248775897338627?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/4456248775897338627/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/11/spring-pitfalls-transactional-tests.html#comment-form' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/4456248775897338627'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/4456248775897338627'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/11/spring-pitfalls-transactional-tests.html' title='Spring pitfalls: transactional tests considered harmful'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-624144439922682448</id><published>2011-10-29T11:10:00.000+02:00</published><updated>2011-11-17T19:29:51.245+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='transactions'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='aop'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Spring pitfalls: proxying</title><content type='html'>&lt;br /&gt;&lt;div&gt;Being a Spring framework user andenthusiast for many years I came across several misunderstandings andproblems with this stack. Also there are places where abstractionsleak terribly and to effectively and safely take advantage of all thefeatures developers need to be aware of them. That is why I amstarting a &lt;i&gt;Spring pitfalls series&lt;/i&gt;. In the first part we willtake a closer look at how proxying works.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Bean proxying is an essential and oneof the most important infrastructure features provided by Spring. Itis so important and low-level that for most of the time we don't evenrealize that it exists. However transactions, aspect-orientedprogramming, advanced scoping, &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async"&gt;@Async&lt;/a&gt;support and various other domestic use-cases wouldn't be possiblewithout it. So what is &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-proxying"&gt;proxying&lt;/a&gt;?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here is an example: when you inject DAOinto service, Spring takes DAO instances and injects it directly.That's it. However sometimes Spring needs to be aware of each andevery call made by service (and any other bean) to DAO. For instanceif DAO is marked transactional it needs to start a transaction beforecall and commit or rolls back afterwards. Of course you can do thismanually, but this is tedious, error-prone and mixes concerns. That'swhy we use declarative transactions on the first place.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So how does Spring implement thisinterception mechanism? There are three methods from simplest to mostadvanced ones. I won't discuss their advantages and disadvantagesyet, we will see them soon on a concrete examples.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4&gt;Java dynamic proxies&lt;/h4&gt;&lt;div&gt;Simplest solution. If DAO implementsany interface, Spring will create a Java &lt;a href="http://www.ibm.com/developerworks/java/library/j-jtp08305/index.html"&gt;dynamicproxy&lt;/a&gt; implementing that interface(s) and inject it instead of thereal class. The &lt;i&gt;real&lt;/i&gt; onestill exists and the proxy has reference to it, but to the outsideworld – the proxy is the bean. Now every time you call methods onyour DAO, Spring can intercept them, add some AOP magic and call theoriginal method.&lt;/div&gt;&lt;div style="font-style: normal; margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4&gt;CGLIB generatedclasses&lt;/h4&gt;&lt;div&gt;The downside of Java dynamic proxies isa requirement on the bean to implement at least one interface. CGLIBworks around this limitation by dynamically subclassing the originalbean and adding interception logic directly by overriding everypossible method. Think of it as subclassing the original class andcalling super version amongst other things:&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;class DAO {&lt;br /&gt;  def findBy(id: Int) = //...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class DAO$EnhancerByCGLIB extends DAO {&lt;br /&gt;  override def findBy(id: Int) = {&lt;br /&gt;    startTransaction&lt;br /&gt;    try {&lt;br /&gt;      val result = super.findBy(id)&lt;br /&gt;      commitTransaction()&lt;br /&gt;      result&lt;br /&gt;    } catch {&lt;br /&gt;      case e =&amp;gt;&lt;br /&gt;        rollbackTransaction()&lt;br /&gt;        throw e&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;However, this pseudocode does &lt;b&gt;not&lt;/b&gt;illustrate howit works in reality – which introduces yet another problem, staytuned. BTW all examples will be in Scala, live with that and get usedto it.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;AspectJ weaving&lt;/h4&gt;Thisis the most invasive but also the most reliable and intuitivesolution from the developer perspective. In this mode interception isapplied directly to your class bytecode which means the class yourJVM runs is not the same as the one you wrote. AspectJ weaver addsinterception logic by directly modifying your bytecode of your class,either during build – &lt;i&gt;compiletime weaving&lt;/i&gt;(&lt;i&gt;CTW&lt;/i&gt;)or when loading a class – &lt;i&gt;loadtime weaving&lt;/i&gt;(&lt;i&gt;LTW&lt;/i&gt;).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Ifyou are curious how AspectJ magic is implemented under the hood, hereis a decompiled and simplified .class file compiled with AspectJweaving beforehand:&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public void inInterfaceTransactional()&lt;br /&gt;{&lt;br /&gt;  try&lt;br /&gt;  {&lt;br /&gt;    AnnotationTransactionAspect.aspectOf().ajc$before$1$2a73e96c(this, ajc$tjp_2);&lt;br /&gt;    throwIfNotInTransaction();&lt;br /&gt;  }&lt;br /&gt;  catch(Throwable throwable)&lt;br /&gt;  {&lt;br /&gt;    AnnotationTransactionAspect.aspectOf().ajc$afterThrowing$2$2a73e96c(this, throwable);&lt;br /&gt;    throw throwable;&lt;br /&gt;  }&lt;br /&gt;  AnnotationTransactionAspect.aspectOf().ajc$afterReturning$3$2a73e96c(this);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;With load timeweaving the same transformation occurs at runtime, when the class isloaded. As you can see there is nothing disturbing here, in fact thisis exactly how you would program the transactions manually. Sidenote: do you remember the times when viruses were appending theircode into executable files or dynamically injecting themselves whenexecutable was loaded by the operating system?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Knowing proxytechniques is important to understand how proxying works and how itaffects your code. Let us stick with declarative transactiondemarcation example, here is our battlefield:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;trait FooService {&lt;br /&gt;  def inInterfaceTransactional()&lt;br /&gt;  def inInterfaceNotTransactional();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;@Service&lt;br /&gt;class DefaultFooService extends FooService {&lt;br /&gt;&lt;br /&gt;  private def throwIfNotInTransaction() {&lt;br /&gt;    assume(TransactionSynchronizationManager.isActualTransactionActive)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def publicNotInInterfaceAndNotTransactional() {&lt;br /&gt;    inInterfaceTransactional()&lt;br /&gt;    publicNotInInterfaceButTransactional()&lt;br /&gt;    privateMethod();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Transactional&lt;br /&gt;  def publicNotInInterfaceButTransactional() {&lt;br /&gt;    throwIfNotInTransaction()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Transactional&lt;br /&gt;  private def privateMethod() {&lt;br /&gt;    throwIfNotInTransaction()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Transactional&lt;br /&gt;  override def inInterfaceTransactional() {&lt;br /&gt;    throwIfNotInTransaction()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  override def inInterfaceNotTransactional() {&lt;br /&gt;    inInterfaceTransactional()&lt;br /&gt;    publicNotInInterfaceButTransactional()&lt;br /&gt;    privateMethod();&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Handy&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;throwIfNotInTransaction()&lt;/span&gt; method... throws exception when not invokedwithin a transaction. Who would have thought? This method is calledfrom various places and different configurations. If you examinecarefully how methods are invoked – this should all work. Howeverour developers' life tend to be brutal. First obstacle wasunexpected: &lt;a href="http://scalatest.org/"&gt;ScalaTest&lt;/a&gt; does notsupport Spring integration &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html"&gt;testing&lt;/a&gt;via dedicated runner. Luckily this can be easily ported with a simpletrait (handles dependency injection to test cases and applicationcontext caching):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;trait SpringRule extends AbstractSuite { this: Suite =&amp;gt;&lt;br /&gt;&lt;br /&gt;  abstract override def run(testName: Option[String], reporter: Reporter, stopper: Stopper, filter: Filter, configMap: Map[String, Any], distributor: Option[Distributor], tracker: Tracker) {&lt;br /&gt;    new TestContextManager(this.getClass).prepareTestInstance(this)&lt;br /&gt;    super.run(testName, reporter, stopper, filter, configMap, distributor, tracker)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Note that we arenot starting and rolling back transactions like the &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html#testing-tx"&gt;original&lt;/a&gt;testing framework. Not only because it would interfere with our demobut also because I find transactional tests harmful – but more onthat in the future. Back to our example, here is a smoke test. Thecomplete source code can be downloaded &lt;a href="https://github.com/nurkiewicz/spring-pitfalls"&gt;here&lt;/a&gt;from &lt;a href="https://github.com/nurkiewicz/spring-pitfalls/tree/proxy-problem"&gt;proxy-problem&lt;/a&gt;branch. Don't complain about the lack of assertions – here we areonly testing that exceptions are not thrown:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;@RunWith(classOf[JUnitRunner])&lt;br /&gt;@ContextConfiguration&lt;br /&gt;class DefaultFooServiceTest extends FunSuite with ShouldMatchers with SpringRule{&lt;br /&gt;&lt;br /&gt;  @Resource&lt;br /&gt;  private val fooService: FooService = null&lt;br /&gt;&lt;br /&gt;  test("calling method from interface should apply transactional aspect") {&lt;br /&gt;    fooService.inInterfaceTransactional()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  test("calling non-transactional method from interface should start transaction for all called methods") {&lt;br /&gt;    fooService.inInterfaceNotTransactional()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Surprisingly, thetest fails. Well, if you've been reading my articles for a while youshouldn't be surprised: &lt;a href="http://nurkiewicz.blogspot.com/2009/08/spring-aop-riddle.html"&gt;SpringAOP riddle&lt;/a&gt; and &lt;a href="http://nurkiewicz.blogspot.com/2009/09/spring-aop-riddle-demystified.html"&gt;SpringAOP riddle demystified&lt;/a&gt;. Actually, the Spring referencedocumentation explains this in &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies"&gt;greatdetail&lt;/a&gt;, also check out &lt;a href="http://stackoverflow.com/questions/3037006"&gt;this&lt;/a&gt;SO question. In short – non transactional method callstransactional one but &lt;b&gt;bypassing&lt;/b&gt; the transactional proxy. Eventhough it seems obvious that when inInterfaceNotTransactional() callsinInterfaceTransactional() the transaction should start – it doesnot. The abstraction leaks. By the way also check out fascinating&lt;a href="http://www.ibm.com/developerworks/java/library/j-ts1/index.html"&gt;Transaction strategies: Understanding transaction pitfalls&lt;/a&gt; article for more.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Remember ourexample showing how CGLIB works? Also knowing how polymorphism worksit seems like using class based proxies should help.&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;inInterfaceNotTransactional()&lt;/span&gt; now calls &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;inInterfaceTransactional()&lt;/span&gt;overriden by CGLIB/Spring, which in turns calls the original classes.&lt;b&gt;Not a chance!&lt;/b&gt; This is the real implementation in pseudo-code:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;class DAO$EnhancerByCGLIB extends DAO {&lt;br /&gt;&lt;br /&gt;  val target: DAO = ...&lt;br /&gt;&lt;br /&gt;  override def findBy(id: Int) = {&lt;br /&gt;    startTransaction&lt;br /&gt;    try {&lt;br /&gt;      val result = target.findBy(id)&lt;br /&gt;      commitTransaction()&lt;br /&gt;      result&lt;br /&gt;    } catch {&lt;br /&gt;      case e =&amp;gt;&lt;br /&gt;        rollbackTransaction()&lt;br /&gt;        throw e&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Instead ofsubclassing and instantiating subclassed bean Spring first createsthe original bean and then creates a subclass which wraps theoriginal one (somewhat &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorator&lt;/a&gt;pattern) in one of the post processors. This means that – again –the self call inside bean bypasses AOP proxy around our class. Ofcourse using CGLIB changes how are bean behaves in few other ways.For instance we can now inject concrete class rather than aninterface, in fact the interface is not even needed and CGLIBproxying is required in this circumstances. There are also drawbacks– constructor injection is no longer possible, see &lt;a href="https://jira.springsource.org/browse/SPR-3150"&gt;SPR-3150&lt;/a&gt;,which is a &lt;a href="http://nurkiewicz.blogspot.com/2011/09/evolution-of-spring-dependency.html"&gt;shame&lt;/a&gt;.So what about some more thorough tests?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;@RunWith(classOf[JUnitRunner])&lt;br /&gt;@ContextConfiguration&lt;br /&gt;class DefaultFooServiceTest extends FunSuite with ShouldMatchers with SpringRule {&lt;br /&gt;&lt;br /&gt;  @Resource&lt;br /&gt;  private val fooService: DefaultFooService = null&lt;br /&gt;&lt;br /&gt;  test("calling method from interface should apply transactional aspect") {&lt;br /&gt;    fooService.inInterfaceTransactional()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  test("calling non-transactional method from interface should start transaction for all called methods") {&lt;br /&gt;    fooService.inInterfaceNotTransactional()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  test("calling transactional method not belonging to interface should start transaction for all called methods") {&lt;br /&gt;    fooService.publicNotInInterfaceButTransactional()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  test("calling non-transactional method not belonging to interface should start transaction for all called methods") {&lt;br /&gt;    fooService.publicNotInInterfaceAndNotTransactional()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Please pick teststhat will fail (pick exactly two). Can you explain why? Again commonsense would suggest that everything should pass, but that's not thecase. You can play around yourself, see &lt;a href="https://github.com/nurkiewicz/spring-pitfalls/tree/class-based-proxy"&gt;class-based-proxy&lt;/a&gt;branch.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;We are not here toexpose problems but to overcome them. Unfortunately our tangledservice class can only be fixed using heavy artillery – trueAspectJ weaving. Both compile- and load-time weaving makes the testpass. See &lt;a href="https://github.com/nurkiewicz/spring-pitfalls/tree/aspectj-ctw"&gt;aspectj-ctw&lt;/a&gt;and &lt;a href="https://github.com/nurkiewicz/spring-pitfalls/tree/aspectj-ltw"&gt;aspectj-ltw&lt;/a&gt;branches accordingly.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You should now beasking yourself several question. &lt;i&gt;Which approach should I take&lt;/i&gt;(or: &lt;i&gt;do I really need to use AspectJ?&lt;/i&gt;) and &lt;i&gt;why should Ieven bother?&lt;/i&gt; – amongst others. I would say – in most casessimple Spring proxying will suffice. But you absolutely have to beaware of how does the propagation work and when it doesn't. Otherwisebad things happen. Commits and rollbacks occurring in unexpectedplaces, spanning unexpected amount of data, ORM &lt;a href="http://stackoverflow.com/questions/82429"&gt;dirtychecking&lt;/a&gt; not working, invisible records – believe, this thingshappen on wild. And remember that topics we have covered here applyto all AOP aspects, not only transactions.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-624144439922682448?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/624144439922682448/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/10/spring-pitfalls-proxying.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/624144439922682448'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/624144439922682448'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/10/spring-pitfalls-proxying.html' title='Spring pitfalls: proxying'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-5094207683393029370</id><published>2011-09-23T22:43:00.000+02:00</published><updated>2011-11-17T19:28:59.132+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='logging'/><category scheme='http://www.blogger.com/atom/ns#' term='logback'/><title type='text'>Logging exceptions root cause first</title><content type='html'>The &lt;a href="http://logback.qos.ch/news.html"&gt;0.9.30&lt;/a&gt; releaseof &lt;a href="http://logback.qos.ch/"&gt;Logback&lt;/a&gt; logging librarybrings new awesome feature: logging stack traces starting from root(innermost) exception rather than from the outermost one. Of coursemy excitement has nothing to do with the fact that &lt;a href="http://logback.qos.ch/apidocs/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverter.html"&gt;Icontributed&lt;/a&gt; this feature...&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;To paraphrase Cecil B. de Mille: “&lt;i&gt;The way to make a blog post isto begin with a stack trace and work up to a climax&lt;/i&gt;” - here itgoes:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-89nDr6bsVSI/Tnzs8_R1SfI/AAAAAAAAAfo/KuGtmJ_gnkE/s1600/causedby.log.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="450" src="http://2.bp.blogspot.com/-89nDr6bsVSI/Tnzs8_R1SfI/AAAAAAAAAfo/KuGtmJ_gnkE/s640/causedby.log.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;The details aren't important yet, but from 100ft view you can seelong stack trace with several exceptions wrapping each other(&lt;i&gt;causing&lt;/i&gt;&lt;span style="font-style: normal;"&gt;). We'll go back tothis stack trace, but first some basics. If you throw an exception itwill be logged in a way showing how the stack was looking in themoment when the exception was from. At the very bottom you willeither see &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;static main()&lt;/span&gt; or &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;Thread.run()&lt;/span&gt; proceeded by methods invokedup to the first stack trace line indicating the place where theactual exception was thrown. This is very convenient since you cansee the whole control flow that resulted in the exception:&lt;/span&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class BookController {&lt;br /&gt;&lt;br /&gt;  private final BookService bookService = new BookService();&lt;br /&gt;&lt;br /&gt;  public void alpha() { beta(); }&lt;br /&gt;&lt;br /&gt;  private void beta() { gamma(); }&lt;br /&gt;&lt;br /&gt;  private void gamma() { bookService.delta(); }&lt;br /&gt;&lt;br /&gt;  public static void main(String[] args) {&lt;br /&gt;    new BookController().alpha();&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class BookService {&lt;br /&gt;&lt;br /&gt;  private final BookDao bookDao = new BookDao();&lt;br /&gt;&lt;br /&gt;  public void delta() { epsilon(); }&lt;br /&gt;&lt;br /&gt;  private void epsilon() { zeta(); }&lt;br /&gt;&lt;br /&gt;  private void zeta() { bookDao.eta(); }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class BookDao {&lt;br /&gt;&lt;br /&gt;  public void eta() { theta(); }&lt;br /&gt;&lt;br /&gt;  private void theta() { iota(); }&lt;br /&gt;&lt;br /&gt;  public void iota() { throw new RuntimeException("Omega server not available"); }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;If you don't know the &lt;a href="http://en.wikipedia.org/wiki/Greek_alphabet"&gt;Greekalphabet&lt;/a&gt;, you can start learning from the stack trace (remember,the control flow starts at the bottom and works its way up):&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;&lt;pre class="brush: plain"&gt;&lt;br /&gt;java.lang.RuntimeException: Omega server not available&lt;br /&gt;  at BookDao.iota(BookController.java:50)&lt;br /&gt;  at BookDao.theta(BookController.java:48)&lt;br /&gt;  at BookDao.eta(BookController.java:46)&lt;br /&gt;  at BookService.zeta(BookController.java:41)&lt;br /&gt;  at BookService.epsilon(BookController.java:39)&lt;br /&gt;  at BookService.delta(BookController.java:37)&lt;br /&gt;  at BookController.gamma(BookController.java:22)&lt;br /&gt;  at BookController.beta(BookController.java:20)&lt;br /&gt;  at BookController.alpha(BookController.java:18)&lt;br /&gt;  at BookController.main(BookController.java:26)&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;Wonderful, right? When readingfrom top to bottom you can say: &lt;/span&gt;&lt;i&gt;iota() was called bytheta() was called by eta()&lt;/i&gt;&lt;span style="font-style: normal;"&gt;...Clear and simple. However what if somebody decides to wrap theoriginal exception and re-throw it?&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class BookController {&lt;br /&gt;&lt;br /&gt;  private static final Logger log = LoggerFactory.getLogger(BookController.class);&lt;br /&gt;&lt;br /&gt;  private final BookService bookService = new BookService();&lt;br /&gt;&lt;br /&gt;  public void alpha() { beta(); }&lt;br /&gt;&lt;br /&gt;  private void beta() { gamma(); }&lt;br /&gt;&lt;br /&gt;  private void gamma() {&lt;br /&gt;    try {&lt;br /&gt;      bookService.delta();&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;      throw new RuntimeException("Sorry, try again later", e);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public static void main(String[] args) {&lt;br /&gt;    try {&lt;br /&gt;      new BookController().alpha();&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;      log.error("", e);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class BookService {&lt;br /&gt;&lt;br /&gt;  private final BookDao bookDao = new BookDao();&lt;br /&gt;&lt;br /&gt;  public void delta() { epsilon(); }&lt;br /&gt;&lt;br /&gt;  private void epsilon() { zeta(); }&lt;br /&gt;&lt;br /&gt;  private void zeta() {&lt;br /&gt;    try {&lt;br /&gt;      bookDao.eta();&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;      throw new RuntimeException("Unable to save order", e);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class BookDao {&lt;br /&gt;&lt;br /&gt;  public void eta() { theta(); }&lt;br /&gt;&lt;br /&gt;  private void theta() { iota(); }&lt;br /&gt;&lt;br /&gt;  public void iota() {&lt;br /&gt;    try {&lt;br /&gt;      throw new RuntimeException("Omega server not available");&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;      throw new RuntimeException("Database problem", e);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;Now quickly: find the root causein the stack trace!&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;&lt;pre class="brush: plain"&gt;&lt;br /&gt;java.lang.RuntimeException: Sorry, try again later&lt;br /&gt;  at BookController.gamma(BookController.java:26)&lt;br /&gt;  at BookController.beta(BookController.java:20)&lt;br /&gt;  at BookController.alpha(BookController.java:18)&lt;br /&gt;  at BookController.main(BookController.java:32)&lt;br /&gt;Caused by: java.lang.RuntimeException: Unable to save order&lt;br /&gt;  at BookService.zeta(BookController.java:51)&lt;br /&gt;  at BookService.epsilon(BookController.java:45)&lt;br /&gt;  at BookService.delta(BookController.java:43)&lt;br /&gt;  at BookController.gamma(BookController.java:24)&lt;br /&gt;  ... 8 common frames omitted&lt;br /&gt;Caused by: java.lang.RuntimeException: Database problem&lt;br /&gt;  at BookDao.iota(BookController.java:66)&lt;br /&gt;  at BookDao.theta(BookController.java:60)&lt;br /&gt;  at BookDao.eta(BookController.java:58)&lt;br /&gt;  at BookService.zeta(BookController.java:49)&lt;br /&gt;  ... 11 common frames omitted&lt;br /&gt;Caused by: java.lang.RuntimeException: Omega server not available&lt;br /&gt;  at BookDao.iota(BookController.java:64)&lt;br /&gt;  ... 14 common frames omitted&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;Turns out that &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;main()&lt;/span&gt; is nolonger the last line. Even worse, everything seems garbled, try toread the Greek alphabet again... Now let's go back to our originalstack trace. It comes from Spring framework startup failure, imagineit can be several pages long.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-UjNwQ8LgHac/Tnzs9xcbhQI/AAAAAAAAAfs/Zp0DhfDrzm8/s1600/causedby-arrows.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="460" src="http://4.bp.blogspot.com/-UjNwQ8LgHac/Tnzs9xcbhQI/AAAAAAAAAfs/Zp0DhfDrzm8/s640/causedby-arrows.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;For you convenience I addedarrows to mark you the path you should follow to reconstruct thecontrol flow: starting from the red arrow's tail (&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;Thread.run()&lt;/span&gt;)somewhere in the middle you go up and then... jump to the tail oforange arrow. From the head of the orange arrow you jump to the tailof the green one and so on... Not very intuitive, don't you think?And what is this red ellipse showing? Yes, it is the root cause ofthe failure (the innermost exception). On the other hand theexception printed at the very beginning (the one you typically readon the first place) says something about an &lt;i style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;error creatingDefaultAnnotationHandlerMapping#0&lt;/i&gt; (&lt;i&gt;what?&lt;/i&gt;) The true error (&lt;i&gt;&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;No matchingbean of type...&lt;/span&gt;&lt;/i&gt;) is cleverly hidden...&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;So what is this &lt;a href="http://logback.qos.ch/manual/layouts.html#rootException"&gt;newfeature&lt;/a&gt; all about? Again our simple example. After upgrading to0.9.30 just add &lt;span style="font-size: large;"&gt;&lt;b&gt;&lt;a href="http://logback.qos.ch/manual/layouts.html#rootException" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;%rEx&lt;/a&gt;&lt;/b&gt;&lt;/span&gt;(or equivalent &lt;b&gt;&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;%rootException&lt;/span&gt;&lt;/b&gt;) at the end of your logging pattern:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;code style="font-size: 14px;"&gt;&amp;lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"&amp;gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;lt;encoder&amp;gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;lt;pattern&amp;gt;%d %level %m%n&lt;strong&gt;%rEx&lt;/strong&gt;&amp;lt;/pattern&amp;gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;lt;/encoder&amp;gt;&lt;br /&gt;&amp;lt;/appender&amp;gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: normal;"&gt;This will replace the defaultstack trace printing routing with the one I humbly contributed. Thesame Greek program will now print:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: plain"&gt;&lt;br /&gt;java.lang.RuntimeException: Omega server not available&lt;br /&gt;  at BookDao.iota(BookController.java:64)&lt;br /&gt;Wrapped by: java.lang.RuntimeException: Database problem&lt;br /&gt;  at BookDao.iota(BookController.java:66)&lt;br /&gt;  at BookDao.theta(BookController.java:60)&lt;br /&gt;  at BookDao.eta(BookController.java:58)&lt;br /&gt;  at BookService.zeta(BookController.java:49)&lt;br /&gt;Wrapped by: java.lang.RuntimeException: Unable to save order&lt;br /&gt;  at BookService.zeta(BookController.java:51)&lt;br /&gt;  at BookService.epsilon(BookController.java:45)&lt;br /&gt;  at BookService.delta(BookController.java:43)&lt;br /&gt;  at BookController.gamma(BookController.java:24)&lt;br /&gt;Wrapped by: java.lang.RuntimeException: Sorry, try again later&lt;br /&gt;  at BookController.gamma(BookController.java:26)&lt;br /&gt;  at BookController.beta(BookController.java:20)&lt;br /&gt;  at BookController.alpha(BookController.java:18)&lt;br /&gt;  at BookController.main(BookController.java:32)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Please compare it carefully with the previous output. First ofall, the very first line points to the problem. No digging in the“&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;Caused by&lt;/span&gt;” exceptions, most of the time you will probably skipthe rest. Secondly, the control flow is uninterrupted and continuous– you can still read it from top to bottom or vice-versa. And lastbut not least – the fact that exceptions were wrapped in themeantime is preserved but does not garble the stack trace.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now you deserve to see the original Spring exception takingadvantage of &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;%rEx&lt;/span&gt; printing:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-cgyIJ13n4VE/Tnzs_0yZVSI/AAAAAAAAAf0/GIzCYbVdITE/s1600/wrappedby-arrows.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="430" src="http://1.bp.blogspot.com/-cgyIJ13n4VE/Tnzs_0yZVSI/AAAAAAAAAf0/GIzCYbVdITE/s640/wrappedby-arrows.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The observations are exactly the same: root cause of the problemappears at the very beginning, shortening the time the problem needsto be investigated. Also when analysing the control flow there is notjumping – &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;Thread.main()&lt;/span&gt; is at the bottom and you can read the tracefrom bottom to top continuously.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;If you “work” a lot with stack traces (either in developmentor in production/support) – consider switching to root cause firstlogging. It will save you few seconds every time you analyseparticular exception. But I also noticed inexperienced developerssometimes aren't even aware of “&lt;i&gt;&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;Caused by&lt;/span&gt;&lt;/i&gt;” rule: &lt;i&gt;find firstexception and look at the last &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;Caused by&lt;/span&gt;&lt;/i&gt; – remaining clueless whatthe problem is, looking only at the outermost, least specific, mostgeneric error. This will help them as well.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;By the way – all this hustle can be avoided if you avoidwrapping and re-throwing exception altogether. I know, all too oftenwe are forced to do so by checked exceptions...&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-5094207683393029370?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/5094207683393029370/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/09/logging-exceptions-root-cause-first.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/5094207683393029370'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/5094207683393029370'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/09/logging-exceptions-root-cause-first.html' title='Logging exceptions root cause first'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-89nDr6bsVSI/Tnzs8_R1SfI/AAAAAAAAAfo/KuGtmJ_gnkE/s72-c/causedby.log.png' height='72' width='72'/><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-2618588514620661673</id><published>2011-09-01T22:01:00.000+02:00</published><updated>2011-11-17T19:27:22.781+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>The evolution of Spring dependency injection techniques</title><content type='html'>&lt;div&gt;Looking back at the history of Springframework you will find out that the number of ways you can implementdependency injection is growing in every release. If you've beenworking with this framework for more than a month you'll probablyfind nothing interesting in this retrospective article. Nothinghopefully except the last example in Scala, language thataccidentally works great with Spring.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4&gt;First there was XML [&lt;a href="https://github.com/nurkiewicz/spring-di/tree/xml"&gt;fullsource&lt;/a&gt;]:&lt;/h4&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd "&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="foo" class="com.blogspot.nurkiewicz.Foo"&amp;gt;&lt;br /&gt;        &amp;lt;property name="bar" ref="bar"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="jdbcOperations" ref="jdbcTemplate"/&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="bar" class="com.blogspot.nurkiewicz.Bar" init-method="init"/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&amp;gt;&lt;br /&gt;        &amp;lt;property name="driverClassName" value="org.h2.Driver"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="url" value="jdbc:h2:mem:"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="username" value="sa"/&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg ref="dataSource"/&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;This simple application only fetches H2database server time and prints it with full formatting:&lt;/div&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class Foo {&lt;br /&gt;&lt;br /&gt;    private Bar bar;&lt;br /&gt;&lt;br /&gt;    private JdbcOperations jdbcOperations;&lt;br /&gt;&lt;br /&gt;    public String serverTime() {&lt;br /&gt;        return bar.format(&lt;br /&gt;                jdbcOperations.queryForObject("SELECT now()", Date.class)&lt;br /&gt;        );&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void setBar(Bar bar) {&lt;br /&gt;        this.bar = bar;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void setJdbcOperations(JdbcOperations jdbcOperations) {&lt;br /&gt;        this.jdbcOperations = jdbcOperations;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class Bar {&lt;br /&gt;&lt;br /&gt;    private FastDateFormat dateFormat;&lt;br /&gt;&lt;br /&gt;    public void init() {&lt;br /&gt;        dateFormat = FastDateFormat.getDateTimeInstance(FULL, FULL);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public String format(Date date) {&lt;br /&gt;        return dateFormat.format(date);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;There is something disturbing aboutthis code. First of all there is surprisingly a lot of XML. It isstill less compared to similar EJB 2.1 application (with &lt;a href="https://github.com/nurkiewicz/spring-di/tree/spring-1.2.6"&gt;minorchanges&lt;/a&gt; this code runs on Spring 1.2.6 dating back to 2006), butit just feels wrong. The public setters are even more disturbing –why are we forced to expose the ability to override objectdependencies at any time and by anyone? By the way I never reallyunderstood why Spring does not allow injecting dependencies directlyto private fields when &amp;lt;property&amp;gt; tag is used since it ispossible with...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4&gt;Annotations [&lt;a href="https://github.com/nurkiewicz/spring-di/tree/annotations"&gt;fullsource&lt;/a&gt;]&lt;/h4&gt;&lt;div&gt;Java 5 and Spring 2.5 brought supportfor annotation-driven dependency injection:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;context:annotation-config/&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!-- or even: --&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;context:component-scan base-package="com.blogspot.nurkiewicz"/&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Take the first line and you no longerhave to define &amp;lt;property&amp;gt; tags in your XML, only &amp;lt;bean&amp;gt;s.The framework will pick up standard @Resource annotations. Replace itwith the second line and you don't even have to specify beans in yourXML at all:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Service&lt;br /&gt;public class Foo {&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private Bar bar;&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private JdbcOperations jdbcOperations;&lt;br /&gt;&lt;br /&gt;    public String serverTime() {&lt;br /&gt;        return bar.format(&lt;br /&gt;                jdbcOperations.queryForObject("SELECT now()", Date.class)&lt;br /&gt;        );&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Service&lt;br /&gt;public class Bar {&lt;br /&gt;&lt;br /&gt;    private FastDateFormat dateFormat;&lt;br /&gt;&lt;br /&gt;    @PostConstruct&lt;br /&gt;    public void init() {&lt;br /&gt;        dateFormat = FastDateFormat.getDateTimeInstance(FULL, FULL);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public String format(Date date) {&lt;br /&gt;        return dateFormat.format(date);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Of course you are not impressed! &lt;i&gt;Nihilnovi&lt;/i&gt;. Also we still have to live with XML because we have nocontrol over 3rd party classes (like data source and &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html"&gt;JdbcTemplate&lt;/a&gt;),hence we can't annotate them. But Spring 3.0 introduced:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4&gt;@Configuration [&lt;a href="https://github.com/nurkiewicz/spring-di/tree/at-configuration"&gt;fullsource&lt;/a&gt;]&lt;/h4&gt;&lt;div&gt;I've been already exploring the&lt;a href="http://nurkiewicz.blogspot.com/2011/01/spring-framework-without-xml-at-all.html"&gt;@Configuration/@Bean&lt;/a&gt;support, so this time please focus on how we start the applicationcontext. Do you see any reference to the XML file? TheapplicationContext.xml descriptor is gone completely:&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@ComponentScan("com.blogspot.nurkiewicz")&lt;br /&gt;public class Bootstrap {&lt;br /&gt;&lt;br /&gt;    private static final Logger log = LoggerFactory.getLogger(Bootstrap.class);&lt;br /&gt;&lt;br /&gt;    @Bean&lt;br /&gt;    public DataSource dataSource() {&lt;br /&gt;        final BasicDataSource dataSource = new BasicDataSource();&lt;br /&gt;        dataSource.setDriverClassName("org.h2.Driver");&lt;br /&gt;        dataSource.setUrl("jdbc:h2:mem:");&lt;br /&gt;        dataSource.setUsername("sa");&lt;br /&gt;        return dataSource;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Bean&lt;br /&gt;    public JdbcTemplate jdbcTemplate() {&lt;br /&gt;        return new JdbcTemplate(dataSource());&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void main(String[] args) {&lt;br /&gt;        final AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(Bootstrap.class);&lt;br /&gt;        final Foo foo = applicationContext.getBean(Foo.class);&lt;br /&gt;&lt;br /&gt;        log.info(foo.serverTime());&lt;br /&gt;&lt;br /&gt;        applicationContext.close();&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As you can see Spring came quite a longroad from XML-heavy to XML-free framework. But the most exciting partis that you can you use whichever style you prefer or even mix them.You can take legacy Spring application and start using annotations orswitch to XML for god knows what reasons here or there.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;One technique I haven't mentioned isconstructor injection. It has some great benefits (see &lt;a href="http://tech.finn.no/2011/05/13/dependency-injection-with-constructors/"&gt;&lt;i&gt;DependencyInjection with constructors?&lt;/i&gt;&lt;/a&gt;), like ability to markdependencies as final and forbidding to create uninitialized objects:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Service&lt;br /&gt;public class Foo {&lt;br /&gt;&lt;br /&gt;    private final Bar bar;&lt;br /&gt;&lt;br /&gt;    private final JdbcOperations jdbcOperations;&lt;br /&gt;&lt;br /&gt;    @Autowired&lt;br /&gt;    public Foo(Bar bar, JdbcOperations jdbcOperations) {&lt;br /&gt;        this.bar = bar;&lt;br /&gt;        this.jdbcOperations = jdbcOperations;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    //...&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I would love constructor injection,however once again I feel a bit disappointed. Each and every objectdependency requires (a) constructor parameter, (b) final field and(c) assignment operation in constructor. We end up with ten lines ofcode that don't do anything yet. This chatty code  overcomes all theadvantages. Of course no object should have more than &lt;i&gt;(put yournumber here)&lt;/i&gt; dependencies – and thanks to constructor injectionyou immediately &lt;b&gt;see&lt;/b&gt; that theobject has too many – but still I find this code introducing toomuch ceremony.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4&gt;Spring constructor injection with Scala [&lt;a href="https://github.com/nurkiewicz/spring-di/tree/scala"&gt;fullsource&lt;/a&gt;]&lt;/h4&gt;One feature of Scala fits perfectly into Spring framework: eachargument of any Scala object by default creates final field named thesame as this argument. What does this mean in our case? Look at Fooclass translated to Scala:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;@Service&lt;br /&gt;class Foo @Autowired() (bar: Bar, jdbcOperations: JdbcOperations) {&lt;br /&gt;&lt;br /&gt;    def serverTime() = bar.format(jdbcOperations.queryForObject("SELECT now()", classOf[Date]))&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div&gt;Seriously?But... how? Before we dive into advantages of Scala here, look at theequivalent Java code as generated by Java decompiler:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Service&lt;br /&gt;public class Foo implements ScalaObject&lt;br /&gt;{&lt;br /&gt;    private final Bar bar;&lt;br /&gt;    private final JdbcOperations jdbcOperations;&lt;br /&gt;&lt;br /&gt;    @Autowired&lt;br /&gt;    public Foo(Bar bar, JdbcOperations jdbcOperations)&lt;br /&gt;    {&lt;br /&gt;        this.bar = bar;&lt;br /&gt;        this.jdbcOperations = jdbcOperations;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public String serverTime()&lt;br /&gt;    {&lt;br /&gt;        return this.bar.format(this.jdbcOperations.queryForObject("SELECT now()", Date.class));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Almost exactly the same code as wewould have written in Java. With all the advantages: dependencies arefinal making our services truly immutable and stateless; dependenciesare private and not exposed to the outside world; literally no extracode to manage dependencies: just add constructor argument, Scalawill take care of the rest.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To wrap things up – you have a widerange of possibilities. From XML, through Java code to Scala. Thelast approach is actually very tempting as it saves you from all theboilerplate and allows you to focus on business functionality. The&lt;a href="https://github.com/nurkiewicz/spring-di"&gt;full source code&lt;/a&gt;is available under my GitHub repository, each step is tagged so youcan compare and choose whichever approach you like the most.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-2618588514620661673?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/2618588514620661673/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/09/evolution-of-spring-dependency.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2618588514620661673'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2618588514620661673'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/09/evolution-of-spring-dependency.html' title='The evolution of Spring dependency injection techniques'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-3527227597997947083</id><published>2011-08-07T18:15:00.002+02:00</published><updated>2011-11-17T19:25:44.807+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>What features of Java have been dropped in Scala?</title><content type='html'>&lt;br /&gt;&lt;div&gt;Despite more complex and less intuitive syntax compared to Java, Scala actually drops several features of Java, sometimes for good, other times providing replacements on the standard library level. As you will see soon, Scala isn't a superset of Java (like Groovy) and actually removes a lot of noise. Below is a catalogue of &lt;i&gt;the missing features&lt;/i&gt;&lt;span style="font-style: normal;"&gt;.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4&gt;break and continue in loops&lt;/h4&gt;Every time I see code like this:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;while(cond1) {&lt;br /&gt;    work();&lt;br /&gt;    if(cond2)&lt;br /&gt;        continue;&lt;br /&gt;    rest();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I feel as if it has been written by a guy who truly misses the times when &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;goto&lt;/span&gt; wasn't yet considered harmful. Hands up who finds this version more readable:&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;while(cond1) {&lt;br /&gt;    work();&lt;br /&gt;    if(!cond2)&lt;br /&gt;        rest();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Getting rid of break requires a little more though, but generally extracting a loop to a separate method/function (or at least putting it at the end of existing method) and using return instead will do the trick. By the why Scala allows you to define functions inside other functions, so you won't pollute your global class namespace with plenty of small methods used only once – problem that sometimes arises when &lt;a href="http://www.amazon.com/gp/product/0132350882/ref=as_li_ss_tl?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=217145&amp;amp;creative=399369&amp;amp;creativeASIN=0132350882"&gt;religiously&lt;/a&gt; extracting methods in Java.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;break&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;continue&lt;/span&gt; – we thank you in the name of our fathers and grandfathers for your contribution to imperative programming. But we no longer need you and we won't miss you.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Arrays&lt;/h4&gt;It's amazing how many bad habits have we learnt by all these years and how we got used to idioms that are inconsistent and simply painful. You have covariant arrays in Java with square brackets syntax, &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;length&lt;/span&gt; final property and ability to store primitive types. You also have Java collections framework with &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;List&amp;amp;amp;lt;T&amp;amp;amp;gt;&lt;/span&gt; abstraction – that is not covariant, uses &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;get()&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;size()&lt;/span&gt; methods and can't store primitives. The list of differences does not end here, however isn't every array just a special case of &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;List&lt;/span&gt;? Why do we have a special syntax for arrays in the language while collections are implemented in on top of the language? And isn't a bit irritating to convert them from one to another all the time?&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;String[] array = new String[10];&lt;br /&gt;List&amp;lt;String&amp;gt; list = Arrays.asList(array);&lt;br /&gt;String[] array2 = list.toArray(new String[list.size()]);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Converting from collection to array is my favourite Java idiom... Why not just have same syntax, same methods, same abstraction, polymorphic behaviour – and only different implementation names?  &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;val array = Array("ab", "c", "def")&lt;br /&gt;println(array(1))&lt;br /&gt;array filter (_.size &amp;gt; 1)&lt;br /&gt;&lt;br /&gt;val list = List("ab", "c", "def")&lt;br /&gt;println(list(1))&lt;br /&gt;println(list filter (_.size &amp;gt; 1))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;And don't worry, behind the scenes Scala compiler will use the same efficient array bytecode as if you were using plain arrays in Java. No magic abstractions and several layers of wrapping.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Primitives&lt;/h4&gt;Another weird Java inconsistency – why do we have a choice between primitive &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;int&lt;/span&gt; and wrapping &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;Integer&lt;/span&gt;? If the variable is of Integer type does this mean it is optional (&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;null&lt;/span&gt;), or is it just that you can't use primitives in collections (but can in arrays, as pointed out above)? Is this unboxing safe (also known as: &lt;i&gt;how on earth this can throw NullPointerException&lt;/i&gt;?) Can I compare these to integers using == operator? And can I simply call &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;toString()&lt;/span&gt; to get string representation of this number?&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In Scala you no longer have a choice, every primitive type is an object, while most of the time still being a primitive in memory and in bytecode. How is that possible? Have a look at the following popular example:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;val x = 37     //x and y are objects of type Int&lt;br /&gt;val y = 5&lt;br /&gt;val z = x + y  //x.+(y) - yes, Int class has a "+" method&lt;br /&gt;assert(z.toString == "42")&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;x&lt;/span&gt;, &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;y&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;z&lt;/span&gt; are instances of type &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;Int&lt;/span&gt;. They are all objects, even adding two integers is semantically a method &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;+&lt;/span&gt; called on &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;x&lt;/span&gt; with &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;y&lt;/span&gt; argument. If you think it has to perform terribly – once again behind the scenes it is compiled into ordinary primitive addition. But now you can easily use primitives in collections, pass them when any type is required (Object in Java, Any in Scala) or simply create a text representation without awkward &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;Integer.toString(7)&lt;/span&gt; idiom. Sooo many bad habits.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Checked exceptions&lt;/h4&gt;Another feature that I can hardly miss. Not much to be said here. Neither any mainstream language except Java have them, nor any mainstream JVM language (except Java). This topic is still relatively controversial, however if you've ever tried to deal with ubiquitous &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;SQLException&lt;/span&gt; or &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;IOException&lt;/span&gt;, you know how much boilerplate it introduces without good reason. Anyway, look at the next examples...&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Interfaces&lt;/h4&gt;This one is good! Scala doesn't have interfaces. Instead it introduces traits – something in between abstract classes (some trait methods might have implementation) and interfaces (one can mix in more than one trait). So essentially traits enables you to implement multiple inheritance while avoiding dreadful &lt;a href="http://en.wikipedia.org/wiki/Diamond_problem"&gt;diamond problem&lt;/a&gt;. How it is done requires an article on its own (in short: last trait wins), but I would rather show you an example how helpful traits are to reduce duplication.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Suppose you are writing an interface to abstract binary protocol. Most implementations take raw byte array, so in Java you would simply say:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public interface Marshaller {&lt;br /&gt;    long send(byte[] content);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;This is great from the implementation perspective – just implement a single method and the abstraction is ready. However users of the interface are complaining that it is cumbersome and not very convenient. They would like to send strings, binary and text streams, serialized objects and so on. They can either create a facade around this interface (and every user will create his/hers very own with a distinct set of bugs) or force the author of the API to extend it:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public interface Marshaller {&lt;br /&gt;&lt;br /&gt;    long send(byte[] content);&lt;br /&gt;&lt;br /&gt;    long send(InputStream stream);&lt;br /&gt; &lt;br /&gt;    long send(Reader reader);&lt;br /&gt; &lt;br /&gt;    long send(String s);&lt;br /&gt;&lt;br /&gt;    long send(Serializable obj);&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now the API is a breeze, however every implementation has to implement five methods instead of one. Also note that since most abstracted protocols are based on byte arrays, all the methods can be implemented in terms of the first one. And only the first one contains the actual marshalling code. This in turns causes every implementation to have the exact same four methods – duplication didn't go away – it has just been moved. Actually this problem is known as a thin vs. rich interface and it has been described in great &lt;a href="http://www.amazon.com/gp/product/0981531644/ref=as_li_ss_tl?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=217145&amp;amp;creative=399369&amp;amp;creativeASIN=0981531644"&gt;Programming in Scala&lt;/a&gt; book.&lt;br /&gt;What I was typically doing was to give service providers an abstract class with typical implementations of all the methods except the root one, which was used by all other methods:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;import org.apache.commons.io.IOUtils;&lt;br /&gt;&lt;br /&gt;public abstract class MarshallerSupport implements Marshaller {&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public abstract long send(byte[] content);&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public long send(InputStream stream) {&lt;br /&gt;        try {&lt;br /&gt;            return send(IOUtils.toByteArray(stream));&lt;br /&gt;        } catch (IOException e) {&lt;br /&gt;            throw new RuntimeException(e);  //choose something more specific in real life&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public long send(Reader reader) {&lt;br /&gt;        try {&lt;br /&gt;            return send(IOUtils.toByteArray(reader));&lt;br /&gt;        } catch (IOException e) {&lt;br /&gt;            throw new RuntimeException(e);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public long send(String s) {&lt;br /&gt;        try {&lt;br /&gt;            return send(s.getBytes("UTF8"));&lt;br /&gt;        } catch (UnsupportedEncodingException e) {&lt;br /&gt;            throw new RuntimeException(e);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public long send(Serializable obj) {&lt;br /&gt;        try {&lt;br /&gt;            final ByteArrayOutputStream bytes = new ByteArrayOutputStream();&lt;br /&gt;            new ObjectOutputStream(bytes).writeObject(obj);&lt;br /&gt;            return send(bytes.toByteArray());&lt;br /&gt;        } catch (IOException e) {&lt;br /&gt;            throw new RuntimeException(e);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now everyone is happy – instead of copying all the overloaded methods over and over, just subclass the &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;MarshallerSupport&lt;/span&gt; and implement what you need. But what if your interface implementation also has to subclass some other class? You are out of luck then. In Scala however you change the interface to trait, opening the possibility to mix in (think something between extending and implementing) several other traits. By the way do you remember what I said about checked exceptions?&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;trait MarshallerSupport extends Marshaller {&lt;br /&gt;&lt;br /&gt;    def send(content: Array[Byte]): Long&lt;br /&gt;&lt;br /&gt;    def send(stream: InputStream): Long = send(IOUtils.toByteArray(stream))&lt;br /&gt;&lt;br /&gt;    def send(reader: Reader): Long = send(IOUtils.toByteArray(reader))&lt;br /&gt;&lt;br /&gt;    def send(s: String): Long = send(s.getBytes("UTF8"))&lt;br /&gt;&lt;br /&gt;    def send(obj: Serializable): Long = {&lt;br /&gt;        val bytes = new ByteArrayOutputStream&lt;br /&gt;        new ObjectOutputStream(bytes).writeObject(obj)&lt;br /&gt;        send(bytes.toByteArray)&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Switch statement&lt;/h4&gt;There is no &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;switch&lt;/span&gt; statement in Scala. Calling &lt;a href="http://www.scala-lang.org/node/120"&gt;pattern matching&lt;/a&gt; a better switch would be a blasphemy. Not only because pattern matching in Scala is an expression returning a value and also not because you can switch over literally any value if you want. Not even because there is no fall-through, break and default. It's because Scala's pattern matching enables you to match whole object structures and lists, even with wildcards. Consider this expression simplification method, originally taken from already mentioned &lt;a href="http://www.amazon.com/gp/product/0981531644/ref=as_li_ss_tl?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=217145&amp;amp;creative=399369&amp;amp;creativeASIN=0981531644"&gt;Programming in Scala&lt;/a&gt; book:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;abstract class Expr&lt;br /&gt;case class Var(name: String) extends Expr&lt;br /&gt;case class Number(num: Double) extends Expr&lt;br /&gt;case class UnOp(operator: String, arg: Expr) extends Expr&lt;br /&gt;case class BinOp(operator: String, left: Expr, right: Expr) extends Expr&lt;br /&gt;&lt;br /&gt;//...&lt;br /&gt;&lt;br /&gt;def simplify(expr: Expr): Expr = expr match {&lt;br /&gt;    case UnOp("-", UnOp("-", e)) =&amp;gt; e  //double negation&lt;br /&gt;    case BinOp("+", e, Number(0)) =&amp;gt; e //adding zero&lt;br /&gt;    case BinOp("*", e, Number(1)) =&amp;gt; e //multiplying by one&lt;br /&gt;    case _ =&amp;gt; expr&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Look carefully how clever this code is! If our expression is unary “&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;-&lt;/span&gt;” operation and the argument is a second unary “&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;-&lt;/span&gt;” operation with any expression &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;e&lt;/span&gt; as an argument (think: &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;-(-e)&lt;/span&gt;), then simply return &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;e&lt;/span&gt;. If you find this pattern matching example hard to read, check out the roughly equivalent Java code. However please remember: size doesn't matter (one could probably do the same with Perl one-liner) – it's about readability and maintainability:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public Expr simplify(Expr expr) {&lt;br /&gt;    if (expr instanceof UnOp) {&lt;br /&gt;        UnOp unOp = (UnOp) expr;&lt;br /&gt;        if (unOp.getOperator().equals("-")) {&lt;br /&gt;            if (unOp.getArg() instanceof UnOp) {&lt;br /&gt;                UnOp arg = (UnOp) unOp.getArg();&lt;br /&gt;                if (arg.getOperator().equals("-"))&lt;br /&gt;                    return arg.getArg();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    if (expr instanceof BinOp) {&lt;br /&gt;        BinOp binOp = (BinOp) expr;&lt;br /&gt;        if (binOp.getRight() instanceof Number) {&lt;br /&gt;            Number arg = (Number) binOp.getRight();&lt;br /&gt;            if (binOp.getOperator().equals("+") &amp;&amp; arg.getNum() == 0 ||&lt;br /&gt;                    binOp.getOperator().equals("*") &amp;&amp; arg.getNum() == 1)&lt;br /&gt;                return binOp.getLeft();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    return expr;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;UPDATE&lt;/span&gt;:In one of the comments &lt;i&gt;Yassine Elouafi&lt;/i&gt;&lt;span style="font-style: normal;"&gt;claims this example is too limited as it can not simplify nestedexpressions like: &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;BinOp("+", Var("x"), BinOp("*",Var("y"), Number(0)))&lt;/span&gt; which reads: &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;x + y * 0&lt;/span&gt;. Indeed thisalgorithm assumes nested terms are already simplified. But it shouldbe pretty obvious to improve this code to work with arbitrary complexexpressions – without loosing readability. Recursion with bottom-upapproach seems perfect: simplify the leaves first (simplest terms)and go up. Here is the improved code:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;def simplify(expr: Expr): Expr = expr match {&lt;br /&gt;    case UnOp("-", UnOp("-", e)) =&amp;gt; simplify(e)&lt;br /&gt;    case BinOp("+", e, Number(0)) =&amp;gt; simplify(e)&lt;br /&gt;    case b@BinOp("+", _, _) =&amp;gt; simplify(BinOp(b.operator, simplify(b.left), simplify(b.right)))&lt;br /&gt;    case BinOp("*", e, Number(1)) =&amp;gt; simplify(e)&lt;br /&gt;    case BinOp("*", e, Number(0)) =&amp;gt; Number(0)&lt;br /&gt;    case _ =&amp;gt; expr&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Not that bad, don't you think? Ofcourse there are still several improvements that might be applied (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;0+ e&lt;/span&gt;, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;1 * e&lt;/span&gt;, operations on constants, etc.), but thanks to the powerof recursion the results are already quite impressive:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;//x + y * 0&lt;br /&gt;assert(simplify(BinOp("+", Var("x"), BinOp("*", Var("y"), Number(0)))) === Var("x"))&lt;br /&gt;&lt;br /&gt;//(x + y) * 0&lt;br /&gt;assert(simplify(BinOp("*", BinOp("+", Var("x"), Var("y")), Number(0))) === Number(0.0))&lt;br /&gt;&lt;br /&gt;//-(-(-(-5)))&lt;br /&gt;assert(simplify(UnOp("-", UnOp("-", UnOp("-", UnOp("-", Number(5)))))) === Number(5.0))&lt;br /&gt;&lt;br /&gt;//y * 1 + (x + z) * 0&lt;br /&gt;assert(&lt;br /&gt;    simplify(&lt;br /&gt;        BinOp(&lt;br /&gt;            "+",&lt;br /&gt;            BinOp(&lt;br /&gt;                "*",&lt;br /&gt;                Var("y"),&lt;br /&gt;                Number(1)&lt;br /&gt;            ),&lt;br /&gt;            BinOp(&lt;br /&gt;                "*",&lt;br /&gt;                BinOp(&lt;br /&gt;                    "+",&lt;br /&gt;                    Var("x"),&lt;br /&gt;                    Var("z")&lt;br /&gt;                ),&lt;br /&gt;                Number(0)&lt;br /&gt;            )&lt;br /&gt;        )&lt;br /&gt;    ) === Var("y")&lt;br /&gt;)&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-style: normal;"&gt;So isScala scalable?&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;&lt;h4&gt;instanceof/casting&lt;/h4&gt;As with many other features, Scala does not have a built-in syntax for &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;instanceof&lt;/span&gt; and downcasting. Instead the language provides you methods on actual objects:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;val b: Boolean = expr.isInstanceOf[UnOp]&lt;br /&gt;val unOp: UnOp = expr.asInstanceOf[UnOp]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In Scala a lot of features normally considered as part of the language are actually implemented in the language itself or at least they don't require a special syntax. I like this idea, in fact I find Ruby's way of creating objects (&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;Foo.new&lt;/span&gt; – method instead of &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;new&lt;/span&gt; operator) very attractive and even unusual lack of if conditionals in Smalltalk requires some &lt;a href="http://en.wikipedia.org/wiki/Smalltalk#Control_structures"&gt;attention&lt;/a&gt;.&lt;br /&gt;&lt;h4&gt;Enums&lt;/h4&gt;Scala doesn't have built-in support for enums. Enumerations in Java are known to have several fancy features which other languages envy like type safety and ability to add methods to each enum. There are at least two ways to emulate enums in Scala:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;object Status extends Enumeration {&lt;br /&gt;   type Status = Value&lt;br /&gt;&lt;br /&gt;   val Pending = Value("Pending...")&lt;br /&gt;   val Accepted = Value("Accepted :-)")&lt;br /&gt;   val Rejected = Value("Rejected :-(")&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;assume(Status.Pending.toString == "Pending...")&lt;br /&gt;assume(Status.withName("Rejected :-(") == Status.Rejected)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Or if you don't care about textual enum representation:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;object Status extends Enumeration {&lt;br /&gt;   type Status = Value&lt;br /&gt;&lt;br /&gt;   val Pending, Accepted, Rejected = Value&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;However the second and the most comprehensive way to emulate enums is to use case classes. Side note: &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;name&lt;/span&gt; is actually an abstract method defined in base class. When you declare a method without defining the method body it is implicitly assumed to be &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;abstract&lt;/span&gt; – no need to mark the obvious with extra keywords:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;sealed abstract class Status(val code: Int) {&lt;br /&gt; def name: String&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case object Pending extends Status(0) {&lt;br /&gt; override def name = "?"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case object Accepted extends Status(1) {&lt;br /&gt; override def name = "+"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case object Rejected extends Status(-1) {&lt;br /&gt; override def name = "-"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//...&lt;br /&gt;&lt;br /&gt;val s: Status = Accepted&lt;br /&gt;&lt;br /&gt;assume(s.name == "+")&lt;br /&gt;assume(s.code == 1)&lt;br /&gt;&lt;br /&gt;s match {&lt;br /&gt;    case Pending =&amp;gt;&lt;br /&gt;    case Accepted =&amp;gt;&lt;br /&gt;    case Rejected =&amp;gt;  //comment this line, you'll see compiler warning&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;This approach, although has nothing to do with enums per se, has many advantages. The biggest one is that the compiler will warn you when performing non exhaustive pattern matching – think: switch over an enum in Java without explicitly referencing each and every value or &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;default&lt;/span&gt; block.&lt;br /&gt;&lt;h4&gt;Static methods/fields&lt;/h4&gt;Scala doesn't have a notion of &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;static&lt;/span&gt; fields and methods. Instead it has a feature named &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;object&lt;/span&gt;s as opposed to &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;class&lt;/span&gt;es. When you define a class using &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;object&lt;/span&gt; keyword, Scala runtime will eagerly create one instance of this class and make it available under class name. This is essentially a &lt;i&gt;singleton&lt;/i&gt; pattern built into the language but the most important is the mindset shift introduced by this approach. Instead of a bunch of static functions artificially gathered together inside a class (which is only a &lt;i&gt;de facto&lt;/i&gt; namespace in this case) you have a singleton with &lt;i&gt;true&lt;/i&gt; methods:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;sealed abstract class Status&lt;br /&gt;case object Pending extends Status&lt;br /&gt;case object Accepted extends Status&lt;br /&gt;case object Rejected extends Status&lt;br /&gt;&lt;br /&gt;case class Application(status: Status, name: String)&lt;br /&gt;&lt;br /&gt;object Util {&lt;br /&gt;&lt;br /&gt;    def groupByStatus(applications: Seq[Application]) = applications groupBy {_.status}&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Here is how the syntax works (and nice &lt;a href="http://www.scalatest.org/scaladoc-1.6.1/#org.scalatest.matchers.ShouldMatchers"&gt;ScalaTest&lt;/a&gt; DSL example):&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;@RunWith(classOf[JUnitRunner])&lt;br /&gt;class UtilTest extends FunSuite with ShouldMatchers {&lt;br /&gt;&lt;br /&gt;   type ? = this.type&lt;br /&gt;&lt;br /&gt;   test("should group applications by status") {&lt;br /&gt;      val applications = List(&lt;br /&gt;         Application(Pending, "Lorem"),&lt;br /&gt;         Application(Accepted, "ipsum"),&lt;br /&gt;         Application(Accepted, "dolor")&lt;br /&gt;      )&lt;br /&gt;&lt;br /&gt;      val appsPerStatus = Util.groupByStatus(applications)&lt;br /&gt;&lt;br /&gt;      appsPerStatus should have size (2)&lt;br /&gt;      appsPerStatus(Pending) should (&lt;br /&gt;            have size (1) and&lt;br /&gt;            contain (Application(Pending, "Lorem"))&lt;br /&gt;      )&lt;br /&gt;      appsPerStatus(Accepted) should (&lt;br /&gt;            have size (2) and&lt;br /&gt;            contain (Application(Accepted, "ipsum")) and&lt;br /&gt;            contain (Application(Accepted, "dolor"))&lt;br /&gt;      )&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;volatile/transient/native and serialVersionUID are gone&lt;/h4&gt;The language designers decided to convert the first three keywords into annotations. Both approaches have pros and cons, hard to find the clear winner. However turning  &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;serialVersionUID&lt;/span&gt; into a class level annotation is a pretty good choice. I know this field existed long before annotations were introduced to the Java language, so we shouldn't blame it. But I always hated when in statically typed languages some names/fields have special meaning not reflected anywhere except the language specification itself (&lt;i&gt;magic numbers?&lt;/i&gt;) Unfortunately there are examples of this unpleasant behaviour in Scala as well, namely special treatment of &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;apply()&lt;/span&gt; method and methods ending with colon. Too bad.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Pre/post-increment&lt;/h4&gt;You cannot do &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;i++&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;++i&lt;/span&gt; in Scala. Period. You need a bit more verbose &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;i += 1&lt;/span&gt; – and to make matters worse this expression return &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;Unit&lt;/span&gt; (think: &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;void&lt;/span&gt;). How can we deal with this noticeable feature missing? Turns out that very often this type of constructs are imperative style legacy and they can easily be avoided by using more functional and pure constructs. Take the following problem as an example:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;You have two same sized arrays: one with &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;names&lt;/span&gt; and a second one with &lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;ages&lt;/span&gt;. Now you want to display each name with a corresponding age – somehow iterating over both arrays in parallel. In Java this is surprisingly tough to implement cleanly:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;String[] names = new String[]{"Alice", "Bobby", "Eve", "Jane"};&lt;br /&gt;Integer[] ages = new Integer[]{27, 31, 29, 25};&lt;br /&gt;&lt;br /&gt;int curAgeIdx = 0;&lt;br /&gt;for (String name : names) {&lt;br /&gt;    System.out.println(name + ": " + ages[curAgeIdx]);&lt;br /&gt;    ++curAgeIdx;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//or:&lt;br /&gt;&lt;br /&gt;for(int idx = 0; idx &amp;lt; names.length; ++idx)&lt;br /&gt;    System.out.println(names[idx] + ": " + ages[idx]);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In Scala maybe it is shorter, but very mysterious at first:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;var names = Array("Alice", "Bobby", "Eve", "Jane")&lt;br /&gt;var ages = Array(27, 31, 29, 25)&lt;br /&gt;&lt;br /&gt;names zip ages foreach {p =&amp;gt; println(p._1 + ": " + p._2)}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New',Courier,monospace;"&gt;zip&lt;/span&gt;? I encourage you play a bit with this example. If you don't feel like starting up the whole IDE, try it with Scala REPL:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: bash"&gt;&lt;br /&gt;$ scala&lt;br /&gt;scala&amp;gt; Array("one", "two", "three") zip Array(1, 2, 31)   &lt;br /&gt;res1: Array[(java.lang.String, Int)] = Array((one,1), (two,2), (three,31))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Look carefully, do you see the result array containing pairs of corresponding elements from the first and the second arrays “&lt;i&gt;zipped&lt;/i&gt;” together? One simple experiment and now suddenly it should be clear and much more readable than ordinary imperative solution.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Scala inventors looked very thoroughly on Java language and they didn't just add syntactic sugar (like function literals or implicit conversions). They discovered plenty of inconsistencies and annoyances in Java, getting rid of them and providing more concise and deliberate replacements. Despite higher level constructs like primitive and array objects, under the hood the same fast and straightforward bytecode is generated.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-3527227597997947083?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/3527227597997947083/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/08/what-features-of-java-have-been-dropped.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/3527227597997947083'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/3527227597997947083'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/08/what-features-of-java-have-been-dropped.html' title='What features of Java have been dropped in Scala?'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-1002127732823020463</id><published>2011-07-21T21:15:00.002+02:00</published><updated>2011-11-17T19:23:18.307+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ejb'/><category scheme='http://www.blogger.com/atom/ns#' term='books'/><category scheme='http://www.blogger.com/atom/ns#' term='review'/><title type='text'>EJB 3.1 Cookbook by Richard Reese review</title><content type='html'>&lt;div&gt;Recently I received a copy of EJB 3.1 Cookbook (courtesy to &lt;a href="http://www.packtpub.com/"&gt;Packt Publishing&lt;/a&gt;) with a kind request to prepare a review. And since I have just got my new &lt;a href="http://www.amazon.com/?tag=javaandneighb-20&amp;amp;camp=0&amp;amp;creative=0&amp;amp;linkCode=as4"&gt;Kindle reader&lt;/a&gt;, this was a great opportunity to test them together.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-dx9wGAdz8wU/Tih2oRruzsI/AAAAAAAAAfM/O4PSHdelZQg/s1600/51DWCsuRDVL._SS500_.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="320" src="http://1.bp.blogspot.com/-dx9wGAdz8wU/Tih2oRruzsI/AAAAAAAAAfM/O4PSHdelZQg/s320/51DWCsuRDVL._SS500_.jpg" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://www.packtpub.com/ejb-3-1-cookbook/book"&gt;&lt;/a&gt;&lt;br /&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;a href="http://www.packtpub.com/ejb-3-1-cookbook/book"&gt;EJB3.1 Cookbook&lt;/a&gt; by Richard Reese aims to provide “&lt;i&gt;a collectionof simple but incredibly effective recipes&lt;/i&gt;” – quoting thesubtitle. The book covers expected part of the EJB stack: session andmessage-driven beans, JPA, security, interceptors, timer service andweb services. Contents are&lt;/div&gt;organized around so called &lt;i&gt;recipes&lt;/i&gt; – short (no more than three pages long) micro-chapters focused on one specific issue. This is the most advantageous feature of this publication: all recipes all self-contained most of the time, so one can jump between them and apply the most suitable in given scenario. This makes the book suitable for both the beginners, which should read it from cover to cover and slightly more experienced developers. However the latter ones will probably  prefer more comprehensive sources and skip significant parts of the book.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Although I found the book structure very convenient, contents (both granularity and volume) are highly subjective and controversial. On the one hand the author devotes five recipes to describe separately each JMS message type (string, byte, stream, map and object) – each one is almost identical. Whilst he could only list different types, he fills half of the JMS chapter this way (&lt;i&gt;sic!&lt;/i&gt;) On the other hand, there is only one recipe explaining new JPA 2.0 Criteria API – to make matters worse, only using weakly typed queries. Probably one of the most important new features in EJB 3.1 stack has been covered on two pages. And this API is not particularly easy to grasp. To depict you the scale – the art of adding Bean Validation annotations (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@NotNull&lt;/span&gt; etc.) on fields required ten pages and eight recipes... Where a half-page bullet-list would suffice.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The last chapter – &lt;i&gt;EJB Techniques &lt;/i&gt;– is very intriguing. Lots of valuable and accurate tips have been given, like the difference between &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Date&lt;/span&gt; and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Calendar&lt;/span&gt;, logging and dealing with exceptions, effective &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;String&lt;/span&gt; manipulations. Despite appearances, this is not the basic Java knowledge and many experienced programmers still don't know that &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;SimpleDateFormat&lt;/span&gt; is not thread-safe and that &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Date&lt;/span&gt; class does not store time zone. I am really happy that this kind of knowledge found its way in the book. Unfortunately – in the wrong one. That being said, there are more appropriate books, not focused on EJB or even Java EE. Here it just looks like putting anything useful to reach dozen chapters in total.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;There are however bright sides as well. I particularly enjoyed &lt;i&gt;Transaction Processing&lt;/i&gt; and &lt;i&gt;Interceptors&lt;/i&gt; chapters. In the former one the author briefly but succinctly explains different transaction propagation and error handling behaviours, very important topics. Table on page 210 captures the essence of transaction demarcation in few simple rules, brilliant in its simplicity. In the interceptors chapter the recipes are focused on typical cross-cutting concerns, forming handy starting point. Also pretty informative.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;When in comes to code examples and use-cases, they were generally interesting and well thought. Nevertheless, I am still awfully confused after reading a recipe on @Singleton: “&lt;i&gt;We will assume that our game will never have more than one player so a singleton is an appropriate choice &lt;/i&gt;” - says the author to justify the usage of singleton to store user attributes. Yes, I think we are all using Enterprise Java Beans and Application Servers to develop systems that would never have more than one user at a time... (Hint: statefull session bean) The same thing with the usage of &lt;i&gt;&lt;a href="http://en.wikipedia.org/wiki/Facade_pattern"&gt;Facade&lt;/a&gt;&lt;/i&gt; pattern throughout the book. First the author quotes the exact definition of this design pattern and then names a class wrapping &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;EntityManager&lt;/span&gt; and providing convenient, strongly typed &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;create()&lt;/span&gt;, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;remove()&lt;/span&gt;, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;findAll()&lt;/span&gt;, etc. - &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;PatientFacade&lt;/span&gt;. No, this class is not hiding the complexity of &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Patient&lt;/span&gt; entity, and all programmers all over the world would call this abstraction a &lt;i&gt;Repository&lt;/i&gt; or &lt;i&gt;DAO&lt;/i&gt;. Not here.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;By the way in the same recipe one-to-many relationship is introduced between a patient and medication, where clearly many-to-many is required. Curiously enough, in the next recipe &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;DISTINCT&lt;/span&gt; SQL statement is used to filter out duplications that have appeared due to denormalization. Well, if the database was designed properly, there wouldn't be any duplicates on the first place... After all these misleading and sometimes harmful advices, typos and errors in source codes (&lt;i style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;ClassNoDefException&lt;/i&gt;? - never heard of it...) are not that irritating.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In conclusion, despite all the deficiencies and inconsistencies, I mostly enjoyed reading this book. Once again I will highlight the very elegant chapter-recipe structure and the fixed layout inside each recipe. I believe it is suitable for people that suddenly inherited an EJB application and need an immediate help and suggestions. However on the long run, they should invest in more comprehensive publication. Few years back I managed to pass SCBCD exam (EJB 3.0 by that time) after reading &lt;a href="http://www.amazon.com/gp/product/059600978X/ref=as_li_ss_tl?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=217145&amp;amp;creative=399377&amp;amp;creativeASIN=059600978X"&gt;Enterprise JavaBeans 3.0&lt;/a&gt;. With the book in question it would be virtually impossible. If you need a quick and dirty, yet entertaining source of ready solutions, go ahead. Otherwise, definitely look for something broader and less verbose.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-1002127732823020463?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/1002127732823020463/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/07/ejb-31-cookbook-by-richard-reese-review.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/1002127732823020463'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/1002127732823020463'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/07/ejb-31-cookbook-by-richard-reese-review.html' title='EJB 3.1 Cookbook by Richard Reese review'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/-dx9wGAdz8wU/Tih2oRruzsI/AAAAAAAAAfM/O4PSHdelZQg/s72-c/51DWCsuRDVL._SS500_.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-981368694888269595</id><published>2011-07-03T19:15:00.001+02:00</published><updated>2011-11-17T19:22:27.232+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='rest'/><category scheme='http://www.blogger.com/atom/ns#' term='spring mvc'/><category scheme='http://www.blogger.com/atom/ns#' term='jquery'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='jqgrid'/><title type='text'>Poor man's CRUD: jqGrid, REST, AJAX, and Spring MVC in one house</title><content type='html'>&lt;div&gt;More than two years back I wrote an article on how two implement elegant CRUD in &lt;a href="http://struts.apache.org/2.2.1.1/"&gt;Struts2&lt;/a&gt;. Actually I had to devote two articles on that subject because the topic was so broad. Today I have taken much more lightweight and modern approach with a set of popular and well established frameworks and libraries. Namely, we will use &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html"&gt;Spring MVC&lt;/a&gt; on the back-end to provide REST interface to our resources, fabulous &lt;a href="http://www.trirand.com/blog"&gt;jqGrid&lt;/a&gt; plugin for &lt;a href="http://jquery.com/"&gt;jQuery&lt;/a&gt; to render tabular grids (and much more!) and we will wire up everything with a pinch of JavaScript and AJAX.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Back-end is actually the least interesting part of this showcase, it could have been implemented using any server-side technology capable of handling RESTful requests, probably JAX-RS should now be considered standard in this field. I have chosen Spring MVC without any good reason, but it's also not a bad choice for this task. We will expose CRUD operations over REST interface; the list of &lt;a href="http://en.wikipedia.org/wiki/List_of_best-selling_books"&gt;best selling books in history&lt;/a&gt; will be our domain model (can you guess who is on the podium?)&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Controller&lt;br /&gt;@RequestMapping(value = "/book")&lt;br /&gt;public class BookController {&lt;br /&gt;&lt;br /&gt;  private final Map&amp;lt;Integer, Book&amp;gt; books = new ConcurrentSkipListMap&amp;lt;Integer, Book&amp;gt;();&lt;br /&gt;&lt;br /&gt;  @RequestMapping(value = "/{id}", method = GET)&lt;br /&gt;  public @ResponseBody Book read(@PathVariable("id") int id) {&lt;br /&gt;    return books.get(id);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @RequestMapping(method = GET)&lt;br /&gt;  public @ResponseBody Page&amp;lt;Book&amp;gt; listBooks(&lt;br /&gt;      @RequestParam(value = "page", required = false, defaultValue = "1") int page,&lt;br /&gt;      @RequestParam(value = "max", required = false, defaultValue = "20") int max) {&lt;br /&gt;    final ArrayList&amp;lt;Book&amp;gt; booksList = new ArrayList&amp;lt;Book&amp;gt;(books.values());&lt;br /&gt;    final int startIdx = (page - 1) * max;&lt;br /&gt;    final int endIdx = Math.min(startIdx + max, books.size());&lt;br /&gt;    return new Page&amp;lt;Book&amp;gt;(booksList.subList(startIdx, endIdx), page, max, books.size());&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Few things need explanation. First of all &lt;b&gt;for the purposes of this simple showcase&lt;/b&gt; I haven't used any database, all the books are stored in an in-memory map inside a controller. Forgive me. Second issue is more subtle. Since there seems to be &lt;a href="http://stackoverflow.com/questions/924472"&gt;no agreement&lt;/a&gt; on how to handle paging with RESTful web services, I used simple query parameters. You may find it ugly, but I find abusing &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Accept-Ranges&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Range&lt;/span&gt; headers together with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;206&lt;/span&gt; HTTP response code even uglier.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Last notable detail is the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Page&amp;lt;Book&amp;gt;&lt;/span&gt; wrapper class:&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@XmlRootElement&lt;br /&gt;public class Page&amp;lt;T&amp;gt; {&lt;br /&gt;&lt;br /&gt;  private List&amp;lt;T&amp;gt; rows;&lt;br /&gt;&lt;br /&gt;  private int page;&lt;br /&gt;  private int max;&lt;br /&gt;  private int total;&lt;br /&gt;&lt;br /&gt;  //...&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I could have return raw list (or, more precisely, requested part of the list), but I also need a way to provide convenient metadata like total number of records to the view layer, not to mention some difficulties while marshalling/unmarshalling raw lists.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;We are now ready to start our application and do a little test drive with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;curl&lt;/span&gt;:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;!-- $ curl -v "http://localhost:8080/books/rest/book?page=1&amp;max=2" --&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&amp;gt;&lt;br /&gt;&amp;lt;page&amp;gt;&lt;br /&gt;  &amp;lt;total&amp;gt;43&amp;lt;/total&amp;gt;&lt;br /&gt;  &amp;lt;page&amp;gt;1&amp;lt;/page&amp;gt;&lt;br /&gt;  &amp;lt;max&amp;gt;3&amp;lt;/max&amp;gt;&lt;br /&gt;  &amp;lt;rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book"&amp;gt;&lt;br /&gt;    &amp;lt;author&amp;gt;Charles Dickens&amp;lt;/author&amp;gt;&lt;br /&gt;    &amp;lt;available&amp;gt;true&amp;lt;/available&amp;gt;&lt;br /&gt;    &amp;lt;cover&amp;gt;PAPERBACK&amp;lt;/cover&amp;gt;&lt;br /&gt;    &amp;lt;id&amp;gt;1&amp;lt;/id&amp;gt;&lt;br /&gt;    &amp;lt;publishedYear&amp;gt;1859&amp;lt;/publishedYear&amp;gt;&lt;br /&gt;    &amp;lt;title&amp;gt;A Tale of Two Cities&amp;lt;/title&amp;gt;&lt;br /&gt;  &amp;lt;/rows&amp;gt;&lt;br /&gt;  &amp;lt;rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book"&amp;gt;&lt;br /&gt;    &amp;lt;author&amp;gt;J. R. R. Tolkien&amp;lt;/author&amp;gt;&lt;br /&gt;    &amp;lt;available&amp;gt;true&amp;lt;/available&amp;gt;&lt;br /&gt;    &amp;lt;cover&amp;gt;HARDCOVER&amp;lt;/cover&amp;gt;&lt;br /&gt;    &amp;lt;id&amp;gt;2&amp;lt;/id&amp;gt;&lt;br /&gt;    &amp;lt;publishedYear&amp;gt;1954&amp;lt;/publishedYear&amp;gt;&lt;br /&gt;    &amp;lt;title&amp;gt;The Lord of the Rings&amp;lt;/title&amp;gt;&lt;br /&gt;  &amp;lt;/rows&amp;gt;&lt;br /&gt;  &amp;lt;rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book"&amp;gt;&lt;br /&gt;    &amp;lt;author&amp;gt;J. R. R. Tolkien&amp;lt;/author&amp;gt;&lt;br /&gt;    &amp;lt;available&amp;gt;true&amp;lt;/available&amp;gt;&lt;br /&gt;    &amp;lt;cover&amp;gt;PAPERBACK&amp;lt;/cover&amp;gt;&lt;br /&gt;    &amp;lt;id&amp;gt;3&amp;lt;/id&amp;gt;&lt;br /&gt;    &amp;lt;publishedYear&amp;gt;1937&amp;lt;/publishedYear&amp;gt;&lt;br /&gt;    &amp;lt;title&amp;gt;The Hobbit&amp;lt;/title&amp;gt;&lt;br /&gt;  &amp;lt;/rows&amp;gt;&lt;br /&gt;&amp;lt;/page&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Response type defaults to XML if none is specified but if we add &lt;a href="http://jackson.codehaus.org/"&gt;Jackson&lt;/a&gt; library to the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;CLASSPATH&lt;/span&gt;, Spring will pick it up and enable us to use JSON as well:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;// $ curl -v -H "Accept: application/json" "http://localhost:8080/books/rest/book?page=1&amp;max=3"&lt;br /&gt;&lt;br /&gt;{&lt;br /&gt;    "total":43,&lt;br /&gt;    "max":3,&lt;br /&gt;    "page":1,&lt;br /&gt;    "rows":[&lt;br /&gt;        {&lt;br /&gt;            "id":1,&lt;br /&gt;            "available":true,&lt;br /&gt;            "author":"Charles Dickens",&lt;br /&gt;            "title":"A Tale of Two Cities",&lt;br /&gt;            "publishedYear":1859,&lt;br /&gt;            "cover":"PAPERBACK",&lt;br /&gt;            "comments":null&lt;br /&gt;        },&lt;br /&gt;        {&lt;br /&gt;            "id":2,&lt;br /&gt;            "available":true,&lt;br /&gt;            "author":"J. R. R. Tolkien",&lt;br /&gt;            "title":"The Lord of the Rings",&lt;br /&gt;            "publishedYear":1954,&lt;br /&gt;            "cover":"HARDCOVER",&lt;br /&gt;            "comments":null&lt;br /&gt;        },&lt;br /&gt;        {&lt;br /&gt;            "id":3,&lt;br /&gt;            "available":true,&lt;br /&gt;            "author":"J. R. R. Tolkien",&lt;br /&gt;            "title":"The Hobbit",&lt;br /&gt;            "publishedYear":1937,&lt;br /&gt;            "cover":"PAPERBACK",&lt;br /&gt;            "comments":null&lt;br /&gt;        }&lt;br /&gt;    ]&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Nice, now we can work on the front-end, hopefully not making our hands too dirty. With regards to HTML markup, this is all we need, seriously:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: html"&gt;&lt;br /&gt;&amp;lt;table id="grid"&amp;gt;&amp;lt;/table&amp;gt;&lt;br /&gt;&amp;lt;div id="pager"&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Keep in mind that we will implement all CRUD operations, but still, this is all we need. No more HTML. Rest of the magic happens thanks to marvellous jqGrid library. Here is a basic setup:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;$("#grid")&lt;br /&gt;    .jqGrid({&lt;br /&gt;      url:'rest/book',&lt;br /&gt;      colModel:[&lt;br /&gt;        {name:'id', label: 'ID', formatter:'integer', width: 40},&lt;br /&gt;        {name:'title', label: 'Title', width: 300},&lt;br /&gt;        {name:'author', label: 'Author', width: 200},&lt;br /&gt;        {name:'publishedYear', label: 'Published year', width: 80, align: 'center'},&lt;br /&gt;        {name:'available', label: 'Available', formatter: 'checkbox', width: 46, align: 'center'}&lt;br /&gt;      ],&lt;br /&gt;      caption: "Books",&lt;br /&gt;      pager : '#pager',&lt;br /&gt;      height: 'auto'&lt;br /&gt;    })&lt;br /&gt;    .navGrid('#pager', {edit:false,add:false,del:false, search: false});&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Technically, this is all we need. URL to fetch the data, pointing to our controller (jqGrid will perform all the AJAX magic for us) and the data model (you may recognize book fields and their descriptions). However, since jqGrid is highly customizable, I applied few tweaks to make the grid look a bit better. Also I didn't like suggested names of metadata, for instance &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;total&lt;/span&gt;&amp;nbsp;field returned from the server is suppose to be the total number of pages, not records – highly counter-intuitive. Here are my tweaked options:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;$.extend($.jgrid.defaults, {&lt;br /&gt;  datatype: 'json',&lt;br /&gt;  jsonReader : {&lt;br /&gt;    repeatitems:false,&lt;br /&gt;    total: function(result) {&lt;br /&gt;      //Total number of pages&lt;br /&gt;      return Math.ceil(result.total / result.max);&lt;br /&gt;    },&lt;br /&gt;    records: function(result) {&lt;br /&gt;      //Total number of records&lt;br /&gt;      return result.total;&lt;br /&gt;    }&lt;br /&gt;  },&lt;br /&gt;  prmNames: {rows: 'max', search: null},&lt;br /&gt;  height: 'auto',&lt;br /&gt;  viewrecords: true,&lt;br /&gt;  rowList: [10, 20, 50, 100],&lt;br /&gt;  altRows: true,&lt;br /&gt;  loadError: function(xhr, status, error) {&lt;br /&gt;    alert(error);&lt;br /&gt;  }&lt;br /&gt;  });&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Eager to see the results? Here is a browser screenshot:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-S_jCbvgAito/ThCgthzLOlI/AAAAAAAAAcY/z2FWNRGmdSw/s1600/popup.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="258" src="http://1.bp.blogspot.com/-S_jCbvgAito/ThCgthzLOlI/AAAAAAAAAcY/z2FWNRGmdSw/s320/popup.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Good looking, with customizable paging, lightweight refreshing... And our hands are still relatively clean! But I promised CRUD... If you were careful, you have probably noticed few &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;navGrid&lt;/span&gt; attributes, dying to be turned on:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;var URL = 'rest/book';&lt;br /&gt;var options = {&lt;br /&gt;  url: URL,&lt;br /&gt;  editurl: URL,&lt;br /&gt;  colModel:[&lt;br /&gt;    {&lt;br /&gt;      name:'id', label: 'ID',&lt;br /&gt;      formatter:'integer',&lt;br /&gt;      width: 40,&lt;br /&gt;      editable: true,&lt;br /&gt;      editoptions: {disabled: true, size:5}&lt;br /&gt;    },&lt;br /&gt;    {&lt;br /&gt;      name:'title',&lt;br /&gt;      label: 'Title',&lt;br /&gt;      width: 300,&lt;br /&gt;      editable: true,&lt;br /&gt;      editrules: {required: true}&lt;br /&gt;    },&lt;br /&gt;    {&lt;br /&gt;      name:'author',&lt;br /&gt;      label: 'Author',&lt;br /&gt;      width: 200,&lt;br /&gt;      editable: true,&lt;br /&gt;      editrules: {required: true}&lt;br /&gt;    },&lt;br /&gt;    {&lt;br /&gt;      name:'cover',&lt;br /&gt;      label: 'Cover',&lt;br /&gt;      hidden: true,&lt;br /&gt;      editable: true,&lt;br /&gt;      edittype: 'select',&lt;br /&gt;      editrules: {edithidden:true},&lt;br /&gt;      editoptions: {&lt;br /&gt;        value: {'PAPERBACK': 'paperback', 'HARDCOVER': 'hardcover', 'DUST_JACKET': 'dust jacket'}&lt;br /&gt;      }&lt;br /&gt;    },&lt;br /&gt;    {&lt;br /&gt;      name:'publishedYear',&lt;br /&gt;      label: 'Published year',&lt;br /&gt;      width: 80,&lt;br /&gt;      align: 'center',&lt;br /&gt;      editable: true,&lt;br /&gt;      editrules: {required: true, integer: true},&lt;br /&gt;      editoptions: {size:5, maxlength: 4}&lt;br /&gt;    },&lt;br /&gt;    {&lt;br /&gt;      name:'available',&lt;br /&gt;      label: 'Available',&lt;br /&gt;      formatter: 'checkbox',&lt;br /&gt;      width: 46,&lt;br /&gt;      align: 'center',&lt;br /&gt;      editable: true,&lt;br /&gt;      edittype: 'checkbox',&lt;br /&gt;      editoptions: {value:"true:false"}&lt;br /&gt;    },&lt;br /&gt;    {&lt;br /&gt;      name:'comments',&lt;br /&gt;      label: 'Comments',&lt;br /&gt;      hidden: true,&lt;br /&gt;      editable: true,&lt;br /&gt;      edittype: 'textarea',&lt;br /&gt;      editrules: {edithidden:true}&lt;br /&gt;    }&lt;br /&gt;  ],&lt;br /&gt;  caption: "Books",&lt;br /&gt;  pager : '#pager',&lt;br /&gt;  height: 'auto'&lt;br /&gt;};&lt;br /&gt;$("#grid")&lt;br /&gt;    .jqGrid(options)&lt;br /&gt;    .navGrid('#pager', {edit:true,add:true,del:true, search: false});&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The configuration is getting dangerously verbose, but there's nothing complicated out there – for each field we have added few additional attributes controlling how this field should be treated in edit mode. This includes what type of HTML input should represent it, validation rules, visibility, etc. But honestly, I believe it was worth it:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-E5f2LP5ZtQs/ThCg3iqQJcI/AAAAAAAAAcc/aKqjUPF6h8w/s1600/edit_validation_normal.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="258" src="http://2.bp.blogspot.com/-E5f2LP5ZtQs/ThCg3iqQJcI/AAAAAAAAAcc/aKqjUPF6h8w/s320/edit_validation_normal.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This nicely looking edit window has been fully generated by jqGrid based on our edit options mentioned above, including validation logic. We can make some of the fields visible in the grid hidden/inactive in edit dialog (like &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;id&lt;/span&gt;) and vice-versa (&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;cover&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;comments&lt;/span&gt; are not present in the grid, however you can modify them). Also notice few new icons visible in bottom-left corner of the grid. Adding and deleting is possible as well – and we haven't written a single line of HTML/JSP/JavaScript (excluding jqGrid configuration object).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-GrLAA3ArM44/ThChOrlOkOI/AAAAAAAAAcg/oVcWcydyOoA/s1600/del.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="258" src="http://2.bp.blogspot.com/-GrLAA3ArM44/ThChOrlOkOI/AAAAAAAAAcg/oVcWcydyOoA/s320/del.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Of course we all know that &lt;a href="http://www.codinghorror.com/blog/2005/08/the-user-interface-is-the-application.html"&gt;&lt;i&gt;The User Interface Is The Application&lt;/i&gt;&lt;/a&gt;, and our interface is pretty good, however sometimes we really want a beautiful &lt;b&gt;and&lt;/b&gt; working application. And currently the latter requirement is our Achilles' heel. Not because the back-end isn't ready, this is rather trivial:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Controller&lt;br /&gt;@RequestMapping(value = "/book")&lt;br /&gt;public class BookController {&lt;br /&gt;&lt;br /&gt;  private final Map&amp;lt;Integer, Book&amp;gt; books = new ConcurrentSkipListMap&amp;lt;Integer, Book&amp;gt;();&lt;br /&gt;&lt;br /&gt;  @RequestMapping(value = "/{id}", method = GET)&lt;br /&gt;  public @ResponseBody Book read(@PathVariable("id") int id) {&lt;br /&gt;    //...&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @RequestMapping(method = GET)&lt;br /&gt;  public&lt;br /&gt;  @ResponseBody&lt;br /&gt;  Page&amp;lt;Book&amp;gt; listBooks(&lt;br /&gt;      @RequestParam(value = "page", required = false, defaultValue = "1") int page,&lt;br /&gt;      @RequestParam(value = "max", required = false, defaultValue = "20") int max) {&lt;br /&gt;    //...&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @RequestMapping(value = "/{id}", method = PUT)&lt;br /&gt;  @ResponseStatus(HttpStatus.NO_CONTENT)&lt;br /&gt;  public void updateBook(@PathVariable("id") int id, @RequestBody Book book) {&lt;br /&gt;    //...&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @RequestMapping(method = POST)&lt;br /&gt;  public ResponseEntity&amp;lt;String&amp;gt; createBook(HttpServletRequest request, @RequestBody Book book) {&lt;br /&gt;    //...&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @RequestMapping(value = "/{id}", method = DELETE)&lt;br /&gt;  @ResponseStatus(HttpStatus.NO_CONTENT)&lt;br /&gt;  public void deleteBook(@PathVariable("id") int id) {&lt;br /&gt;    //...&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Server-side is ready, but when it comes to data manipulation on the client-side, jqGrid reveals its dirty secret – all the traffic to the server is sent using POST like this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: plain"&gt;&lt;br /&gt;Content-Type: application/x-www-form-urlencoded in the following format:&lt;br /&gt;&lt;br /&gt;id=&amp;title=And+Then+There+Were+None&amp;author=Agatha+Christie&amp;cover=PAPERBACK&amp;publishedYear=1939&amp;available=true&amp;comments=&amp;oper=add&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The last attribute (&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;oper=add&lt;/span&gt;) is crucial. Not really idiomatic REST, don't you think? If we could only use POST/PUT/DELETE appropriately and serialize data using JSON or XML... Modifying my server so that it is compliant with some JavaScript library (no matter how cool it is), seems like a last resort. Thankfully, everything can be &lt;a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs"&gt;customized&lt;/a&gt; with a moderate amount of work.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;$.extend($.jgrid.edit, {&lt;br /&gt;      ajaxEditOptions: { contentType: "application/json" },&lt;br /&gt;      mtype: 'PUT',&lt;br /&gt;      serializeEditData: function(data) {&lt;br /&gt;        delete data.oper;&lt;br /&gt;        return JSON.stringify(data);&lt;br /&gt;      }&lt;br /&gt;    });&lt;br /&gt;$.extend($.jgrid.del, {&lt;br /&gt;      mtype: 'DELETE',&lt;br /&gt;      serializeDelData: function() {&lt;br /&gt;        return "";&lt;br /&gt;      }&lt;br /&gt;    });&lt;br /&gt;&lt;br /&gt;var URL = 'rest/book';&lt;br /&gt;var options = {&lt;br /&gt;  url: URL,&lt;br /&gt;  //...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var editOptions = {&lt;br /&gt;  onclickSubmit: function(params, postdata) {&lt;br /&gt;    params.url = URL + '/' + postdata.id;&lt;br /&gt;  }&lt;br /&gt;};&lt;br /&gt;var addOptions = {mtype: "POST"};&lt;br /&gt;var delOptions = {&lt;br /&gt;  onclickSubmit: function(params, postdata) {&lt;br /&gt;    params.url = URL + '/' + postdata;&lt;br /&gt;  }&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;$("#grid")&lt;br /&gt;    .jqGrid(options)&lt;br /&gt;    .navGrid('#pager',&lt;br /&gt;    {}, //options&lt;br /&gt;    editOptions,&lt;br /&gt;    addOptions,&lt;br /&gt;    delOptions,&lt;br /&gt;    {} // search options&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;We have customized HTTP method per operation, serialization is handled using JSON and finally URLs for edit and delete operations are now suffixed with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;/&lt;i&gt;record_id&lt;/i&gt;&lt;/span&gt;. Now it not only looks, it works! Look at the browser interaction with the server (note different HTTP methods and URLs):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-WdpIbN8QiJ8/ThChU-IlDQI/AAAAAAAAAck/k6A7fcL27_0/s1600/http.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="229" src="http://4.bp.blogspot.com/-WdpIbN8QiJ8/ThChU-IlDQI/AAAAAAAAAck/k6A7fcL27_0/s320/http.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here is an example of creating a new resource on browser side:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-zoFATrd62Gw/ThChbLCaiII/AAAAAAAAAco/DYbviVdqK-U/s1600/http_post.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="146" src="http://3.bp.blogspot.com/-zoFATrd62Gw/ThChbLCaiII/AAAAAAAAAco/DYbviVdqK-U/s320/http_post.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To follow REST principles as closely as possible I return &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;201 Created&lt;/span&gt; response code together with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Location&lt;/span&gt; header pointing to newly created resource. As you can see data is now being sent to the server in JSON format.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To summarize, such an approach has plenty of advantages:&lt;/div&gt;&lt;ul&gt;&lt;li&gt;&lt;div&gt;GUI is very responsive, page  appears instantly (it can be a static resource served from &lt;a href="http://en.wikipedia.org/wiki/Content_delivery_network"&gt;CDN&lt;/a&gt;),  while data is loaded asynchronously via AJAX in lightweight JSON  format&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div&gt;We get CRUD operations for free&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div&gt;REST interface for other systems  is also for free&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;Compare this with any web framework  out there. And did I mention about this little cherry on our  JavaScript frosting: jqGrid is fully compliant with &lt;a href="http://jqueryui.com/themeroller"&gt;jQuery  UI themes&lt;/a&gt; and also supports internationalization. Here is the  same application with changed theme and language:&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-XCqyIzZ-N18/ThChhbYPODI/AAAAAAAAAcs/qjUfZo6pW5I/s1600/edit_validation_green.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="258" src="http://4.bp.blogspot.com/-XCqyIzZ-N18/ThChhbYPODI/AAAAAAAAAcs/qjUfZo6pW5I/s320/edit_validation_green.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Full &lt;a href="https://github.com/nurkiewicz/books"&gt;source code&lt;/a&gt; is available on &lt;a href="https://github.com/nurkiewicz"&gt;my&lt;/a&gt; GitHub account. The application is self contained, just build it and deploy it to some servlet container.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-981368694888269595?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/981368694888269595/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/07/poor-mans-crud-jqgrid-rest-ajax-and.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/981368694888269595'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/981368694888269595'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/07/poor-mans-crud-jqgrid-rest-ajax-and.html' title='Poor man&apos;s CRUD: jqGrid, REST, AJAX, and Spring MVC in one house'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/-S_jCbvgAito/ThCgthzLOlI/AAAAAAAAAcY/z2FWNRGmdSw/s72-c/popup.png' height='72' width='72'/><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-7180071547096823487</id><published>2011-05-30T23:47:00.000+02:00</published><updated>2011-11-17T19:20:32.160+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='jmx'/><category scheme='http://www.blogger.com/atom/ns#' term='esb'/><category scheme='http://www.blogger.com/atom/ns#' term='apache cxf'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='web services'/><title type='text'>Enabling load balancing and failover in Apache CXF</title><content type='html'>&lt;div&gt;A while ago we've faced the requirement of load-balancing web services clients based on &lt;a href="http://cxf.apache.org/"&gt;Apache CXF&lt;/a&gt;. Also the clients should automatically fail-over when some of the servers are down. To make it even worse, the list of servers target addresses was to be obtained from external service and updated at runtime. Eventually we ended up with home-grown load-balancing micro-library (ESB/UDDI/WS-Addressing seemed like an interesting alternatives, but they were an overkill in our situation). If we only knew Apache CXF already supports all these features (almost) out of the box?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Don't blame us though, only &lt;a href="http://cxf.apache.org/docs/featureslist.html"&gt;reference&lt;/a&gt; to this feature points to a very poor &lt;a href="http://cxf.apache.org/clustering"&gt;documentation&lt;/a&gt; page (if you call 404 “poor”). If it's not in official documentation, I would expect to find it in &lt;a href="http://www.amazon.com/gp/product/1847195407/ref=as_li_ss_tl?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=217145&amp;amp;creative=399349&amp;amp;creativeASIN=1847195407"&gt;Apache CXF Web Service Development&lt;/a&gt; book – unfortunately, bad luck there as well. But hey, isn't exploring such features yourself even greater fun? This is the client configuration we are starting with:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;       xmlns:jaxws="http://cxf.apache.org/jaxws"&lt;br /&gt;       xmlns:clustering="http://cxf.apache.org/clustering"&lt;br /&gt;       xmlns:util="http://www.springframework.org/schema/util"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;jaxws:client id="testServiceClient"&lt;br /&gt;                  serviceClass="com.blogspot.nurkiewicz.cxfcluster.SimpleService"&lt;br /&gt;                  address="http://serverA/simple"&amp;gt;&lt;br /&gt;    &amp;lt;/jaxws:client&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;Endpoint interface is not important here, enough to know the &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;testServiceClient&lt;/span&gt; is being injected to some other services and load balancing and failover features shouldn't affect existing code. Note the service address is fixed and hard-coded (of course it can be externalized and read upon startup).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Surprisingly enabling failover alone is pretty simple, straightforward and self-explanatory (despite being XML):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;jaxws:client id="testServiceClient"&lt;br /&gt;              serviceClass="com.blogspot.nurkiewicz.cxfcluster.SimpleService"&lt;br /&gt;              address="http://serverA/simple"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;jaxws:features&amp;gt;&lt;br /&gt;        &amp;lt;clustering:failover&amp;gt;&lt;br /&gt;            &amp;lt;clustering:strategy&amp;gt;&lt;br /&gt;                &amp;lt;bean class="org.apache.cxf.clustering.RandomStrategy"&amp;gt;&lt;br /&gt;                    &amp;lt;property name="alternateAddresses"&amp;gt;&lt;br /&gt;                        &amp;lt;util:list&amp;gt;&lt;br /&gt;                            &amp;lt;value&amp;gt;http://serverB/simple&amp;lt;/value&amp;gt;&lt;br /&gt;                            &amp;lt;value&amp;gt;http://serverC/simple&amp;lt;/value&amp;gt;&lt;br /&gt;                            &amp;lt;value&amp;gt;http://serverD/simple&amp;lt;/value&amp;gt;&lt;br /&gt;                        &amp;lt;/util:list&amp;gt;&lt;br /&gt;                    &amp;lt;/property&amp;gt;&lt;br /&gt;                &amp;lt;/bean&amp;gt;&lt;br /&gt;            &amp;lt;/clustering:strategy&amp;gt;&lt;br /&gt;        &amp;lt;/clustering:failover&amp;gt;&lt;br /&gt;    &amp;lt;/jaxws:features&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/jaxws:client&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;serverA&lt;/span&gt; address is used as a primary endpoint, but when it fails all failover endpoints (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;serverB&lt;/span&gt;, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;serverC&lt;/span&gt; and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;serverD&lt;/span&gt;) are examined in random order. To play a bit with this configuration I advice you to turn on Apache CXF &lt;a href="http://cxf.apache.org/docs/configuration.html"&gt;logging&lt;/a&gt; of requests and responses:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt; &amp;lt;cxf:bus&amp;gt;&lt;br /&gt;    &amp;lt;cxf:features&amp;gt;&lt;br /&gt;        &amp;lt;cxf:logging/&amp;gt;&lt;br /&gt;    &amp;lt;/cxf:features&amp;gt;&lt;br /&gt;&amp;lt;/cxf:bus&amp;gt; &lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Once again (!) official documentation does not mention about very convenient configuration parameter &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;prettyLogging&lt;/span&gt; that can be applied to logging feature in order to make XML requests and responses being properly formatted (new lines and indentation) before being logged. I wouldn't recommend it for production setup, but during development and testing having SOAP messages formatted is invaluable:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;bean id="abstractLoggingInterceptor" abstract="true"&amp;gt;&lt;br /&gt;    &amp;lt;property name="prettyLogging" value="true"/&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&amp;lt;bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" parent="abstractLoggingInterceptor"/&amp;gt;&lt;br /&gt;&amp;lt;bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" parent="abstractLoggingInterceptor"/&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;cxf:bus&amp;gt;&lt;br /&gt;    &amp;lt;cxf:inInterceptors&amp;gt;&lt;br /&gt;        &amp;lt;ref bean="loggingInInterceptor"/&amp;gt;&lt;br /&gt;    &amp;lt;/cxf:inInterceptors&amp;gt;&lt;br /&gt;    &amp;lt;cxf:outInterceptors&amp;gt;&lt;br /&gt;        &amp;lt;ref bean="loggingOutInterceptor"/&amp;gt;&lt;br /&gt;    &amp;lt;/cxf:outInterceptors&amp;gt;&lt;br /&gt;    &amp;lt;cxf:outFaultInterceptors&amp;gt;&lt;br /&gt;        &amp;lt;ref bean="loggingOutInterceptor"/&amp;gt;&lt;br /&gt;    &amp;lt;/cxf:outFaultInterceptors&amp;gt;&lt;br /&gt;    &amp;lt;cxf:inFaultInterceptors&amp;gt;&lt;br /&gt;        &amp;lt;ref bean="loggingInInterceptor"/&amp;gt;&lt;br /&gt;    &amp;lt;/cxf:inFaultInterceptors&amp;gt;&lt;br /&gt;&amp;lt;/cxf:bus&amp;gt; &lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So our service nicely fails over to backup endpoints if primary one is not available. But we have four equivalent servers and we want our client to treat them equally hitting each one with similar probability (round robin? random?). Here is when load-balancing is entering the stage:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;jaxws:client id="testServiceClient" serviceClass="com.blogspot.nurkiewicz.cxfcluster.SimpleService"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;jaxws:features&amp;gt;&lt;br /&gt;        &amp;lt;clustering:loadDistributor&amp;gt;&lt;br /&gt;            &amp;lt;clustering:strategy&amp;gt;&lt;br /&gt;                &amp;lt;bean class="org.apache.cxf.clustering.SequentialStrategy"&amp;gt;&lt;br /&gt;                    &amp;lt;property name="alternateAddresses"&amp;gt;&lt;br /&gt;                        &amp;lt;util:list&amp;gt;&lt;br /&gt;                            &amp;lt;value&amp;gt;http://serverA/simple&amp;lt;/value&amp;gt;&lt;br /&gt;                            &amp;lt;value&amp;gt;http://serverB/simple&amp;lt;/value&amp;gt;&lt;br /&gt;                            &amp;lt;value&amp;gt;http://serverC/simple&amp;lt;/value&amp;gt;&lt;br /&gt;                            &amp;lt;value&amp;gt;http://serverD/simple&amp;lt;/value&amp;gt;&lt;br /&gt;                        &amp;lt;/util:list&amp;gt;&lt;br /&gt;                    &amp;lt;/property&amp;gt;&lt;br /&gt;                &amp;lt;/bean&amp;gt;&lt;br /&gt;            &amp;lt;/clustering:strategy&amp;gt;&lt;br /&gt;        &amp;lt;/clustering:loadDistributor&amp;gt;&lt;br /&gt;    &amp;lt;/jaxws:features&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/jaxws:client&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Please note that the client itself does no longer define the address attribute. This suggests that &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;alternateAddresses&lt;/span&gt; list is used exclusively throughout all the invocations and no primary address exists – which is actually the case. &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;SequentialStrategy&lt;/span&gt; will use one endpoint after another providing nice round robin implementation (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;RandomStrategy&lt;/span&gt; is available as well). Also in this configuration you will get failover for free – if any endpoint fails, all endpoints starting from the first one will be examined (obviously except the one that has just failed).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Great! Now are CXF clients are much more rigid and fault-tolerant. But in our journey for higher availability and minimizing downtimes having alternate nodes being loaded only at application startup (in other words – adding a new server requires all clients restart) is too limiting. Fortunately we can make our load-balancing a bit more dynamic in two simple steps.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;jaxws:client id="testServiceClient" serviceClass="com.blogspot.nurkiewicz.cxfcluster.SimpleService"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;jaxws:features&amp;gt;&lt;br /&gt;        &amp;lt;clustering:loadDistributor&amp;gt;&lt;br /&gt;            &amp;lt;clustering:strategy&amp;gt;&lt;br /&gt;                &amp;lt;bean class="org.apache.cxf.clustering.SequentialStrategy"&amp;gt;&lt;br /&gt;                    &amp;lt;property name="alternateAddresses" ref="alternateAddresses"/&amp;gt;&lt;br /&gt;                &amp;lt;/bean&amp;gt;&lt;br /&gt;            &amp;lt;/clustering:strategy&amp;gt;&lt;br /&gt;        &amp;lt;/clustering:loadDistributor&amp;gt;&lt;br /&gt;    &amp;lt;/jaxws:features&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/jaxws:client&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;util:list id="alternateAddresses" list-class="java.util.concurrent.CopyOnWriteArrayList"&amp;gt;&lt;br /&gt;    &amp;lt;value&amp;gt;http://serverA/simple&amp;lt;/value&amp;gt;&lt;br /&gt;    &amp;lt;value&amp;gt;http://serverB/simple&amp;lt;/value&amp;gt;&lt;br /&gt;    &amp;lt;value&amp;gt;http://serverC/simple&amp;lt;/value&amp;gt;&lt;br /&gt;    &amp;lt;value&amp;gt;http://serverD/simple&amp;lt;/value&amp;gt;&lt;br /&gt;&amp;lt;/util:list&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Nothing fancy, extracting nested anonymous bean. But having access to this list (please note I used &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;java.util.concurrent.CopyOnWriteArrayList&lt;/span&gt;) enables us to inject it to any other service, possibly changing its state. How do I know this will work? Well, I spent few afternoons debugging Apache CXF to finally discover load-balancing algorithm: at first invocation CXF asks strategy for a list of possible nodes. Then it passes this list back to the strategy asking to pick one (small &lt;i&gt;wtf&lt;/i&gt; here...) The strategy decides which address to use and removes picked address from the list (another small &lt;i&gt;one&lt;/i&gt; here...) When CXF discovers the list is empty, story repeats itself. So if we replace the list of alternate addresses at runtime, after one round new list will be returned to the core CXF infrastructure.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Because I'm a huge JMX advocate, here is how we are going to modify the addresses list (you can use whatever mechanism you like):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Service&lt;br /&gt;@ManagedResource&lt;br /&gt;public class AlternateAddressesManager {&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private List&amp;lt;String&amp;gt; alternateAddresses;&lt;br /&gt;&lt;br /&gt;    @ManagedOperation&lt;br /&gt;    public void addAlternateAddress(String address) {&lt;br /&gt;        alternateAddresses.add(address);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @ManagedOperation&lt;br /&gt;    public boolean removeAlternateAddress(String address) {&lt;br /&gt;        return alternateAddresses.remove(address);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @ManagedAttribute&lt;br /&gt;    public List&amp;lt;String&amp;gt; getAlternateAddresses() {&lt;br /&gt;        return Collections.unmodifiableList(alternateAddresses);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Yep, it's the very same &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;alternateAddresses&lt;/span&gt; list used by &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;SequentialStrategy&lt;/span&gt;, so by simply modifying it we are altering CXF addressing behaviour. Arguably we could extend &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;CopyOnWriteArrayList&lt;/span&gt; adding few extra JMX-enabled methods (or, exploting Springs' flexibility, expose &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;List&lt;/span&gt; methods directly via JMX!), but this would decrease maintainability and I would consider this as poor design.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Finally, we can launch &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;jconsole&lt;/span&gt; or JVisualVM as on the screenshots below and enjoy our load-balancing infrastructure:&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-0ZMAvLi6dOY/TeQPhgWf7RI/AAAAAAAAAbo/RolMGEq_NhU/s1600/zrzut_ekranu-8.png" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="249" src="http://3.bp.blogspot.com/-0ZMAvLi6dOY/TeQPhgWf7RI/AAAAAAAAAbo/RolMGEq_NhU/s320/zrzut_ekranu-8.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-M6arpyUFIO4/TeQPi32_k3I/AAAAAAAAAbs/bx3QmaXkVmo/s1600/zrzut_ekranu-9.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="164" src="http://2.bp.blogspot.com/-M6arpyUFIO4/TeQPi32_k3I/AAAAAAAAAbs/bx3QmaXkVmo/s320/zrzut_ekranu-9.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Happy? Not really. While studying CXF source code I came across this dreadful JavaDoc comment on &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;LoadDistributorFeature&lt;/span&gt; and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;FailoverTargetSelector&lt;/span&gt; classes which take significant part in load-balancing process:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;/**&lt;/div&gt;&lt;div style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;&amp;nbsp;* [...]&lt;/div&gt;&lt;div style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;&amp;nbsp;* Note that this feature changes the conduit on the fly and thus &lt;b&gt;makes&lt;/b&gt;&lt;/div&gt;&lt;div style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;&amp;nbsp;* &lt;b&gt;the Client not thread safe.&lt;/b&gt;&lt;/div&gt;&lt;div style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;&amp;nbsp;*/&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Focus on the text in bold (OK, honestly, I don't understand the rest). If you've worked with Spring for some time you know that &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;testServiceClient&lt;/span&gt; bean is a shared singleton used by multiple threads concurrently (no, making it prototype scope won't help; why?), in contrary to default EJB stateless session beans, which are pooled. Fortunately Spring has a built-in solution for that as well. But before I finally came up with a right solution, several obstacles arose.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;First, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;jaxws:client&lt;/span&gt; tag from CXF namespace does not allow to define bean scope, defaulting to singleton, while we want to pool our clients. So I had to fall back to good old bean definition with &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;org.apache.cxf.jaxws.JaxWsProxyFactoryBean&lt;/span&gt;. No problem, slightly more verbose, although if you can't/don't want to use custom Spring namespaces, you might have used it from the very beginning. Now the best part: I can simply wrap any bean with prototype scope in a special proxy and Spring will &lt;i&gt;automagically&lt;/i&gt; create an object pool (based on &lt;a href="http://commons.apache.org/pool/"&gt;commons-pool&lt;/a&gt; library) and create as many bean instances as necessary to keep each bean used by only one thread. Here is the configuration:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;bean id="testServiceClientFactoryBean" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean"&amp;gt;&lt;br /&gt;    &amp;lt;property name="serviceClass" value="com.blogspot.nurkiewicz.cxfcluster.SimpleService"/&amp;gt;&lt;br /&gt;    &amp;lt;property name="features"&amp;gt;&lt;br /&gt;        &amp;lt;util:list&amp;gt;&lt;br /&gt;            &amp;lt;bean class="org.apache.cxf.clustering.LoadDistributorFeature"&amp;gt;&lt;br /&gt;                &amp;lt;property name="strategy"&amp;gt;&lt;br /&gt;                    &amp;lt;bean class="org.apache.cxf.clustering.SequentialStrategy"&amp;gt;&lt;br /&gt;                        &amp;lt;property name="alternateAddresses" ref="alternateAddresses"/&amp;gt;&lt;br /&gt;                    &amp;lt;/bean&amp;gt;&lt;br /&gt;                &amp;lt;/property&amp;gt;&lt;br /&gt;            &amp;lt;/bean&amp;gt;&lt;br /&gt;        &amp;lt;/util:list&amp;gt;&lt;br /&gt;    &amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;bean id="testServiceClientTarget" factory-bean="testServiceClientFactoryBean" factory-method="create" scope="prototype" lazy-init="true"/&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;bean id="testServiceClient" class="org.springframework.aop.framework.ProxyFactoryBean"&amp;gt;&lt;br /&gt;    &amp;lt;property name="targetSource"&amp;gt;&lt;br /&gt;        &amp;lt;bean class="org.springframework.aop.target.CommonsPoolTargetSource"&amp;gt;&lt;br /&gt;            &amp;lt;property name="targetClass" value="com.blogspot.nurkiewicz.cxfcluster.SimpleService"/&amp;gt;&lt;br /&gt;            &amp;lt;property name="targetBeanName" value="testServiceClientTarget"/&amp;gt;&lt;br /&gt;            &amp;lt;property name="maxSize" value="10"/&amp;gt;&lt;br /&gt;            &amp;lt;property name="maxWait" value="5000"/&amp;gt;&lt;br /&gt;        &amp;lt;/bean&amp;gt;&lt;br /&gt;    &amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Have you noticed &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;maxSize&lt;/span&gt; and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;maxWait&lt;/span&gt; pool attributes? They are &lt;b&gt;insanely cool&lt;/b&gt;! You can tell Spring not to create more than 10 clients in the pool and if the pool is empty (all the beans are currently in use), we should wait no more than 5000ms (and what happens afterwards is configurable!) This is actually a very simple yet powerful throttling mechanism, much simpler than JMS or explicit thread pools, we get absolutely for free! E.g. don't want to serve more than 20 concurrent web service clients? Make your server endpoint access service bean being pooled with size limited to 20. Client above this limit will be rejected as no service bean is available.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Of course in adults world nothing works as expected. I quickly discovered that &lt;i&gt;JaxWsProxyFactoryBean.create is not thread-safe&lt;/i&gt;&lt;span style="font-style: normal;"&gt; and reported &lt;a href="https://issues.apache.org/jira/browse/CXF-3558"&gt;CXF-3558&lt;/a&gt;. As a workaround I had to synchronize the client factory used by &lt;/span&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; font-style: normal;"&gt;CommonsPoolTargetSource&lt;/span&gt;&lt;span style="font-style: normal;"&gt; simply by subclassing it:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-style: normal;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;import org.apache.commons.pool.ObjectPool;&lt;br /&gt;import org.apache.commons.pool.PoolUtils;&lt;br /&gt;import org.springframework.aop.target.CommonsPoolTargetSource;&lt;br /&gt;&lt;br /&gt;public class SynchCommonsPoolTargetSource extends CommonsPoolTargetSource {&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    protected ObjectPool createObjectPool() {&lt;br /&gt;        return PoolUtils.synchronizedPool(super.createObjectPool());&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-style: normal;"&gt;Synchronizing the factory seems like a common need so I created &lt;a href="https://jira.springsource.org/browse/SPR-8382"&gt;SPR-8382&lt;/a&gt; – maybe it will find its way to official release. BTW while working on this article I also reported &lt;a href="http://youtrack.jetbrains.net/issue/IDEA-70365"&gt;IDEA-70365&lt;/a&gt; – &lt;/span&gt;&lt;i&gt;Spurious "Could not autowire" error reported for beans of List type&lt;/i&gt;&lt;span style="font-style: normal;"&gt;.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-style: normal;"&gt;Finally! Our load-balancing and failover works like a charm. Next step would be to temporarily discard nodes that are down for couple of seconds and increase this time if the endpoint is still down afterwards. But Apache CXF has so terrible API in this area that I had to leave this topic for a while. Maybe YOU can help?&lt;/span&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-7180071547096823487?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/7180071547096823487/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/05/enabling-load-balancing-and-failover-in.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/7180071547096823487'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/7180071547096823487'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/05/enabling-load-balancing-and-failover-in.html' title='Enabling load balancing and failover in Apache CXF'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/-0ZMAvLi6dOY/TeQPhgWf7RI/AAAAAAAAAbo/RolMGEq_NhU/s72-c/zrzut_ekranu-8.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-8544619098801066319</id><published>2011-04-08T19:50:00.003+02:00</published><updated>2011-11-17T19:19:28.907+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='logging'/><category scheme='http://www.blogger.com/atom/ns#' term='nosql'/><category scheme='http://www.blogger.com/atom/ns#' term='mongodb'/><category scheme='http://www.blogger.com/atom/ns#' term='logback'/><title type='text'>MongoDB and recording appenders for Logback</title><content type='html'>&lt;div&gt;Today I am giving you two new &lt;a href="http://logback.qos.ch/manual/appenders.html"&gt;appenders&lt;/a&gt; for &lt;a href="http://logback.qos.ch/"&gt;Logback&lt;/a&gt;: one for &lt;a href="http://www.mongodb.org/"&gt;MongoDB&lt;/a&gt; and one which I called &lt;i&gt;recording appender&lt;/i&gt;. Just as a reminder, appenders (both in Log4J and Logback) are an abstraction of your application logs destination. The most common are &lt;a href="http://logback.qos.ch/manual/appenders.html#FileAppender"&gt;file&lt;/a&gt; and &lt;a href="http://logback.qos.ch/manual/appenders.html#ConsoleAppender"&gt;console&lt;/a&gt; appenders, followed by several others built-in. MongoDB appender is pretty straightforward, so I will start by describing the recording appender.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4 class="western"&gt;Recording appender&lt;/h4&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As you already &lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-logging-levels.html"&gt;know&lt;/a&gt;, one of the biggest benefits of using logging frameworks are logging levels. By carefully choosing levels for each logging statement we can easily filter which logs should be present in our log files and which shouldn't. Also we can apply different logging strategies for different environments. This is in theory. In practice we often face the choice between: log everything just in case and handle gigabytes of meaningless log files &lt;i&gt;&lt;b&gt;or&lt;/b&gt;&lt;/i&gt;&lt;span style="font-weight: normal;"&gt; log only warnings and errors but when they actually occur, they are meaningless as well, lacking important debugging context. &lt;/span&gt;&lt;span style="font-weight: normal;"&gt;The idea isn't new (see &lt;/span&gt;&lt;span style="font-weight: normal;"&gt;&lt;a href="http://stackoverflow.com/questions/690431/how-to-configure-log4j-to-dump-debug-info-when-an-error-occurs"&gt;[1]&lt;/a&gt;, &lt;a href="http://www.mail-archive.com/logback-user@qos.ch/msg00606.html"&gt;[2]&lt;/a&gt; and &lt;a href="http://www.mail-archive.com/logback-user@qos.ch/msg02027.html"&gt;[3]&lt;/a&gt; for example), but somehow decent implementation is missing in both Log4J and Logback. And the idea is simple – as long as there is nothing wrong happening with the system: do not log anything or log very little – but silently memorize all debug logs in some cyclic buffer. And whenever disaster occurs (any log with ERROR level, probably an exception), dump the buffer first to provide meaningful context.&lt;/span&gt;&lt;/div&gt;&lt;div style="font-weight: normal; margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-weight: normal;"&gt;Writing custom logging appenders is pretty straightforward. &lt;/span&gt;&lt;span style="font-weight: normal;"&gt;Following is the essence of my recording appender:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;div style="font-weight: normal; margin-bottom: 0cm;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class RecordingAppender extends UnsynchronizedAppenderBase&amp;lt;ILoggingEvent&amp;gt; {&lt;br /&gt;&lt;br /&gt;  private ThreadLocal&amp;lt;CyclicBuffer&amp;lt;ILoggingEvent&amp;gt;&amp;gt; recordedEvents = new ThreadLocal&amp;lt;CyclicBuffer&amp;lt;ILoggingEvent&amp;gt;&amp;gt;() {&lt;br /&gt;    @Override&lt;br /&gt;    protected CyclicBuffer&amp;lt;ILoggingEvent&amp;gt; initialValue() {&lt;br /&gt;      return new CyclicBuffer&amp;lt;ILoggingEvent&amp;gt;(maxEvents);&lt;br /&gt;    }&lt;br /&gt;  };&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  protected void append(ILoggingEvent eventObject) {&lt;br /&gt;    if (triggersDump(eventObject)) {&lt;br /&gt;      dumpRecordedEvents();&lt;br /&gt;      dump(eventObject);&lt;br /&gt;    } else&lt;br /&gt;      recordedEvents.get().add(eventObject);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  //...&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I hope the code is self-explanatory, if not – I failed as a developer, not you as a reader. The only detail worth explaining is the usage of &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;ThreadLocal&lt;/span&gt;. Logging history is stored ThreadLocal, so only logs from current thread will be dumped in case of error. This seems reasonable in most cases (and eliminates the need for synchronization). Why the appender is parametrized with generic &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;ILoggingEvent&lt;/span&gt; type will be described later. The full source code of this appender is, as always, available on my Logback &lt;a href="https://github.com/nurkiewicz/logback/blob/recording-appender/logback-classic/src/main/java/ch/qos/logback/classic/RecordingAppender.java"&gt;fork&lt;/a&gt; at GitHub (&lt;a href="https://github.com/nurkiewicz/logback/tree/recording-appender"&gt;recording-appender&lt;/a&gt; branch).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Using this appender is really simple – just declare &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;ch.qos.logback.classic.RecordingAppender&lt;/span&gt; and define one or more delegating appenders to be used when dump is required. As a side note: which GoF pattern is it?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;With the configuration below every log statement with level WARN or higher will trigger dump. The configuration also states that up to 1000 records will be kept in memory, unless some of them are older than 15 seconds. When warning or error is encountered, it will be printed on the console, preceded by more detailed logs. It really works (in addition of having &lt;a href="https://github.com/nurkiewicz/logback/blob/recording-appender/logback-classic/src/test/java/ch/qos/logback/classic/RecordingAppenderTest.java"&gt;100%&lt;/a&gt; code coverage).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8" ?&amp;gt;&lt;br /&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;  &amp;lt;appender name="REC" class="ch.qos.logback.classic.RecordingAppender"&amp;gt;&lt;br /&gt;    &amp;lt;appender-ref ref="STDOUT"/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;maxEvents&amp;gt;1000&amp;lt;/maxEvents&amp;gt;&lt;br /&gt;    &amp;lt;dumpThreshold&amp;gt;WARN&amp;lt;/dumpThreshold&amp;gt;&lt;br /&gt;    &amp;lt;expiryTimeMs&amp;gt;15000&amp;lt;/expiryTimeMs&amp;gt;&lt;br /&gt;  &amp;lt;/appender&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"&amp;gt;&lt;br /&gt;    &amp;lt;encoder&amp;gt;&lt;br /&gt;      &amp;lt;pattern&amp;gt;%-4relative [%thread] %-5level - %msg%n&amp;lt;/pattern&amp;gt;&lt;br /&gt;    &amp;lt;/encoder&amp;gt;&lt;br /&gt;  &amp;lt;/appender&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;root level="DEBUG"&amp;gt;&lt;br /&gt;    &amp;lt;appender-ref ref="REC"/&amp;gt;&lt;br /&gt;  &amp;lt;/root&amp;gt;&lt;br /&gt;&amp;lt;/configuration&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h4 class="western"&gt;MongoDB appender&lt;/h4&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;MongoDB, being document oriented database focused on performance and scalability seems like a great storage for application and server logs – much better than &lt;a href="http://logback.qos.ch/manual/appenders.html#DBAppender"&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;DbAppender&lt;/span&gt;&lt;/a&gt; using traditional relational database. Why? Quickly count how many tables and rows you need to store normalized logging event containing stack trace with several frames and MDC map? And what if you just want to store some properties, leaving others as optional? Sacrificing absolute durability and ACID constraints, in MongoDB you just store document – with nested properties, skipping optional parameters – and extremely fast. Also, once again, the idea isn't &lt;a href="http://www.slideshare.net/WombatNation/logging-app-behavior-to-mongo-db"&gt;new&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But again, why would you like to store application or web server HTTP access logs (be patient!) in database altogether? Well, with a little help of &lt;a href="http://www.mongodb.org/display/DOCS/Sharding"&gt;sharding&lt;/a&gt; and &lt;a href="http://www.mongodb.org/display/DOCS/MapReduce"&gt;MapReduce&lt;/a&gt;, searching, aggregating and transforming &lt;i&gt;a lot&lt;/i&gt; of data is a pleasure.  &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The implementation is trivial (excerpt from &lt;a href="https://github.com/nurkiewicz/logback/blob/mongodb-appender/logback-core/src/main/java/ch/qos/logback/core/db/mongo/MongoDBAppenderBase.java"&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;MongoDBAppenderBase.java&lt;/span&gt;&lt;/a&gt;, see &lt;a href="https://github.com/nurkiewicz/logback/tree/mongodb-appender"&gt;mongo-appender&lt;/a&gt; branch):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://draft.blogger.com/post-create.g?blogID=6753769565491687768" name="__DdeLink__290_1782232332"&gt;&lt;/a&gt; &lt;pre class="brush: java"&gt;&lt;br /&gt;public abstract class MongoDBAppenderBase&amp;lt;E&amp;gt; extends UnsynchronizedAppenderBase&amp;lt;E&amp;gt; {&lt;br /&gt;&lt;br /&gt;  //...&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  public void start() {&lt;br /&gt;    try {&lt;br /&gt;      connectToMongoDB();&lt;br /&gt;      super.start();&lt;br /&gt;    } catch (UnknownHostException e) {&lt;br /&gt;      addError("Error connecting to MongoDB server: " + host + ":" + port, e);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private void connectToMongoDB() throws UnknownHostException {&lt;br /&gt;    mongo = new Mongo(new ServerAddress(host, port), buildOptions());&lt;br /&gt;    DB db = mongo.getDB(dbName);&lt;br /&gt;    if (username != null &amp;&amp; password != null)&lt;br /&gt;      db.authenticate(username, password.toCharArray());&lt;br /&gt;    eventsCollection = db.getCollection(collectionName);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  protected abstract BasicDBObject toMongoDocument(E event);&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  protected void append(E eventObject) {&lt;br /&gt;    eventsCollection.insert(toMongoDocument(eventObject));&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  //...&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://draft.blogger.com/post-create.g?blogID=6753769565491687768" name="__DdeLink__288_1782232332"&gt;&lt;/a&gt; Appender doesn't have to be synchronized (it only uses native MongoDB &lt;a href="http://www.mongodb.org/display/DOCS/Java+Language+Center"&gt;Java driver&lt;/a&gt;, which is thread safe and even handles connection pooling) and all it does is connecting to MongoDB server/cluster and insert logging events as documents in the database. Abstract &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;toMongoDocument()&lt;/span&gt; method and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;E&lt;/span&gt; generic type? - looks suspicious... Logback has a pretty clever architecture. In &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;logback-core&lt;/span&gt; you place general logging logic, like connecting and storing documents in MongoDB in our case. Then one can simply subclass the base appender to define logic specific to a given logging object type.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;img src="http://yuml.me/diagram/scruffy;dir:td/class/%5BMongoDBAppenderBase%3CE%3E%5D%5E%5BMongoDBAppender%3CIAccessEvent%3E%5D%0D,%20%5BMongoDBAppenderBase%3CE%3E%5D%5E%5BMongoDBAppender%3CILoggingEvent%3E%5D" /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So what object types does Logback support? The traditional (classic) logging is what we are familiar with. &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;logback-access&lt;/span&gt; on the other hand allows us to log web container &lt;a href="http://httpd.apache.org/docs/2.2/logs.html#accesslog"&gt;access logs&lt;/a&gt; using Logback infrastructure. And because MongoDB has no schema and creates collections (table-like structures) the first time they are used, we can essentially store anything. Following is the  &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;toMongoDocument()&lt;/span&gt; implementation excerpt for classic logs (note the generic type):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class MongoDBAppender extends MongoDBAppenderBase&amp;lt;ILoggingEvent&amp;gt; {&lt;br /&gt;&lt;br /&gt;  public MongoDBAppender() {&lt;br /&gt;    super("loggingEvents");&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  protected BasicDBObject toMongoDocument(ILoggingEvent event) {&lt;br /&gt;    final BasicDBObject doc = new BasicDBObject();&lt;br /&gt;    doc.append("timeStamp", new Date(event.getTimeStamp()));&lt;br /&gt;    doc.append("level", event.getLevel().levelStr);&lt;br /&gt;    doc.append("thread", event.getThreadName());&lt;br /&gt;    if (event.getMdc() != null &amp;&amp; !event.getMdc().isEmpty())&lt;br /&gt;      doc.append("mdc", event.getMdc());&lt;br /&gt;    //...&lt;br /&gt;    return doc;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;...and here is what you can expect to find your MongoDB database:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;{&lt;br /&gt;    "_id" : ObjectId("4d9cbcbf7abb3abdaf9679cd"),&lt;br /&gt;    "timeStamp" : ISODate("2011-04-06T19:19:27.006Z"),&lt;br /&gt;    "level" : "ERROR",&lt;br /&gt;    "thread" : "main",&lt;br /&gt;    "logger" : "ch.qos.logback.classic.db.mongo.MongoDBAppenderTest",&lt;br /&gt;    "message" : "D" &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Very similar implementation for access logs follows. Once again look carefully – both appenders are extending &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;MongoDBAppenderBase&lt;/span&gt; with different generic type, only implementing &lt;i&gt;log-to-document&lt;/i&gt; logic, whereas common database connection logic is handled once in base class. Pretty elegant design (it's Logback design, not mine, I am just following it), seems like OOP is not dead after all:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class MongoDBAppender extends MongoDBAppenderBase&amp;lt;IAccessEvent&amp;gt; {&lt;br /&gt;&lt;br /&gt;  public MongoDBAppender() {&lt;br /&gt;    super("accessEvents");&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  protected BasicDBObject toMongoDocument(IAccessEvent event) {&lt;br /&gt;    final BasicDBObject doc = new BasicDBObject();&lt;br /&gt;    doc.append("timeStamp", new Date(event.getTimeStamp()));&lt;br /&gt;    if(server)&lt;br /&gt;      doc.append("server", event.getServerName());&lt;br /&gt;    //...&lt;br /&gt;    return doc;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You can compare &lt;a href="https://github.com/nurkiewicz/logback/blob/mongodb-appender/logback-classic/src/main/java/ch/qos/logback/classic/db/mongo/MongoDBAppender.java"&gt;classic&lt;/a&gt; and &lt;a href="https://github.com/nurkiewicz/logback/blob/mongodb-appender/logback-access/src/main/java/ch/qos/logback/access/db/mongo/MongoDBAppender.java"&gt;access&lt;/a&gt; implementations to see how similar they are, although they cope with really different data. Here is what you might find in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;accessEvents&lt;/span&gt; collections in MongoDB:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;{&lt;br /&gt;    "_id" : ObjectId("4d98cc4f7abb95e59279e183"),&lt;br /&gt;    "timeStamp" : ISODate("2011-04-03T19:36:47.339Z"),&lt;br /&gt;    "server" : "localhost",&lt;br /&gt;    "remote" : {&lt;br /&gt;        "host" : "0:0:0:0:0:0:0:1",&lt;br /&gt;        "user" : "tomcat",&lt;br /&gt;        "addr" : "0:0:0:0:0:0:0:1" &lt;br /&gt;    },&lt;br /&gt;    "request" : {&lt;br /&gt;        "uri" : "/manager/images/tomcat.gif",&lt;br /&gt;        "protocol" : "HTTP/1.1",&lt;br /&gt;        "method" : "GET",&lt;br /&gt;        "sessionId" : "1C6357816D9EEFD31F6D9D154D87308A",&lt;br /&gt;        "userAgent" : "Mozilla/5.0 (X11; U; Linux i686; pl-PL; rv:1.9.2.16) Gecko/20110323 Ubuntu/10.10 (maverick) Firefox/3.6.16",&lt;br /&gt;        "referer" : "http://localhost:8080/manager/html" &lt;br /&gt;    },&lt;br /&gt;    "response" : {&lt;br /&gt;        "contentLength" : NumberLong(1934),&lt;br /&gt;        "statusCode" : 200 &lt;br /&gt;    } &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You might ask yourself a question: why would I store access logs in crazy, JSON-like documents stored in database driven by C++? The answer is: scalability. MongoDB speed and sharding capabilities make it a great choice for storing lots of free-form data. Now, using built-in MapReduce framework you might search, aggregate, or maybe even look for suspicious usage patterns across thousands of servers in parallel. Be warned thou that &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;timeStamp&lt;/span&gt;, although looks promising, isn't very good candidate for sharding key. Assuming all your web servers have similar system clock, at a given point in time all of them will be writing to the same shard. After a moment or two, they will all switch to a different one. At the same time, all other shards are dying of boredom. But &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;timeStamp+serverName&lt;/span&gt; looks nice (order of keys in compound key is really important, just like with indexes in RDBMS).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Another tip is using &lt;a href="http://www.mongodb.org/display/DOCS/Capped+Collections"&gt;capped collections&lt;/a&gt; in MongoDB. There is no obvious natural key for logging events (both classic and access), so we need to use generated keys, which aren't useful as they don't form any particular order. But if you use capped collections, order of records in the database is guaranteed to be the same as insertion order. Also, capped collections are limited in size and automatically remove the oldest entries, which seems like a great fit for logging use case.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,monospace;"&gt;MongoDBAppender&lt;/span&gt; has many other features, including:&lt;/div&gt;&lt;ul&gt;&lt;li&gt;&lt;div&gt;Fully configurable MongoDB  connection&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div&gt;For access logger you can define  which access parameters (like response status code, URI, session id,  etc.) should be persisted&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div&gt;For classic logger: should caller  data be persisted&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;See for yourself how many optional parameters are &lt;a href="https://github.com/nurkiewicz/logback/blob/mongodb-appender/logback-classic/src/test/input/joran/mongodb/all_params.xml"&gt;provided&lt;/a&gt;. If you like the idea of recording appender (&lt;i&gt;your application very own &lt;a href="http://en.wikipedia.org/wiki/Flight_data_recorder"&gt;flight data recorder&lt;/a&gt;&lt;/i&gt;), please take a look and vote for &lt;a href="http://jira.qos.ch/browse/LBCLASSIC-260"&gt;LBCLASSIC-260&lt;/a&gt;. I also filed an issue for MongoDB appender, &lt;a href="http://jira.qos.ch/browse/LBCLASSIC-261"&gt;LBCLASSIC-261&lt;/a&gt;. Oh, if I'm into advertising myself already, maybe &lt;a href="http://jira.qos.ch/browse/LBCLASSIC-217"&gt;this&lt;/a&gt; will catch your attention as well. Have a great time playing with my appenders (you can even combine them) and I'm waiting for your comments.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-8544619098801066319?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/8544619098801066319/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/04/mongodb-and-recording-appenders-for.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/8544619098801066319'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/8544619098801066319'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/04/mongodb-and-recording-appenders-for.html' title='MongoDB and recording appenders for Logback'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-8563938229337803058</id><published>2011-03-20T19:46:00.001+01:00</published><updated>2011-11-17T19:17:16.718+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='jfreechart'/><category scheme='http://www.blogger.com/atom/ns#' term='jmx'/><category scheme='http://www.blogger.com/atom/ns#' term='jqplot'/><category scheme='http://www.blogger.com/atom/ns#' term='jquery'/><category scheme='http://www.blogger.com/atom/ns#' term='jolokia'/><category scheme='http://www.blogger.com/atom/ns#' term='highcharts'/><category scheme='http://www.blogger.com/atom/ns#' term='monitoring'/><title type='text'>Jolokia + Highcharts = JMX for human beings</title><content type='html'>&lt;div&gt;Java Management Extensions (&lt;a href="http://www.oracle.com/technetwork/java/javase/tech/javamanagement-140525.html"&gt;JMX&lt;/a&gt;) is a well established, but not widespread technology allowing to monitor and manage every JVM. It provides tons of useful information, like CPU, thread and memory monitoring. Also every application can register its own metrics and operations in so called &lt;a href="http://download.oracle.com/javase/6/docs/api/javax/management/MBeanServer.html"&gt;MBeanServer&lt;/a&gt;. Several libraries take advantage of JMX: &lt;a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/jmx/StatisticsServiceMBean.html"&gt;Hibernate&lt;/a&gt;, &lt;a href="http://ehcache.org/documentation/jmx.html"&gt;EhCache&lt;/a&gt; and &lt;a href="http://logback.qos.ch/manual/jmxConfig.html"&gt;Logback&lt;/a&gt; and servers like &lt;a href="http://tomcat.apache.org/tomcat-7.0-doc/monitoring.html"&gt;Tomcat&lt;/a&gt; or &lt;a href="http://www.mulesoft.org/documentation/display/MULE3USER/JMX+Management"&gt;Mule ESB&lt;/a&gt;, to name a few. This way one can monitor ORM performance, HTTP worker threads utilization, but also change logging levels, flush caches, etc. If you are creating your own library or container, JMX is a standard for monitoring, so please don't reinvent a wheel. Also Spring has a wonderful support for &lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jmx.html"&gt;JMX&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;If this standard is so wonderful, why aren't we using it all day long? Well, history of JMX reaches the dark ages of J2EE. Although the specification isn't that complicated, there are at least two disadvantages of JMX effectively discouraging people from using it. First one lies on the server side. At the foundation of Java Management Extensions is an MBeanServer where you register MBeans. Each MBean exposes its properties (attributes) and operations for external access. This is fine (especially when Spring is used: 1 line of XML + two annotations), but there's a catch. By default the MBeanServer exposes itself via RMI, which is certainly not the top XXI century protocol...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The second drawback of JMX lies on the client side. &lt;a href="http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html"&gt;JConsole&lt;/a&gt;, although not terrible, has very limited functionality. If we want to present our JMX-enabled application to the customer, showing JConsole as a client is a bit embarrassing. It is capable of showing graphs, but you cannot display more than one attribute at the same composite graph and you also can't observe attributes from different MBeans at the same time. Last but not least, again, we're living in the XXI century, Swing client? Weird RMI port? What about Web 2.0 rave? Knowing how much I love charts (and how data visualization is important for diagnosing and correlating facts) I felt really disappointed by JConsole capabilites. And the only &lt;a href="http://www.jmanage.org/"&gt;rival&lt;/a&gt; of JConsole seems dead.&lt;/div&gt;&lt;h5 class="western"&gt;Jolokia – bridge JMX over HTTP&lt;/h5&gt;&lt;br /&gt;I knew exactly what I wanted: HTTP transport for JMX server, so that I can easily access MBeanServer from outside without the RMI mess. &lt;a href="http://www.jolokia.org/features-nb.html"&gt;Jolokia&lt;/a&gt; meets my expectations perfectly. This small library (about 170 kiB) connects to a given MBeanServer and exposes it via REST-like interface. Just deploy the jolokia.war file on your servlet container and use whatever HTTP client you want to monitor your JVM!&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: plain"&gt;&lt;br /&gt;$ curl localhost:8080/jolokia&lt;br /&gt;{&lt;br /&gt;  "request" : { "type" : "version" },&lt;br /&gt;  "status" : 200,&lt;br /&gt;  "timestamp" : 1300561261,&lt;br /&gt;  "value" : {&lt;br /&gt;      "agent" : "0.83",&lt;br /&gt;      "info" : {&lt;br /&gt;          "product" : "tomcat",&lt;br /&gt;          "vendor" : "Apache",&lt;br /&gt;          "version" : "7.0.10"&lt;br /&gt;        },&lt;br /&gt;      "protocol" : "4.1"&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;$ curl localhost:8080/jolokia/read/java.lang:type=Memory/HeapMemoryUsage&lt;br /&gt;{&lt;br /&gt;  "request" : {&lt;br /&gt;      "attribute" : "HeapMemoryUsage",&lt;br /&gt;      "mbean" : "java.lang:type=Memory",&lt;br /&gt;      "type" : "read"&lt;br /&gt;    },&lt;br /&gt;  "status" : 200,&lt;br /&gt;  "timestamp" : 1300561367,&lt;br /&gt;  "value" : {&lt;br /&gt;      "committed" : "169607168",&lt;br /&gt;      "init" : "49404160",&lt;br /&gt;      "max" : "702808064",&lt;br /&gt;      "used" : "16635472"&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;You must be aware that Jolokia has a handful of other features. It can work on ordinary JVMs (not only servlet containers) starting dedicated web server, it can also &lt;a href="http://www.jolokia.org/features/proxy.html"&gt;connect&lt;/a&gt; to external MBeanServer, so you don't have to add any new WAR files as long as you have JMX external access. But the killer feature I quickly discovered was:&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;h5 class="western"&gt;Jolokia + AJAX – a perfect couple&lt;/h5&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;HTTP, JSON... AJAX? Accessing MBeans directly using JavaScript on the client side would be huge. But I haven't even written a single line of code yet when I spotted Jolokia &lt;a href="http://jolokia.org/reference/html/clients.html#client-javascript"&gt;Javascript Client Library&lt;/a&gt;. Wow, I really love this project! So I took the token bucket application developed &lt;a href="http://nurkiewicz.blogspot.com/2011/03/tenfold-increase-in-server-throughput.html"&gt;last time&lt;/a&gt; and quickly added simple server polling for current heap memory usage. Boring. Chart displaying memory usage over time would be much sexier...&lt;/div&gt;&lt;h5 class="western"&gt;Jolokia, AJAX and Highcharts – exciting threesome&lt;/h5&gt;&lt;div&gt;First, I owe you some explanation. Why am I entering the dirty playground of the most hated web 2.0 child – JavaScript? Let me reveal my goal: fast and snappy, good looking JMX visualization with real-time updates in the browser rather than in the obscure jconsole. The solution should be simple, shouldn't require major server side changes (preferably: none) and should be highly configurable and flexible. Leveraging &lt;a href="http://www.jfree.org/jfreechart/"&gt;JFreeChart&lt;/a&gt; (Java de facto standard for charting) to produce new version of the chart each second or even more frequently was out of the question.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But if we already have access to JMX metrics on the client (browser) side, why not generating the charts there as well, only quickly updating data series when new data arrives. Be pragmatic. First I tried &lt;a href="http://www.jqplot.com/"&gt;jqPlot&lt;/a&gt; – works great for static charts, but sucks completely when trying to update them. Unless you can live with 10 MiB of memory leaking in the browser every second per chart... Seems like many JavaScript charting libraries suffer the same problem – except &lt;a href="http://www.highcharts.com/"&gt;Highcharts&lt;/a&gt; – library of my choice. Here is how easily one can plot memory usage chart only on the client side using Jolokia JMX library:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;$(document).ready(function() {&lt;br /&gt;    new Monitor();&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;function Monitor() {&lt;br /&gt;    var jmx = new Jolokia("/jolokia");&lt;br /&gt;&lt;br /&gt;    var chart = new Highcharts.Chart({&lt;br /&gt;        chart: {&lt;br /&gt;            renderTo: 'memoryChart',&lt;br /&gt;            defaultSeriesType: 'spline',&lt;br /&gt;            events: {&lt;br /&gt;                load: function() {&lt;br /&gt;                    var series = this.series[0];&lt;br /&gt;                    setInterval(function() {&lt;br /&gt;                        var x = (new Date()).getTime();&lt;br /&gt;                        var memoryUsed = jmx.getAttribute("java.lang:type=Memory", "HeapMemoryUsage", "used");&lt;br /&gt;                        series.addPoint({&lt;br /&gt;                            x: new Date().getTime(),&lt;br /&gt;                            y: parseInt(memoryUsed)&lt;br /&gt;                        }, true, series.data.length &amp;gt;= 50);&lt;br /&gt;                    }, 1000);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        },&lt;br /&gt;        xAxis: {&lt;br /&gt;            type: 'datetime'&lt;br /&gt;        },&lt;br /&gt;        series: [{&lt;br /&gt;                data: [],&lt;br /&gt;            }&lt;br /&gt;        ]&lt;br /&gt;    });&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;Few less important lines were skipped (mainly chart cosmetics), as always full source is available on &lt;a href="https://github.com/nurkiewicz/token-bucket"&gt;GitHub&lt;/a&gt;. And this is the result so far:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh5.googleusercontent.com/-H3nlHGAfKN0/TYZJODIuekI/AAAAAAAAAaQ/cA8_tVMcqio/s1600/single.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="246" src="https://lh5.googleusercontent.com/-H3nlHGAfKN0/TYZJODIuekI/AAAAAAAAAaQ/cA8_tVMcqio/s320/single.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;BTW I bit reluctantly switched to Google Chrome browser while writing this article. JavaScript-heavy applications are insanely slow on Firefox, work fine on Opera but Google Chrome beats them together.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Having one chart, why not add several others? Luckily Jolokia supports &lt;a href="http://jolokia.org/features/bulk-requests.html"&gt;bulk&lt;/a&gt; requests (also in JavaScript client library), so we will poll server only once a second, no matter how many charts are displayed.  &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh4.googleusercontent.com/-V1pVl5POZ24/TYZJWYKkXNI/AAAAAAAAAaU/vlIn5Dyt1iM/s1600/multiple.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="242" src="https://lh4.googleusercontent.com/-V1pVl5POZ24/TYZJWYKkXNI/AAAAAAAAAaU/vlIn5Dyt1iM/s320/multiple.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Since we are doing so well, why not allow user to rearrange charts so that he can put most relevant ones next to each other (portlets? iGoogle? Anyone?) Luckily, &lt;a href="http://jqueryui.com/demos/sortable/portlets.html"&gt;jQuery UI&lt;/a&gt; library (Jolokia JavaScript client is built on top of jQuery) ships with portlet-like support built-in.  &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;function JmxChartsFactory(keepHistorySec, pollInterval, columnsCount) {&lt;br /&gt;    var jolokia = new Jolokia("/jolokia");&lt;br /&gt;    var series = [];&lt;br /&gt;    var monitoredMbeans = [];&lt;br /&gt;    var chartsCount = 0;&lt;br /&gt;&lt;br /&gt;    columnsCount = columnsCount || 3;&lt;br /&gt;    pollInterval = pollInterval || 1000;&lt;br /&gt;    var keepPoints = (keepHistorySec || 600) / (pollInterval / 1000);&lt;br /&gt;&lt;br /&gt;    setupPortletsContainer(columnsCount);&lt;br /&gt;&lt;br /&gt;    setInterval(function() {&lt;br /&gt;        pollAndUpdateCharts();&lt;br /&gt;    }, pollInterval);&lt;br /&gt;&lt;br /&gt;    this.create = function(mbeans) {&lt;br /&gt;        mbeans = $.makeArray(mbeans);&lt;br /&gt;        series = series.concat(createChart(mbeans).series);&lt;br /&gt;        monitoredMbeans = monitoredMbeans.concat(mbeans);&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    function pollAndUpdateCharts() {&lt;br /&gt;        var requests = prepareBatchRequest();&lt;br /&gt;        var responses = jolokia.request(requests);&lt;br /&gt;        updateCharts(responses);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function createNewPortlet(name) {&lt;br /&gt;        return $('#portlet-template')&lt;br /&gt;                .clone(true)&lt;br /&gt;                .appendTo($('.column')[chartsCount++ % columnsCount])&lt;br /&gt;                .removeAttr('id')&lt;br /&gt;                .find('.title').text((name.length &amp;gt; 50? '...' : '') + name.substring(name.length - 50, name.length)).end()&lt;br /&gt;                .find('.portlet-content')[0];&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function setupPortletsContainer() {&lt;br /&gt;        var column = $('.column');&lt;br /&gt;        for(var i = 1; i &amp;lt; columnsCount; ++i){&lt;br /&gt;            column.clone().appendTo(column.parent());&lt;br /&gt;        }&lt;br /&gt;        $(".column").sortable({&lt;br /&gt;            connectWith: ".column"&lt;br /&gt;        });&lt;br /&gt;&lt;br /&gt;        $(".portlet-header .ui-icon").click(function() {&lt;br /&gt;            $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");&lt;br /&gt;            $(this).parents(".portlet:first").find(".portlet-content").toggle();&lt;br /&gt;        });&lt;br /&gt;        $(".column").disableSelection();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function prepareBatchRequest() {&lt;br /&gt;        return $.map(monitoredMbeans, function(mbean) {&lt;br /&gt;            return {&lt;br /&gt;                type: "read",&lt;br /&gt;                mbean: mbean.name,&lt;br /&gt;                attribute: mbean.attribute,&lt;br /&gt;                path: mbean.path&lt;br /&gt;            };&lt;br /&gt;        });&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function updateCharts(responses) {&lt;br /&gt;        var curChart = 0;&lt;br /&gt;        $.each(responses, function() {&lt;br /&gt;            var point = {&lt;br /&gt;                x: this.timestamp * 1000,&lt;br /&gt;                y: parseFloat(this.value)&lt;br /&gt;            };&lt;br /&gt;            var curSeries = series[curChart++];&lt;br /&gt;            curSeries.addPoint(point, true, curSeries.data.length &amp;gt;= keepPoints);&lt;br /&gt;        });&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function createChart(mbeans) {&lt;br /&gt;        return new Highcharts.Chart({&lt;br /&gt;            chart: {&lt;br /&gt;                renderTo: createNewPortlet(mbeans[0].name),&lt;br /&gt;                animation: false,&lt;br /&gt;                defaultSeriesType: 'area',&lt;br /&gt;                shadow: false&lt;br /&gt;            },&lt;br /&gt;            title: { text: null },&lt;br /&gt;            xAxis: { type: 'datetime' },&lt;br /&gt;            yAxis: {&lt;br /&gt;                title: { text: mbeans[0].attribute }&lt;br /&gt;            },&lt;br /&gt;            legend: {&lt;br /&gt;                enabled: true,&lt;br /&gt;                borderWidth: 0&lt;br /&gt;            },&lt;br /&gt;            credits: {enabled: false},&lt;br /&gt;            exporting: { enabled: false },&lt;br /&gt;            plotOptions: {&lt;br /&gt;                area: {&lt;br /&gt;                    marker: {&lt;br /&gt;                        enabled: false&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;            },&lt;br /&gt;            series: $.map(mbeans, function(mbean) {&lt;br /&gt;                return {&lt;br /&gt;                    data: [],&lt;br /&gt;                    name: mbean.path || mbean.attribute&lt;br /&gt;                }&lt;br /&gt;            })&lt;br /&gt;        })&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Sure, 110 lines is a lot of code, but you must admit that it's not that much when feature set is considered: configurable chart history length, polling interval and number of columns in portlet layout. Also, the set of visible JMX charts are fully customizable. If you want, you might easily add the possibility to add and remove charts at runtime when needed or even browsing MBeanServer exposed beans. The usage is of this class is very simple:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;$(document).ready(function() {&lt;br /&gt;    var factory = new JmxChartsFactory();&lt;br /&gt;    factory.create([&lt;br /&gt;        {&lt;br /&gt;            name: 'java.lang:type=Memory',&lt;br /&gt;            attribute: 'HeapMemoryUsage',&lt;br /&gt;            path: 'committed'&lt;br /&gt;        },&lt;br /&gt;        {&lt;br /&gt;            name: 'java.lang:type=Memory',&lt;br /&gt;            attribute: 'HeapMemoryUsage',&lt;br /&gt;            path: 'used'&lt;br /&gt;        }&lt;br /&gt;    ]);&lt;br /&gt;    factory.create([&lt;br /&gt;        {&lt;br /&gt;            name: 'java.lang:type=OperatingSystem',&lt;br /&gt;            attribute: 'SystemLoadAverage'&lt;br /&gt;        }&lt;br /&gt;    ]);&lt;br /&gt;    factory.create({&lt;br /&gt;        name:     'java.lang:type=Threading',&lt;br /&gt;        attribute: 'ThreadCount'&lt;br /&gt;    });&lt;br /&gt;    factory.create([&lt;br /&gt;        {&lt;br /&gt;            name: 'Catalina:name="http-bio-8080",type=ThreadPool',&lt;br /&gt;            attribute: 'currentThreadsBusy'&lt;br /&gt;        },&lt;br /&gt;        {&lt;br /&gt;            name: 'Catalina:name=executor,type=Executor',&lt;br /&gt;            attribute: 'queueSize'&lt;br /&gt;        }&lt;br /&gt;    ]);&lt;br /&gt;    factory.create([&lt;br /&gt;        {&lt;br /&gt;            name: 'com.blogspot.nurkiewicz.download.tokenbucket:name=perRequestTokenBucket,type=PerRequestTokenBucket',&lt;br /&gt;            attribute: 'OngoingRequests'&lt;br /&gt;        },&lt;br /&gt;        {&lt;br /&gt;            name: 'com.blogspot.nurkiewicz.download:name=downloadServletHandler,type=DownloadServletHandler',&lt;br /&gt;            attribute: 'AwaitingChunks'&lt;br /&gt;        }&lt;br /&gt;    ]);&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt; &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Tired of code? HTML for this article can be found &lt;a href="https://github.com/nurkiewicz/token-bucket/blob/master/src/main/webapp/index.html"&gt;here&lt;/a&gt;, and as Chinese used to say, &lt;i&gt;a picture is worth a thousand &lt;/i&gt;&lt;i&gt;lines of code&lt;/i&gt;:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh4.googleusercontent.com/-oJPWOO1VYAU/TYZJc98K_lI/AAAAAAAAAaY/erLrPCHYv7A/s1600/portlet.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="195" src="https://lh4.googleusercontent.com/-oJPWOO1VYAU/TYZJc98K_lI/AAAAAAAAAaY/erLrPCHYv7A/s320/portlet.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;But because our monitoring dashboard is so dynamic, to quote &lt;a href="http://en.wikipedia.org/wiki/Nicolaus_Copernicus"&gt;Nicolaus Copernicus&lt;/a&gt; “&lt;i&gt;A YouTube video is worth a thousand pictures&lt;/i&gt;”* (somewhere in the middle you'll see the system reacting after heavy load was simulated):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="text-align: center;"&gt;&lt;iframe allowfullscreen="" frameborder="0" height="510" src="http://www.youtube.com/embed/a5nqZmyhTNo?rel=0&amp;amp;hd=1" title="YouTube video player" width="640"&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now these 100+ lines of JavaScript code aren't that overwhelming, don't you think? To summarize, using JavaScript and handful of readily available libraries we added interactive, refreshable, Web 2.0-ish monitoring dashboard. It integrates seamlessly with every JVM using JMX, and if we would use Jolokia &lt;a href="http://www.jolokia.org/features/proxy.html"&gt;proxy&lt;/a&gt; mode, &lt;b&gt;no&lt;/b&gt; changes would be required in monitored application/server. Because the client asks JMX server in batch and updates charts on the client side, everything works with minimal delay.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So the next time your customer asks for a monitoring solution or you want to enrich existing application without modifying it too much – consider the simplest solution, as it might be the best one as well. And maybe this tiny dashboard code is a valuable milestone of a decent successor of aforementioned &lt;a href="http://www.jmanage.org/"&gt;JManage&lt;/a&gt;? &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;* Other famous quote by &lt;a href="http://en.wikipedia.org/wiki/Nicolaus_Copernicus"&gt;Nicolaus Copernicus&lt;/a&gt;: “&lt;i&gt;Don't believe in everything you read in the Internet&lt;/i&gt;”...&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-8563938229337803058?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/8563938229337803058/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/03/jolokia-highcharts-jmx-for-human-beings.html#comment-form' title='11 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/8563938229337803058'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/8563938229337803058'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/03/jolokia-highcharts-jmx-for-human-beings.html' title='Jolokia + Highcharts = JMX for human beings'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='https://lh5.googleusercontent.com/-H3nlHGAfKN0/TYZJODIuekI/AAAAAAAAAaQ/cA8_tVMcqio/s72-c/single.png' height='72' width='72'/><thr:total>11</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-1457220125559134237</id><published>2011-03-11T23:22:00.004+01:00</published><updated>2011-11-17T19:14:40.640+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='performance'/><category scheme='http://www.blogger.com/atom/ns#' term='jmx'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='jmeter'/><category scheme='http://www.blogger.com/atom/ns#' term='monitoring'/><category scheme='http://www.blogger.com/atom/ns#' term='tomcat'/><category scheme='http://www.blogger.com/atom/ns#' term='servlets'/><title type='text'>Tenfold increase in server throughput with Servlet 3.0 asynchronous processing</title><content type='html'>&lt;style type="text/css"&gt;p { margin-bottom: 0.21cm; }h5 { margin-bottom: 0.21cm; page-break-after: avoid; }h5.western { font-family: "Arial",sans-serif; font-size: 11pt; font-weight: bold; }h5.cjk { font-family: "DejaVu Sans"; font-size: 11pt; font-weight: bold; }h5.ctl { font-family: "Lohit Hindi"; font-size: 11pt; font-weight: bold; }a:link { color: rgb(0, 0, 128); text-decoration: underline; }&lt;/style&gt;  &lt;br /&gt;&lt;div style="margin-bottom: 0cm;"&gt;It is not a secret that Java servlet containers aren't particularly suited for handling large amount of concurrent users. Commonly established thread-per-request model effectively limits the number of concurrent connections to the number of concurrently running threads JVM can handle. And because every new thread introduces significant increase of memory footprint and CPU utilization (context switches), handling more than 100-200 concurrent connections seems like a ridiculous idea in Java. At least it was in pre-Servlet 3.0 era.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;In this article we will write scalable and robust file download server with throttled speed limit. Second version, leveraging Servlet 3.0 asynchronous processing feature, will be able to handle &lt;b&gt;ten times bigger load using even less threads&lt;/b&gt;. No additional hardware required, just few wise design decisions.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;h5 class="western"&gt;Token bucket algorithm&lt;/h5&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;span style="font-weight: normal;"&gt;Building a file download servers we have to consciously manage are our resources, especially network bandwidth. We don't want a single client to consume the whole traffic, we might even want to throttle the download limit dynamically at runtime, based on user, time of the day, etc. - and of course everything happens during heavy load. Developers love reinventing the wheel, &lt;/span&gt;&lt;span style="font-weight: normal;"&gt;unfortunately all our requirements are already addressed by absurdly simple &lt;a href="http://en.wikipedia.org/wiki/Token_bucket"&gt;token bucket algorithm&lt;/a&gt;.&lt;/span&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;The explanation in Wikipedia is pretty good, but since we'll adjust the algorithm a bit for our needs, here's even simpler description. First there was a bucket. In this bucket there were uniform tokens. Each token is worth 20 kiB (I will be using real values from our application) of raw data. Every time a client ask for a file, the server tries to take one token from the bucket. If it succeeds, he sends 20 kiB to the client. Repeat last two sentences. What if the server fails to obtain the token because the bucket is already empty? He waits.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;a href="http://draft.blogger.com/post-edit.g?blogID=6753769565491687768&amp;amp;postID=1457220125559134237" name="__DdeLink__0_377059792"&gt;&lt;/a&gt;So where are the tokens coming from? Background process fill the bucket from time to time. Now it becomes clear. If this background process adds 100 new tokens every 100 ms (10 times per second), each worth 20 kiB, the server is capable of sending 20 MiB/s (100 times 20 kiB times 10) max, shared amongst all the clients. Of course if the bucket is full (1000 tokens), new tokens are ignored. This works amazingly well – if bucket is empty, clients are waiting for next bucket filling cycle; and by controlling the bucket capacity we can limit total bandwidth.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;Enough of talking, our simplistic implementation of token bucket starts with an interface (whole source code is available on &lt;a href="https://github.com/nurkiewicz/token-bucket"&gt;GitHub&lt;/a&gt; in &lt;a href="https://github.com/nurkiewicz/token-bucket/blob/global-bucket"&gt;global-bucket&lt;/a&gt; branch):&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public interface TokenBucket {&lt;br /&gt;&lt;br /&gt;    int TOKEN_PERMIT_SIZE = 1024 * 20;&lt;br /&gt;&lt;br /&gt;    void takeBlocking() throws InterruptedException;&lt;br /&gt;    void takeBlocking(int howMany) throws InterruptedException;&lt;br /&gt;&lt;br /&gt;    boolean tryTake();&lt;br /&gt;    boolean tryTake(int howMany);&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;takeBlocking()&lt;/span&gt; methods are waiting synchronously for the token to become available, while &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;tryTake()&lt;/span&gt; are taking token only if it is available, returning true immediately if taken, false otherwise. Fortunately the term bucket is just an abstraction: because tokens are indistinguishable, all we need to implement bucket is an integer counter. But because the bucket is inherently multi-threaded and some waiting is involved, we need more sophisticated mechanism. &lt;a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;Semaphore&lt;/a&gt; seems to be almost ideal:&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;a href="http://draft.blogger.com/post-edit.g?blogID=6753769565491687768&amp;amp;postID=1457220125559134237" name="__DdeLink__2_377059792"&gt;&lt;/a&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Service&lt;br /&gt;@ManagedResource&lt;br /&gt;public class GlobalTokenBucket extends TokenBucketSupport {&lt;br /&gt;&lt;br /&gt;    private final Semaphore bucketSize = new Semaphore(0, false);&lt;br /&gt;&lt;br /&gt;    private volatile int bucketCapacity = 1000;&lt;br /&gt;&lt;br /&gt;    public static final int BUCKET_FILLS_PER_SECOND = 10;&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public void takeBlocking(int howMany) throws InterruptedException {&lt;br /&gt;        bucketSize.acquire(howMany);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public boolean tryTake(int howMany) {&lt;br /&gt;        return bucketSize.tryAcquire(howMany);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;Semaphore&lt;/span&gt; fits exactly to our requirements. &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;bucketSize&lt;/span&gt; represents current amount of tokens in the bucket. &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;bucketCapacity&lt;/span&gt; on the other hand limits the bucket maximum size. It is volatile because it can be modified via JMX (visibility):&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@ManagedAttribute&lt;br /&gt;public int getBucketCapacity() {&lt;br /&gt;    return bucketCapacity;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;@ManagedAttribute&lt;br /&gt;public void setBucketCapacity(int bucketCapacity) {&lt;br /&gt;    isTrue(bucketCapacity &amp;gt;= 0);&lt;br /&gt;    this.bucketCapacity = bucketCapacity;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;As you can see I am using Spring and its support for JMX. Spring framework isn't absolutely necessary in this application, but it brings some nice features. For instance implementing a background process that periodically fills the bucket looks like this:&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Scheduled(fixedRate = 1000 / BUCKET_FILLS_PER_SECOND)&lt;br /&gt;public void fillBucket() {&lt;br /&gt;    final int releaseCount = min(bucketCapacity / BUCKET_FILLS_PER_SECOND, bucketCapacity - bucketSize.availablePermits());&lt;br /&gt;    bucketSize.release(releaseCount);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;For the record: (1) &lt;a href="https://github.com/nurkiewicz/token-bucket/blob/global-bucket/src/main/webapp/WEB-INF/applicationContext.xml"&gt;tiny&lt;/a&gt; XML snippet is required to make &lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-scheduled" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;@Scheduled&lt;/a&gt; annotation working and (2) – this code contains major multi-threading bug that we can ignore for the purposes of this article. It is suppose to fill the bucket up to the maximum value – will it always work?&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;Having token bucket abstraction and very basic implementation we can develop the actual servlet returning files. I am always returning the same fixed file with size of almost 200 kiB):&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@WebServlet(urlPatterns = "/*", name="downloadServletHandler")&lt;br /&gt;public class DownloadServlet extends HttpRequestHandlerServlet {}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;@Service&lt;br /&gt;public class DownloadServletHandler implements HttpRequestHandler {&lt;br /&gt;&lt;br /&gt;    private static final Logger log = LoggerFactory.getLogger(DownloadServletHandler.class);&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private TokenBucket tokenBucket;&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {&lt;br /&gt;        final File file = new File("/home/dev/tmp/ehcache-1.6.2.jar");&lt;br /&gt;        final BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));&lt;br /&gt;        try {&lt;br /&gt;            response.setContentLength((int) file.length());&lt;br /&gt;            sendFile(request, response, input);&lt;br /&gt;        } catch (InterruptedException e) {&lt;br /&gt;            log.error("Download interrupted", e);&lt;br /&gt;        } finally {&lt;br /&gt;            input.close();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void sendFile(HttpServletRequest request, HttpServletResponse response, BufferedInputStream input) throws IOException, InterruptedException {&lt;br /&gt;        byte[] buffer = new byte[TokenBucket.TOKEN_PERMIT_SIZE];&lt;br /&gt;        final ServletOutputStream outputStream = response.getOutputStream();&lt;br /&gt;        for (int count = input.read(buffer); count &amp;gt; 0; count = input.read(buffer)) {&lt;br /&gt;            tokenBucket.takeBlocking();&lt;br /&gt;            outputStream.write(buffer, 0, count);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/support/HttpRequestHandlerServlet.html" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;HttpRequestHandlerServlet&lt;/a&gt; was used here. As simple as can be: read 20 kiB of file, take the token from the bucket (waiting if unavailable), send chunk to the client, repeat until the end of file.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;Believe it or not, this actually works! No matter how many (or how few) clients are concurrently accessing this servlet, total outgoing network bandwidth never exceeds 20 MiB! The algorithm works and I hope you get some basic feeling how to use it. But let's face it – global limit is way too inflexible and kind of lame – single client can actually consume your whole bandwidth.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;So what if we had a separate bucket for each client? Instead of one semaphore – a map? Each client has a separate independent bandwidth limit, so there is no risk of starvation. But there is even more:  &lt;/div&gt;&lt;ul&gt;&lt;li&gt;&lt;div style="margin-bottom: 0cm;"&gt;some clients might be more  privileged, having bigger or no limit at all,&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div style="margin-bottom: 0cm;"&gt;some might be black listed,  resulting in connection rejection or very low throughput&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div style="margin-bottom: 0cm;"&gt;banning IPs, requiring  authentication, cookie/user agent verification, etc.&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div style="margin-bottom: 0cm;"&gt;we might try to correlate  concurrent requests coming from the same client and use the same  bucket for all of them to avoid cheating by opening several  connections. We might also reject subsequent connections&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;div style="margin-bottom: 0cm;"&gt;and much more...&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;Our bucket interface grows allowing the implementation to take advantage of the new possibilities (see branch &lt;a href="https://github.com/nurkiewicz/token-bucket/tree/per-request-synch"&gt;per-request-synch&lt;/a&gt;):&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public interface TokenBucket {&lt;br /&gt;&lt;br /&gt;    void takeBlocking(ServletRequest req) throws InterruptedException;&lt;br /&gt;    void takeBlocking(ServletRequest req, int howMany) throws InterruptedException;&lt;br /&gt;&lt;br /&gt;    boolean tryTake(ServletRequest req);&lt;br /&gt;    boolean tryTake(ServletRequest req, int howMany);&lt;br /&gt;&lt;br /&gt;    void completed(ServletRequest req);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public class PerRequestTokenBucket extends TokenBucketSupport {&lt;br /&gt;&lt;br /&gt;    private final ConcurrentMap&amp;lt;Long, Semaphore &amp;gt; bucketSizeByRequestNo = new ConcurrentHashMap&amp;lt;Long, Semaphore &amp;gt;();&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public void takeBlocking(ServletRequest req, int howMany) throws InterruptedException {&lt;br /&gt;        getCount(req).acquire(howMany);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public boolean tryTake(ServletRequest req, int howMany) {&lt;br /&gt;        return getCount(req).tryAcquire(howMany);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public void completed(ServletRequest req) {&lt;br /&gt;        bucketSizeByRequestNo.remove(getRequestNo(req));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private Semaphore getCount(ServletRequest req) {&lt;br /&gt;        final Semaphore semaphore = bucketSizeByRequestNo.get(getRequestNo(req));&lt;br /&gt;        if (semaphore == null) {&lt;br /&gt;            final Semaphore newSemaphore = new Semaphore(0, false);&lt;br /&gt;            bucketSizeByRequestNo.putIfAbsent(getRequestNo(req), newSemaphore);&lt;br /&gt;            return newSemaphore;&lt;br /&gt;        } else {&lt;br /&gt;            return semaphore;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private Long getRequestNo(ServletRequest req) {&lt;br /&gt;        final Long reqNo = (Long) req.getAttribute(REQUEST_NO);&lt;br /&gt;        if (reqNo == null) {&lt;br /&gt;            throw new IllegalAccessError("Request # not found in: " + req);&lt;br /&gt;        }&lt;br /&gt;        return reqNo;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;The implementation is very similar (full class &lt;a href="https://github.com/nurkiewicz/token-bucket/blob/per-request-synch/src/main/java/com/blogspot/nurkiewicz/download/DownloadServletHandler.java"&gt;here&lt;/a&gt;) except that the single semaphore was replaced by map. I am not using request object itself as a map key for various reasons but a unique request number that I am assigning manually when receiving new connection. Calling completed() is very important, otherwise the map would grow continuously leading to memory leak. All in all, the token bucket implementation haven't changed a lot, also the download servlet is almost the same (except passing request to token bucket). We are now ready for some stress testing!&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;h5 class="western"&gt;Throughput testing&lt;/h5&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;For the testing purposes we will use &lt;a href="http://jakarta.apache.org/jmeter/"&gt;JMeter&lt;/a&gt; with this wonderful set of &lt;a href="http://code.google.com/p/jmeter-plugins/"&gt;plugins&lt;/a&gt;. During the 20-minute testing session we warm up our server firing up one new thread (concurrent connection) every 6 seconds to reach 100 threads after 10 minutes. For the next ten minutes we will keep 100 concurrent connections to see how stable the server works:&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh5.googleusercontent.com/-uKjs32ELGeY/TXqdMttwQiI/AAAAAAAAAZ0/9JCcQtXSyUM/s1600/Active+Threads+Over+Time.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="197" src="https://lh5.googleusercontent.com/-uKjs32ELGeY/TXqdMttwQiI/AAAAAAAAAZ0/9JCcQtXSyUM/s320/Active+Threads+Over+Time.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;b&gt;Important note&lt;/b&gt;: I artificially lowered the number of HTTP worker threads to &lt;b&gt;10&lt;/b&gt; in Tomcat (7.0.10 tested). This is a far from real configuration, but I wanted to emphasize some phenomena that occur with high load compared to server capabilities. With default pool size I would need several client machines running distributed JMeter session to generate enough traffic. If you have a server farm or couple of servers in the cloud (as opposed to my 3-year-old laptop), I would be delighted to see the results in more realistic environment.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;Remembering how many HTTP worker threads are available in Tomcat, response times over time are far from satisfactory:&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh6.googleusercontent.com/--CWo69ehvOw/TXqdYbf-xdI/AAAAAAAAAZ4/2J3BTeW5Kcs/s1600/Response+Times+Over+Time.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="197" src="https://lh6.googleusercontent.com/--CWo69ehvOw/TXqdYbf-xdI/AAAAAAAAAZ4/2J3BTeW5Kcs/s320/Response+Times+Over+Time.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;Please note the plateau at the beginning of the test: after about a minute (hint: when the number of concurrent connections exceeds 10) response times are skyrocketing to stabilize at around 10 seconds after 10 minutes (number of concurrent connections reaches one hundred). Once again: the same behavior would occur with 100 worker threads and 1000 concurrent connections – it's just a matter of scale. The response latencies graph (time between sending request and receiving first lines of response) clears any doubts:&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh6.googleusercontent.com/-mkl08vVSROM/TXqdkbc6-yI/AAAAAAAAAZ8/cXi15QU6rqE/s1600/Response+Latencies+Over+Time.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="197" src="https://lh6.googleusercontent.com/-mkl08vVSROM/TXqdkbc6-yI/AAAAAAAAAZ8/cXi15QU6rqE/s320/Response+Latencies+Over+Time.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;Below magical 10 threads our application responds almost instantly. This is really important for clients as receiving only headers  (especially &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;Content-Type&lt;/span&gt; and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;Content-Length&lt;/span&gt;) allows them to more accurately inform the user what is going on. So what is the reason of Tomcat waiting with the response? No magic here really. We have only 10 threads and each connection requires one thread, so Tomcat (and any other pre-Servlet 3.0 container) handles 10 clients while the remaining 90 are... queued. The moment one of the 10 lucky ones is done, one connection from the queue is taken. This explains average 9 second latency whilst the servlet needs only 1 second to serve the request (200 kiB with 20 kiB/s limit). If you are still not convinced, Tomcat provides nice JMX indicators showing how many threads are occupied and how many requests are queued:&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh4.googleusercontent.com/-9o9aY_HxOVk/TXqdqoF_wFI/AAAAAAAAAaA/sTAlBHf1zKY/s1600/zrzut_ekranu-1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="220" src="https://lh4.googleusercontent.com/-9o9aY_HxOVk/TXqdqoF_wFI/AAAAAAAAAaA/sTAlBHf1zKY/s320/zrzut_ekranu-1.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;With traditional servlets there is nothing we can do. Throughput is horrible but increasing the total number of threads is not an option (think: from 100 to 1000). But you don't actually need a profiler to discover that threads aren't the true bottleneck here. Look carefully at DownloadServletHandler, where do you think most of the time is spent? Reading a file? Sending data back to the client? No, the servlet waits... And then waits even more. Non-productively hanging on semaphore – thankfully CPU is not harmed, but what if it was implemented using busy waiting? Luckily Tomcat 7 finally supports...&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;h5 class="western"&gt;Servlet 3.0 asynchronous processing&lt;/h5&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;We are &lt;i&gt;this&lt;/i&gt;&lt;span style="font-style: normal;"&gt; close to increase our server capacity by &lt;/span&gt;&lt;span style="font-style: normal;"&gt;an order of magnitude, but some non-trivial changes are required (see &lt;a href="https://github.com/nurkiewicz/token-bucket"&gt;master&lt;/a&gt; branch). First, download servlet needs to be marked as asynchronous (OK, this is &lt;/span&gt;&lt;span style="font-style: normal;"&gt;still &lt;/span&gt;&lt;span style="font-style: normal;"&gt;trivial):&lt;/span&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;span style="font-style: normal;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@WebServlet(urlPatterns = "/*", name="downloadServletHandler", asyncSupported = true)&lt;br /&gt;public class DownloadServlet extends HttpRequestHandlerServlet {}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;The main change occurs in download handler. Instead of sending the whole file in a loop with lots of waiting (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;takeBlocking()&lt;/span&gt;) involved, we are splitting the loop into separate iterations, each wrapped inside &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;Callable&lt;/span&gt;. Now we will utilize a small thread pool that will be shared by all awaiting connections. Each task in the pool is very simple: instead of waiting for a token, it asks for it in a non-blocking fashion (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;tryTake()&lt;/span&gt;). If the token is available, piece of the file is sent to the client (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;sendChunkWorthOneToken()&lt;/span&gt;). If the token is not available (bucket is empty), nothing happens. No matter whether the token was available or not, the task resubmits itself to the queue for further processing (this is essentially very fancy, multi-threaded loop). Because there is only one pool, the task lands at the end of the queue allowing other connections to be served.  &lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Service&lt;br /&gt;public class DownloadServletHandler implements HttpRequestHandler {&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private TokenBucket tokenBucket;&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private ThreadPoolTaskExecutor downloadWorkersPool;&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {&lt;br /&gt;        final File file = new File("/home/dev/tmp/ehcache-1.6.2.jar");&lt;br /&gt;        response.setContentLength((int) file.length());&lt;br /&gt;        final BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));&lt;br /&gt;        final AsyncContext asyncContext = request.startAsync(request, response);&lt;br /&gt;        downloadWorkersPool.submit(new DownloadChunkTask(asyncContext, input));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private class DownloadChunkTask implements Callable&amp;lt;Void&amp;gt; {&lt;br /&gt;&lt;br /&gt;        private final BufferedInputStream fileInputStream;&lt;br /&gt;        private final byte[] buffer = new byte[TokenBucket.TOKEN_PERMIT_SIZE];&lt;br /&gt;        private final AsyncContext ctx;&lt;br /&gt;&lt;br /&gt;        public DownloadChunkTask(AsyncContext ctx, BufferedInputStream fileInputStream) throws IOException {&lt;br /&gt;            this.ctx = ctx;&lt;br /&gt;            this.fileInputStream = fileInputStream;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        @Override&lt;br /&gt;        public Void call() throws Exception {&lt;br /&gt;            try {&lt;br /&gt;                if (tokenBucket.tryTake(ctx.getRequest())) {&lt;br /&gt;                    sendChunkWorthOneToken();&lt;br /&gt;                } else&lt;br /&gt;                    downloadWorkersPool.submit(this);&lt;br /&gt;            } catch (Exception e) {&lt;br /&gt;                log.error("", e);&lt;br /&gt;                done();&lt;br /&gt;            }&lt;br /&gt;            return null;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void sendChunkWorthOneToken() throws IOException {&lt;br /&gt;            final int bytesCount = fileInputStream.read(buffer);&lt;br /&gt;            ctx.getResponse().getOutputStream().write(buffer, 0, bytesCount);&lt;br /&gt;            if (bytesCount &amp;lt; buffer.length)&lt;br /&gt;                done();&lt;br /&gt;            else&lt;br /&gt;                downloadWorkersPool.submit(this);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void done() throws IOException {&lt;br /&gt;            fileInputStream.close();&lt;br /&gt;            tokenBucket.completed(ctx.getRequest());&lt;br /&gt;            ctx.complete();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;I am leaving the details of Servlet 3.0 API, there are plenty of less sophisticated examples throughout the Internet. Just remember to call &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;startAsync()&lt;/span&gt; and work with returned &lt;a href="http://download.oracle.com/javaee/6/api/javax/servlet/AsyncContext.html"&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;AsyncContext&lt;/span&gt;&lt;/a&gt; instead of plain request and response.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;BTW creating a thread pool using Spring is childishly easy (and we get nice thread names as opposed to &lt;a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;Executors&lt;/a&gt; and &lt;a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html" style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;ExecutorService&lt;/a&gt;):&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;task:executor id="downloadWorkersPool" pool-size="1"/&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;That's right, one thread is enough to serve one hundred concurrent clients. See for yourself (the amount of HTTP worker threads is still 10 and yes, the scale is in milliseconds):&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh5.googleusercontent.com/-mV7FcIdrz5o/TXqdyW9t1lI/AAAAAAAAAaE/3efNVR-XJyM/s1600/Response+Times+Over+Time.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="197" src="https://lh5.googleusercontent.com/-mV7FcIdrz5o/TXqdyW9t1lI/AAAAAAAAAaE/3efNVR-XJyM/s320/Response+Times+Over+Time.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="https://lh6.googleusercontent.com/-vvhCnFH2ows/TXqd52qQeeI/AAAAAAAAAaI/6qwTgyfeseM/s1600/Response+Latencies+Over+Time.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="197" src="https://lh6.googleusercontent.com/-vvhCnFH2ows/TXqd52qQeeI/AAAAAAAAAaI/6qwTgyfeseM/s320/Response+Latencies+Over+Time.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;As you can see, response times when one hundred clients are downloading a file concurrently are only about 5% higher compared to the system with almost no load. Also response latencies aren't particularly harmed by increasing load. I can't push the server even further due to my limited hardware resources, but I have reasons to believe that this simple application would handle even twice as more connection: both HTTP threads and download worker thread weren't fully utilized during the whole test. This also means that we have increased our server capacity 10 times without even using all the threads!&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;Hope you enjoyed this article. Of course not every use case can be scaled so easily, but next time you'll notice your servlet is mainly waiting – don't waste HTTP threads and consider servlet 3.0 asynchronous processing. And test, measure and compare! The complete application source codes are &lt;a href="https://github.com/nurkiewicz/token-bucket"&gt;available&lt;/a&gt; (look at different branches), including JMeter test plan.&lt;/div&gt;&lt;div style="margin-bottom: 0cm;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;h5 class="western"&gt;Areas of improvement&lt;/h5&gt;There are still several places that require attention and improvement. If you want to, don't hesitate, fork, modify and test:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;While profiling I discovered that in more than 80% of  executions &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;DownloadChunkTask&lt;/span&gt; does not acquire a token and only  reschedules itself. This is an awful waste of CPU time that can be  fixed quite easily (how?)&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Consider opening a file and sending content length in a  worker thread rather than in an HTTP thread (before starting  asynchronous context)&lt;br /&gt;&lt;/li&gt;&lt;li&gt;How can one implement global limit on top of bandwidth limits  per request? You have at least couple of choice: either limit the  size of download workers pool queue and reject executions or wrap &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt; PerRequestTokenBucket&lt;/span&gt; with reimplemented &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;GlobalTokenBucket&lt;/span&gt;  (decorator pattern)&lt;br /&gt;&lt;/li&gt;&lt;li&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;TokenBucket.tryTake()&lt;/span&gt; method does clearly violate  &lt;a href="http://en.wikipedia.org/wiki/Command-query_separation"&gt;Command-query separation&lt;/a&gt; principle. Could you suggest how it should  look like to follow it? Why it is so hard?&lt;br /&gt;&lt;/li&gt;&lt;li&gt;I am aware that my test constantly reads the same small file,  so the I/O performance impact is minimal. But in real life scenario  some caching layer would have certainly be applied on top of disk  storage. So the difference is not that big (now the application uses  very small amount of memory, lots of place for cache)&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h5 class="western"&gt;Lessons learned&lt;/h5&gt;&lt;ul&gt;&lt;li&gt;Loopback interface is not infinitely fast. In fact on my  machine localhost was incapable of processing more than 80 MiB/s.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;I don't use plain request object as a key in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt; bucketSizeByRequestNo&lt;/span&gt;. First of all, there are no guarantees on  &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;equals()&lt;/span&gt; and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;hashCode()&lt;/span&gt; for this interface. And more importantly –  read the next point...&lt;br /&gt;&lt;/li&gt;&lt;li&gt;With servlets 3.0 when processing the request you have to  call completed() explicitly to flush and close the connection.  Obviously after calling this method request and response objects are  useless. What wasn't obvious (and I learned that the hard why) is  that Tomcat reuses request objects (pooling) and some of their  contents for subsequent connections. This means that the following  code is incorrect and dangerous, possibly resulting in  accessing/corrupting other requests' attributes or even session (?!?)&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;ctx.complete();&lt;br /&gt;ctx.getRequest().getAttribute("SOME_KEY");&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;EDIT: Watch out for asynchronous executions timeouts. After creating an asynchronous invocation using &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;startAsync()&lt;/span&gt; on Tomcat by default you have 30 seconds. After that Tomcat will kill your connection and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;getRequest()&lt;/span&gt; will suddenly start returning &lt;span style="font-family: &amp;quot;Courier New&amp;quot;,&amp;quot;Courier&amp;quot;,monospace;"&gt;null&lt;/span&gt; (not very helpful). Luckily timeout can be customized and you can listen for timeout events easily (see this &lt;a href="https://github.com/nurkiewicz/token-bucket/commit/36023cea8dbbeed7d224b5e0237b2360981b337c"&gt;commit&lt;/a&gt;).&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-1457220125559134237?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/1457220125559134237/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/03/tenfold-increase-in-server-throughput.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/1457220125559134237'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/1457220125559134237'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/03/tenfold-increase-in-server-throughput.html' title='Tenfold increase in server throughput with Servlet 3.0 asynchronous processing'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='https://lh5.googleusercontent.com/-uKjs32ELGeY/TXqdMttwQiI/AAAAAAAAAZ0/9JCcQtXSyUM/s72-c/Active+Threads+Over+Time.png' height='72' width='72'/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-101753246111762370</id><published>2011-01-11T23:13:00.004+01:00</published><updated>2011-11-17T19:41:29.569+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='servlets'/><title type='text'>Spring framework without XML... At all!</title><content type='html'>&lt;div&gt;First, there was EJB 2.1 with countless XML files all over. It won't be such a big exaggeration to say that for every line of business code you had to create at least 10 lines of framework code and two pages of XML. Local and remote interfaces, manual JNDI lookup, triply nested try-catches, checked &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;RemoteExceptions&lt;/span&gt; everywhere... this was &lt;b&gt;enterprise&lt;/b&gt;. There were even &lt;a href="http://xdoclet.sourceforge.net/xdoclet/status.html"&gt;tools&lt;/a&gt; to generate some of this boilerplate automatically.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Then couple of guys came and created &lt;a href="http://springframework.org/"&gt;Spring framework&lt;/a&gt;. After being forced to cast by obscure &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;PortableRemoteObject.narrow()&lt;/span&gt; it was like taking a deep breath of fresh air, like writing poetry after working in coal mine. Time went by (BTW do you remember how many years ago was the last major JRE release?) and Sun learnt their lesson. EJB 3.0 was even simpler compared to Spring, XML-free, annotations, dependency injection. 3.1 was another great step toward simplicity, being more and more often compared to Spring. Logically current state of the art EJB specification might be considered as a subset of what Spring offers, I am actually surprised why there is no EJB spec. implementation in plain Spring (oh, &lt;a href="http://www.springsource.com/pitchfork"&gt;wait...&lt;/a&gt;), considering its out-of-the-box support for JPA 1.0/2.0, JSR-250, JSR-330, JAX-WS/RS compatible solutions and others. But even though, Spring framework is nowadays perceived as a slow, heavyweight and hard to maintain, mainly due to reliance on XML descriptors. Once simple, now Spring is a whipping boy in the JEE framework battle.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I don't like politics, I won't defend my beloved framework writing lengthy essays. Instead I will take simple, but not trivial Spring application and quickly rewrite it so that it won't use XML. Not reduce the amount of XML, not leave only few untouchable lines. &lt;b&gt;No XML - at all&lt;/b&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;For the purposes of this article I created very simple Spring web &lt;a href="https://github.com/nurkiewicz/spring-no-xml"&gt;application&lt;/a&gt; (base version under &lt;a href="https://github.com/nurkiewicz/spring-no-xml/tree/xml"&gt;xml&lt;/a&gt; branch, final on &lt;a href="https://github.com/nurkiewicz/spring-no-xml"&gt;master&lt;/a&gt; on my GitHub &lt;a href="https://github.com/nurkiewicz"&gt;account&lt;/a&gt;) using JDBC, JMS and JMX, just not to make things trivial. Every change I made to the source code will be reflected in a separate commit to this repository. Step by step I will be removing XML configuration until there will be no Spring XML left. This is where we start:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;       xmlns:tx="http://www.springframework.org/schema/tx"&lt;br /&gt;       xmlns:amq="http://activemq.apache.org/schema/core"&lt;br /&gt;       xmlns:context="http://www.springframework.org/schema/context"&lt;br /&gt;       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&lt;br /&gt;            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd&lt;br /&gt;             http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.4.2.xsd&lt;br /&gt;             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context:mbean-export /&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="fooService" class="com.blogspot.nurkiewicz.FooService"&amp;gt;&lt;br /&gt;        &amp;lt;property name="jmsOperations" ref="jmsTemplate" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="fooRequestProcessor" class="com.blogspot.nurkiewicz.FooRequestProcessor"&amp;gt;&lt;br /&gt;        &amp;lt;property name="fooRepository" ref="fooRepository" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="fooRepository" class="com.blogspot.nurkiewicz.FooRepository" init-method="init"&amp;gt;&lt;br /&gt;        &amp;lt;property name="jdbcOperations" ref="jdbcTemplate" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;!-- JDBC --&amp;gt;&lt;br /&gt;    &amp;lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&amp;gt;&lt;br /&gt;        &amp;lt;property name="driverClassName" value="org.h2.Driver" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="url" value="jdbc:h2:~/workspace/h2/spring-noxmal;DB_CLOSE_ON_EXIT=FALSE;TRACE_LEVEL_FILE=4;AUTO_SERVER=TRUE" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="username" value="sa" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="password" value="" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg ref="dataSource" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg ref="dataSource" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;tx:annotation-driven /&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;!-- JMS --&amp;gt;&lt;br /&gt;    &amp;lt;bean id="jmsConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;            &amp;lt;bean class="org.apache.activemq.ActiveMQConnectionFactory"&amp;gt;&lt;br /&gt;                &amp;lt;property name="brokerURL" value="tcp://localhost:61616" /&amp;gt;&lt;br /&gt;            &amp;lt;/bean&amp;gt;&lt;br /&gt;        &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;amq:queue id="requestsQueue" physicalName="requests" /&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg ref="jmsConnectionFactory" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="defaultDestination" ref="requestsQueue" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"&amp;gt;&lt;br /&gt;        &amp;lt;property name="connectionFactory" ref="jmsConnectionFactory" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="destination" ref="requestsQueue" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="sessionTransacted" value="true"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="concurrentConsumers" value="5"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="messageListener"&amp;gt;&lt;br /&gt;            &amp;lt;bean class="org.springframework.jms.listener.adapter.MessageListenerAdapter"&amp;gt;&lt;br /&gt;                &amp;lt;constructor-arg ref="fooRequestProcessor" /&amp;gt;&lt;br /&gt;                &amp;lt;property name="defaultListenerMethod" value="process"/&amp;gt;&lt;br /&gt;            &amp;lt;/bean&amp;gt;&lt;br /&gt;        &amp;lt;/property&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;Few user beans, JDBC including transaction support and utilizing JMS, both sending and receiving. The details of this application aren't that important: one of the beans is exposed via JMX, it sends JMS message, then that message is received and persisted in database.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The most commonly used and well established approach to reduce XML boilerplate in Spring is to use &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@Service&lt;/span&gt; and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@Resource&lt;/span&gt; annotations together with introducing &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;&amp;lt;context:component-scan/&amp;gt;&lt;/span&gt; for user beans (&lt;a href="https://github.com/nurkiewicz/spring-no-xml/commit/69b0a64b23bdb1a913a5dce81abb4c775d98db7d"&gt;show changes&lt;/a&gt;):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;       xmlns:tx="http://www.springframework.org/schema/tx"&lt;br /&gt;       xmlns:amq="http://activemq.apache.org/schema/core"&lt;br /&gt;       xmlns:context="http://www.springframework.org/schema/context"&lt;br /&gt;       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&lt;br /&gt;            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd&lt;br /&gt;             http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.4.2.xsd&lt;br /&gt;             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context:mbean-export /&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context:component-scan base-package="com.blogspot.nurkiewicz"/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;!-- JDBC --&amp;gt;&lt;br /&gt;    &amp;lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&amp;gt;&lt;br /&gt;        &amp;lt;property name="driverClassName" value="org.h2.Driver" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="url" value="jdbc:h2:~/workspace/h2/spring-noxmal;DB_CLOSE_ON_EXIT=FALSE;TRACE_LEVEL_FILE=4;AUTO_SERVER=TRUE" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="username" value="sa" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="password" value="" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg ref="dataSource" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg ref="dataSource" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;tx:annotation-driven /&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;!-- JMS --&amp;gt;&lt;br /&gt;    &amp;lt;bean id="jmsConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;            &amp;lt;bean class="org.apache.activemq.ActiveMQConnectionFactory"&amp;gt;&lt;br /&gt;                &amp;lt;property name="brokerURL" value="tcp://localhost:61616" /&amp;gt;&lt;br /&gt;            &amp;lt;/bean&amp;gt;&lt;br /&gt;        &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;amq:queue id="requestsQueue" physicalName="requests" /&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg ref="jmsConnectionFactory" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="defaultDestination" ref="requestsQueue" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"&amp;gt;&lt;br /&gt;        &amp;lt;property name="connectionFactory" ref="jmsConnectionFactory" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="destination" ref="requestsQueue" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="sessionTransacted" value="true"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="concurrentConsumers" value="5"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="messageListener"&amp;gt;&lt;br /&gt;            &amp;lt;bean class="org.springframework.jms.listener.adapter.MessageListenerAdapter"&amp;gt;&lt;br /&gt;                &amp;lt;constructor-arg ref="fooRequestProcessor" /&amp;gt;&lt;br /&gt;                &amp;lt;property name="defaultListenerMethod" value="process"/&amp;gt;&lt;br /&gt;            &amp;lt;/bean&amp;gt;&lt;br /&gt;        &amp;lt;/property&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;10 lines less of XML, not very impressive...  And what about user beans?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Service&lt;br /&gt;public class FooRepository {&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private JdbcOperations jdbcOperations;&lt;br /&gt;&lt;br /&gt;    @PostConstruct&lt;br /&gt;    public void init() {&lt;br /&gt;        log.info("Database server time is: {}", jdbcOperations.queryForObject("SELECT CURRENT_TIMESTAMP", Date.class));&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    //...&lt;br /&gt;    &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Setters were replaced by annotations, init-method as well. Now what? Majority of annotation-enthusiasts stop here, but as you can see, there is plenty of XML left... The only problem is – how to annotate third-party classes like connection pools, Spring-provided support classes, etc.?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The real fun begins here. First we will get rid of the data source XML and replace it with... (&lt;a href="https://github.com/nurkiewicz/spring-no-xml/commit/47cd52c77aed743c8a9326cd24b2b8e88051b173"&gt;show changes&lt;/a&gt;):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;import javax.sql.DataSource;&lt;br /&gt;import org.apache.commons.dbcp.BasicDataSource;&lt;br /&gt;import org.springframework.context.annotation.Bean;&lt;br /&gt;import org.springframework.context.annotation.Configuration;&lt;br /&gt;&lt;br /&gt;@Configuration&lt;br /&gt;public class ContextConfiguration {&lt;br /&gt;&lt;br /&gt;    @Bean&lt;br /&gt;    public DataSource dataSource() {&lt;br /&gt;        final BasicDataSource ds = new BasicDataSource();&lt;br /&gt;        ds.setDriverClassName("org.h2.Driver");&lt;br /&gt;        ds.setUrl("jdbc:h2:~/workspace/h2/spring-noxmal;DB_CLOSE_ON_EXIT=FALSE;TRACE_LEVEL_FILE=4;AUTO_SERVER=TRUE");&lt;br /&gt;        ds.setUsername("sa");&lt;br /&gt;        return ds;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/api/org/springframework/context/annotation/Configuration.html"&gt;@Configuration&lt;/a&gt;, &lt;a href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/api/org/springframework/context/annotation/Bean.html"&gt;@Bean&lt;/a&gt;, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;dataSource()&lt;/span&gt;, &lt;i&gt;what the...?!?&lt;/i&gt; It works exactly the way you think: Spring finds the  &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;ContextConfiguration&lt;/span&gt; class and examines all methods annotated with &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@Bean&lt;/span&gt;. Each and every method like that is treated equally to &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;&amp;lt;bean...&amp;gt;&lt;/span&gt; XML declaration (there are even &lt;a href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/api/org/springframework/context/annotation/Scope.html"&gt;@Scope&lt;/a&gt;, &lt;a href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/api/org/springframework/context/annotation/DependsOn.html"&gt;@DependsOn&lt;/a&gt; and &lt;a href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/api/org/springframework/context/annotation/Lazy.html"&gt;@Lazy&lt;/a&gt; annotations), so we can remove the dataSource bean declaration from XML. Actually, we can get rid of &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;JdbcTemplate&lt;/span&gt; and transaction manager as well (&lt;a href="https://github.com/nurkiewicz/spring-no-xml/commit/1be359959999f12a5913db96ece82210acf60452"&gt;show changes&lt;/a&gt;):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Bean&lt;br /&gt;public JdbcOperations jdbcOperations() {&lt;br /&gt;    return new JdbcTemplate(dataSource());&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;@Bean&lt;br /&gt;public PlatformTransactionManager transactionManager() {&lt;br /&gt;    return new DataSourceTransactionManager(dataSource());&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Look closely how easily one can inject data source bean to other beans. You have a method that creates data source on one hand, on the other hand two methods require data source to be injected (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;JdbcTemplate&lt;/span&gt; and transaction manager). It can't be easier, this is probably the way your girlfriend would implement dependency injection (&lt;a href="http://code.google.com/p/google-guice"&gt;Guice&lt;/a&gt;, anyone?)&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;One thing should bother you though... If you call &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;dataSource()&lt;/span&gt; twice, wouldn't this mean that you have just created two separate, independent &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;DataSource&lt;/span&gt; instances? Clearly not what was intended... Well, it bothered me (see &lt;a href="http://blog.springsource.com/2011/01/07/green-beans-getting-started-with-spring-in-your-service-tier/#comments"&gt;comments&lt;/a&gt;), but it seems that once again Spring is a one clever beast. Not finding &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@Scope&lt;/span&gt; annotation it assumes data source should be a singleton. So it applies some CGLIB-proxying-magic around &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;dataSource()&lt;/span&gt; method transparently and protects it from being called more than once. Or, more precisely, you think you can call it many times, but all subsequent calls will return already factored bean, not even reaching the actual implementation. Nice!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;All in all, this shortened our XML configuration to this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;       xmlns:tx="http://www.springframework.org/schema/tx"&lt;br /&gt;       xmlns:amq="http://activemq.apache.org/schema/core"&lt;br /&gt;       xmlns:context="http://www.springframework.org/schema/context"&lt;br /&gt;       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&lt;br /&gt;            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd&lt;br /&gt;             http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.4.2.xsd&lt;br /&gt;             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context:mbean-export /&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context:component-scan base-package="com.blogspot.nurkiewicz"/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;!-- JDBC --&amp;gt;&lt;br /&gt;    &amp;lt;tx:annotation-driven /&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;!-- JMS --&amp;gt;&lt;br /&gt;    &amp;lt;bean id="jmsConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;            &amp;lt;bean class="org.apache.activemq.ActiveMQConnectionFactory"&amp;gt;&lt;br /&gt;                &amp;lt;property name="brokerURL" value="tcp://localhost:61616" /&amp;gt;&lt;br /&gt;            &amp;lt;/bean&amp;gt;&lt;br /&gt;        &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;amq:queue id="requestsQueue" physicalName="requests" /&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"&amp;gt;&lt;br /&gt;        &amp;lt;constructor-arg ref="jmsConnectionFactory" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="defaultDestination" ref="requestsQueue" /&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"&amp;gt;&lt;br /&gt;        &amp;lt;property name="connectionFactory" ref="jmsConnectionFactory" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="destination" ref="requestsQueue" /&amp;gt;&lt;br /&gt;        &amp;lt;property name="sessionTransacted" value="true"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="concurrentConsumers" value="5"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="messageListener"&amp;gt;&lt;br /&gt;            &amp;lt;bean class="org.springframework.jms.listener.adapter.MessageListenerAdapter"&amp;gt;&lt;br /&gt;                &amp;lt;constructor-arg ref="fooRequestProcessor" /&amp;gt;&lt;br /&gt;                &amp;lt;property name="defaultListenerMethod" value="process"/&amp;gt;&lt;br /&gt;            &amp;lt;/bean&amp;gt;&lt;br /&gt;        &amp;lt;/property&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You my stop now and think how would you rewrite the remaining XML-defined beans into Java. Don't worry, there is no catch here – it as straightforward as it should be (&lt;a href="https://github.com/nurkiewicz/spring-no-xml/commit/ac2d5a09a247366e89daa27c3f6230f27df8043c"&gt;see changes&lt;/a&gt;).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Bean&lt;br /&gt;public ConnectionFactory jmsConnectionFactory() {&lt;br /&gt;    final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();&lt;br /&gt;    factory.setBrokerURL("tcp://localhost:61616");&lt;br /&gt;    return new PooledConnectionFactory(factory);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;@Bean&lt;br /&gt;public Queue requestsQueue() {&lt;br /&gt;    return new ActiveMQQueue("requests");&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;@Bean&lt;br /&gt;public JmsOperations jmsOperations() {&lt;br /&gt;    final JmsTemplate jmsTemplate = new JmsTemplate(jmsConnectionFactory());&lt;br /&gt;    jmsTemplate.setDefaultDestination(requestsQueue());&lt;br /&gt;    return jmsTemplate;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Declaration of &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;DefaultMessageListenerContainer&lt;/span&gt; contains some anonymous inner bean, that is being used only once within parent bean. So private method is OK (&lt;a href="https://github.com/nurkiewicz/spring-no-xml/commit/8873348272e0f6ae7f6929d9d2062eae5e49d2b9"&gt;see changes&lt;/a&gt;):&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Bean&lt;br /&gt;public AbstractJmsListeningContainer jmsContainer() {&lt;br /&gt;    final DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();&lt;br /&gt;    container.setConnectionFactory(jmsConnectionFactory());&lt;br /&gt;    container.setDestination(requestsQueue());&lt;br /&gt;    container.setSessionTransacted(true);&lt;br /&gt;    container.setConcurrentConsumers(5);&lt;br /&gt;    container.setMessageListener(messageListenerAdapter());&lt;br /&gt;    return container;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private MessageListenerAdapter messageListenerAdapter() {&lt;br /&gt;    final MessageListenerAdapter adapter = new MessageListenerAdapter(fooRequestProcessor);&lt;br /&gt;    adapter.setDefaultListenerMethod("process");&lt;br /&gt;    return adapter;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;Not much to be said, mainly because Spring plain Java configuration is so trivial and straightforward – and the code may speak for itself. In case you've got lost, after so many transformations we are now here:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;       xmlns:tx="http://www.springframework.org/schema/tx"&lt;br /&gt;       xmlns:context="http://www.springframework.org/schema/context"&lt;br /&gt;       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&lt;br /&gt;            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd&lt;br /&gt;             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context:mbean-export /&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context:component-scan base-package="com.blogspot.nurkiewicz"/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;tx:annotation-driven /&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;To be honest, it wasn't very hard, but the remaining few lines of XML were especially difficult to remove. Believe me, you don't want to go the same path I had to choose to replace these nice little namespace-powered declarations. But after several minutes, few unsuccessful experiments and lots of Spring code reviewed I finally removed JMX (&lt;a href="https://github.com/nurkiewicz/spring-no-xml/commit/8457d4c081b08d4308c2cb90e4def1c67e02cab9"&gt;see changes&lt;/a&gt;) and transaction (&lt;a href="https://github.com/nurkiewicz/spring-no-xml/commit/83033cf328d70dc41fec510b3f831e286af33301"&gt;see changes&lt;/a&gt;) declarations. Looks innocent and I am glad you won't have to dig through Spring code base to reinvent it:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Bean&lt;br /&gt;public AnnotationMBeanExporter annotationMBeanExporter() {&lt;br /&gt;    return new AnnotationMBeanExporter();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;@Bean&lt;br /&gt;public TransactionAttributeSource annotationTransactionAttributeSource() {&lt;br /&gt;    return new AnnotationTransactionAttributeSource();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;@Bean&lt;br /&gt;public TransactionInterceptor transactionInterceptor() {&lt;br /&gt;    return new TransactionInterceptor(transactionManager(), annotationTransactionAttributeSource());&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This would be it. All we have left is this tiny XML bootstrap declaration that instructs Spring where to find all of the beans and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;web.xml&lt;/span&gt; snippet making web container to actually start the Spring application context:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;context:component-scan base-package="com.blogspot.nurkiewicz"/&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;web-app xmlns="http://java.sun.com/xml/ns/javaee"&lt;br /&gt;         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"&lt;br /&gt;         version="3.0"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;listener&amp;gt;&lt;br /&gt;        &amp;lt;listener-class&amp;gt;org.springframework.web.context.ContextLoaderListener&amp;lt;/listener-class&amp;gt;&lt;br /&gt;    &amp;lt;/listener&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/web-app&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;There is no other way to start Spring properly in web-environment, after all you have to make the web-container aware of the Spring framework somehow. I know, I know, I promised no XML at all. So I lied, I'm sorry, OK? Big deal... Wait, wait, just kidding :-), we will get rid of this bootstrap XML completely in seconds. Well, depending how fast can you download the newest &lt;a href="http://tomcat.apache.org/download-70.cgi"&gt;Tomcat 7&lt;/a&gt; or other &lt;a href="http://jcp.org/en/jsr/detail?id=315"&gt;JSR 315&lt;/a&gt; (among insiders known as Servlet 3.0) capable web container...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;Web fragments&lt;/i&gt; is a technology allowing seamless integration of various web frameworks with servlet containers. If you worked with several frameworks, they all require registering specific servlet, filter or listener in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;web.xml&lt;/span&gt;. Most of the time this is the only servlet dependency and Spring is no exception. The idea behind web fragments tries to liberate the end developers from this requirement. Servlet 3.0 compatible container should scan all JARs within &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;/WEB-INF/lib &lt;/span&gt;directory in WAR artifact and if any JAR contains &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;web-fragment.xml&lt;/span&gt; file inside its &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;/META-INF&lt;/span&gt; directory, it will be included in final web.xml.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You realize where I am going? What if we could create such a small web-fragment JAR only for XML-free Spring startup? This is the typical, far from complete WAR file structure:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: plain"&gt;&lt;br /&gt;.&lt;br /&gt;|-- META-INF&lt;br /&gt;`-- WEB-INF&lt;br /&gt;    |-- classes&lt;br /&gt;    |   |-- com&lt;br /&gt;    |   |   `-- blogspot&lt;br /&gt;    |   |       `-- nurkiewicz&lt;br /&gt;    |   |           |-- ContextConfiguration.class&lt;br /&gt;    |   |           |-- FooRepository.class&lt;br /&gt;    |   |           |-- FooRequestProcessor.class&lt;br /&gt;    |   |           |-- FooService$1.class&lt;br /&gt;    |   |           `-- FooService.class&lt;br /&gt;    |   `-- logback.xml&lt;br /&gt;    |-- lib&lt;br /&gt;    |   |-- spring-web-3.0.5.RELEASE.jar&lt;br /&gt;    |   |-- spring-web-fragment-0.0.1-SNAPSHOT.jar&lt;br /&gt;    |   |   `-- META-INF&lt;br /&gt;    |   |       |-- MANIFEST.MF&lt;br /&gt;    |   |       |-- web-fragment-context.xml&lt;br /&gt;    |   |       `-- web-fragment.xml&lt;br /&gt;    |   `-- spring-beans-3.0.5.RELEASE.jar&lt;br /&gt;    `-- web.xml&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The sole purpose of &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;spring-web-fragment-*.jar&lt;/span&gt; is to provide &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;web-fragment.xml&lt;/span&gt; file for the container, being the bootstrap between servlet environment and Spring framework:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;web-fragment xmlns="http://java.sun.com/xml/ns/javaee"&lt;br /&gt;              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-fragment_3_0.xsd"&lt;br /&gt;              version="3.0"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;listener&amp;gt;&lt;br /&gt;        &amp;lt;listener-class&amp;gt;org.springframework.web.context.ContextLoaderListener&amp;lt;/listener-class&amp;gt;&lt;br /&gt;    &amp;lt;/listener&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context-param&amp;gt;&lt;br /&gt;        &amp;lt;param-name&amp;gt;contextConfigLocation&amp;lt;/param-name&amp;gt;&lt;br /&gt;        &amp;lt;param-value&amp;gt;classpath*:/META-INF/web-fragment-context.xml&amp;lt;/param-value&amp;gt;&lt;br /&gt;    &amp;lt;/context-param&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/web-fragment&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;One new element is the explicitly defined  web-fragment-context.xml Spring context file. We cannot use the default location in the WAR file (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;/WEB-INF/applicationContext.xml&lt;/span&gt;), as this file no longer exists (!) But our tiny fragment JAR seems to be the best place for it:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;       xmlns:context="http://www.springframework.org/schema/context"&lt;br /&gt;       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;       xsi:schemaLocation="&lt;br /&gt;     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&lt;br /&gt;     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&lt;br /&gt;       "&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;context:component-scan base-package="." /&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Package declaration &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;"."&lt;/span&gt; looks disturbing. This is very unfortunate but I tried to workaround the requirement of defining at least one package there. This requirement is probably for a reason (I guess scanning the full CLASSPATH takes some time), but I couldn't just put my own package, as I would have to change this declaration for every single project. But this would violate the biggest advantage of web-fragment approach – once you create this empty JAR with two tiny XML files, you can use it for all your projects. All you have to do is to add this JAR into your WAR's libraries and start annotating POJOs with &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@Service&lt;/span&gt; (and/or use &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@Configuration&lt;/span&gt;).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;If such an utility artefact is going to be ever available out-of-the-box along other Spring dependencies (if you like the idea, &lt;a href="https://jira.springframework.org/browse/SPR-7872"&gt;vote&lt;/a&gt;), beginners might enjoy their Spring-journey right from the moment of adding Spring in pom.xml. In fact, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;pom.xml&lt;/span&gt; can now be written in different &lt;a href="http://polyglot.sonatype.org/why.html"&gt;languages&lt;/a&gt;, as well as &lt;a href="http://logback.qos.ch/manual/groovy.html"&gt;logback.xml&lt;/a&gt;. Look ma, no XML! Are you convinced? Do you prefer XML or Java? Or Groovy? Please, don't answer. Spring gives you the choice to be as lightweight and as simple as you want it to be. Without oversimplification and cutting off more advanced functionalities.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;Update [25.01.2011]: Russian translation by Alexander Belotserkovsky &lt;a href="http://habrahabr.ru/blogs/java/112488"&gt;is available&lt;/a&gt;.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-101753246111762370?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/101753246111762370/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/01/spring-framework-without-xml-at-all.html#comment-form' title='20 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/101753246111762370'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/101753246111762370'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/01/spring-framework-without-xml-at-all.html' title='Spring framework without XML... At all!'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>20</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-2472688727643024414</id><published>2011-01-08T17:45:00.001+01:00</published><updated>2011-11-17T19:09:04.896+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='activiti'/><category scheme='http://www.blogger.com/atom/ns#' term='bpmn'/><title type='text'>Activiti processes and executions explained</title><content type='html'>&lt;div&gt;I was interested in &lt;a href="http://activiti.org/"&gt;Activiti&lt;/a&gt; process engine long before it reached its first stable 5.0 version. Now, when 5.1 was released, I decided to play a bit with this framework, especially paying attention to Spring and JUnit support. But one of the first impediments encountered was the difference between process instance and execution, as well as between sub process and call activity. I am hoping after reading this article you won't encounter the same problems when starting with Activiti.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As you know, even a monkey can learn a new Java framework after reading documentation, but the real fun comes when you meet the technology by studying its source code (often tracking bugs and looking for solutions). And I must admit that Activiti code-base was a pleasure to read, nicely structured and designed. For some reason it is not deployed to Alfresco's &lt;a href="http://maven.alfresco.com/nexus/content/repositories/activiti"&gt;repository&lt;/a&gt;, so to take full advantage of your BPMN journey, start by:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: bash"&gt;&lt;br /&gt;svn co http://svn.codehaus.org/activiti/activiti/tags/activiti-5.1&lt;br /&gt;cd activiti-5.1&lt;br /&gt;mvn install source:jar -DskipTests -Pdistro&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;OK, for starters take a look at this process:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/_P3ewsGQzHn0/TSiPQwaWLlI/AAAAAAAAAY8/yXtDC4XHXtc/s1600/ForkJoin.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="229" src="http://2.bp.blogspot.com/_P3ewsGQzHn0/TSiPQwaWLlI/AAAAAAAAAY8/yXtDC4XHXtc/s640/ForkJoin.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;As you can probably guess, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;+&lt;/span&gt; signs symbolize places where process splits up (&lt;i&gt;forks&lt;/i&gt;) into two or more concurrent paths or &lt;i&gt;joins&lt;/i&gt; concurrent paths back. All you need to know is that until every path created in &lt;i&gt;fork&lt;/i&gt; activity reaches corresponding &lt;i&gt;join&lt;/i&gt; activity, all the paths that reached the &lt;i&gt;join&lt;/i&gt; earlier must wait for the last one to come. If you thought about &lt;a href="http://en.wikipedia.org/wiki/Barrier_%28computer_science%29"&gt;barrier pattern&lt;/a&gt; in thread synchronization, you got the idea. You might also wonder why forks and joins in this process are asymmetric (there is no &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Join B&lt;/span&gt; corresponding to &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Fork B&lt;/span&gt;). First of all, I wanted to show that the process will still work with such a flow. And actually, it won't work with obvious symmetric approach, see bug &lt;a href="http://jira.codehaus.org/browse/ACT-482"&gt;ACT-482&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Never mind, let's do some coding! Activiti has excellent support for JUnit (but don't you dare calling this unit testing!) thanks to &lt;a href="http://activiti.org/javadocs/org/activiti/engine/test/Deployment.html"&gt;@Deployment&lt;/a&gt; annotation. But I can't imagine running processes without Spring support (also very good in Activiti), so I started directly from Spring integration test. First context file:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy"&amp;gt;&lt;br /&gt;    &amp;lt;property name="targetDataSource"&amp;gt;&lt;br /&gt;        &amp;lt;bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&amp;gt;&lt;br /&gt;            &amp;lt;property name="driverClassName" value="org.h2.Driver" /&amp;gt;&lt;br /&gt;            &amp;lt;property name="url" value="jdbc:h2:~/workspace/h2/activiti;DB_CLOSE_ON_EXIT=FALSE;TRACE_LEVEL_FILE=4" /&amp;gt;&lt;br /&gt;            &amp;lt;property name="username" value="sa" /&amp;gt;&lt;br /&gt;            &amp;lt;property name="password" value="" /&amp;gt;&lt;br /&gt;        &amp;lt;/bean&amp;gt;&lt;br /&gt;    &amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&amp;gt;&lt;br /&gt;    &amp;lt;property name="dataSource" ref="dataSource" /&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!-- Workaround to http://jira.codehaus.org/browse/ACT-473 --&amp;gt;&lt;br /&gt;&amp;lt;bean id="initProcessEngines" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"&amp;gt;&lt;br /&gt;    &amp;lt;property name="staticMethod" value="org.activiti.engine.ProcessEngines.init"/&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&amp;lt;bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean" depends-on="initProcessEngines"&amp;gt;&lt;br /&gt;    &amp;lt;property name="processEngineConfiguration"&amp;gt;&lt;br /&gt;        &amp;lt;bean class="org.activiti.spring.SpringProcessEngineConfiguration"&amp;gt;&lt;br /&gt;            &amp;lt;property name="databaseType" value="h2" /&amp;gt;&lt;br /&gt;            &amp;lt;property name="dataSource" ref="dataSource" /&amp;gt;&lt;br /&gt;            &amp;lt;property name="transactionManager" ref="transactionManager" /&amp;gt;&lt;br /&gt;            &amp;lt;property name="databaseSchemaUpdate" value="none" /&amp;gt;&lt;br /&gt;            &amp;lt;property name="jobExecutorActivate" value="false" /&amp;gt;&lt;br /&gt;            &amp;lt;property name="deploymentResources" value="classpath*:/com/blogspot/nurkiewicz/tryipad2/bpmn20/*.bpmn20.xml" /&amp;gt;&lt;br /&gt;        &amp;lt;/bean&amp;gt;&lt;br /&gt;    &amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;For unit testing you should rather use in-memory database and set &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;databaseSchemaUpdate&lt;/span&gt; to &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;create&lt;/span&gt;; fortunately H2 works perfectly as in-memory, standalone and TCP-enabled server. Also it's the default database for Activiti and Grails projects is moving &lt;a href="http://www.grails.org/Roadmap"&gt;onto it&lt;/a&gt;. So what are you waiting for?  &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The configuration is anything but complicated, just creating &lt;a href="http://activiti.org/javadocs/org/activiti/engine/ProcessEngine.html"&gt;ProcessEngine&lt;/a&gt; instance using factory bean. This is the central engine class, exposing several convenient services to the user. To make access to them easier, add the following beans as well:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService" /&amp;gt;&lt;br /&gt;&amp;lt;bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService" /&amp;gt;&lt;br /&gt;&amp;lt;bean id="taskService" factory-bean="processEngine" factory-method="getTaskService" /&amp;gt;&lt;br /&gt;&amp;lt;bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService" /&amp;gt;&lt;br /&gt;&amp;lt;bean id="managementService" factory-bean="processEngine" factory-method="getManagementService" /&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Did you noticed &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;deploymentResources&lt;/span&gt; attribute of factory bean? It instruct process engine to search given directory and automatically open, parse and deploy processes found there. Unfortunately Activiti can't handle PNG process diagrams, but it speaks &lt;a href="http://www.bpmn.org/"&gt;BPMN 2.0&lt;/a&gt; natively. Here is the same process in this language:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;process name="ForkJoin" id="ForkJoin" isExecutable="false"&amp;gt;&lt;br /&gt;    &amp;lt;startEvent id="Start" name="Start"/&amp;gt;&lt;br /&gt;    &amp;lt;userTask id="Task_0" name="Task 0"/&amp;gt;&lt;br /&gt;    &amp;lt;parallelGateway gatewayDirection="Diverging" id="Fork_AB" name="Fork AB"/&amp;gt;&lt;br /&gt;    &amp;lt;userTask id="Task_A" name="Task A"/&amp;gt;&lt;br /&gt;    &amp;lt;userTask id="Task_B" name="Task B"/&amp;gt;&lt;br /&gt;    &amp;lt;parallelGateway gatewayDirection="Diverging" id="Fork_B" name="Fork B"/&amp;gt;&lt;br /&gt;    &amp;lt;userTask id="Task_B1" name="Task B1"/&amp;gt;&lt;br /&gt;    &amp;lt;parallelGateway gatewayDirection="Converging" id="Join_B" name="Join B"/&amp;gt;&lt;br /&gt;    &amp;lt;userTask id="Task_B2" name="Task B2"/&amp;gt;&lt;br /&gt;    &amp;lt;parallelGateway gatewayDirection="Converging" id="Join_AB" name="Join AB"/&amp;gt;&lt;br /&gt;    &amp;lt;userTask id="Task_C" name="Task C"/&amp;gt;&lt;br /&gt;    &amp;lt;endEvent id="End" name="End"/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_2" name="" sourceRef="Fork_AB" targetRef="Task_A" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_5" name="" sourceRef="Fork_AB" targetRef="Task_B" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_7" name="" sourceRef="Task_B" targetRef="Fork_B" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_0" name="" sourceRef="Fork_B" targetRef="Task_B1" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_1" name="" sourceRef="Fork_B" targetRef="Task_B2" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_11" name="" sourceRef="Task_B1" targetRef="Join_AB" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_10" name="" sourceRef="Task_B2" targetRef="Join_AB" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_4" name="" sourceRef="Task_A" targetRef="Join_AB" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_8" name="" sourceRef="Join_AB" targetRef="Task_C" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_12" name="" sourceRef="Task_C" targetRef="End" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_9" name="" sourceRef="Start" targetRef="Task_0" /&amp;gt;&lt;br /&gt;    &amp;lt;sequenceFlow id="Flow_6" name="" sourceRef="Task_0" targetRef="Fork_AB" /&amp;gt;&lt;br /&gt;&amp;lt;/process&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Maybe it's not that kind of format you'd love, but on the other hand I won't insult your intelligence explaining it. It becomes even more obvious when compared with process diagram above. By the way keep this diagram and BPMN description open on your second display (I bet you have it!), it will be easier to follow the test case.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;import static org.fest.assertions.Assertions.assertThat;&lt;br /&gt;import org.activiti.engine.RuntimeService;&lt;br /&gt;import org.activiti.engine.runtime.ProcessInstance;&lt;br /&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration(locations = "classpath:/com/blogspot/nurkiewicz/tryipad2/activiti/ActivitiTestCase-context.xml")&lt;br /&gt;public class ForkJoinTest {&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private RuntimeService runtimeService;&lt;br /&gt;&lt;br /&gt;    @Test&lt;br /&gt;    public void shouldRunConcurrently() throws Exception {&lt;br /&gt;        final ProcessInstance process = runtimeService.startProcessInstanceByKey("ForkJoin");&lt;br /&gt;        final String pid = process.getId();&lt;br /&gt;        //...&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Using &lt;a href="http://activiti.org/javadocs/org/activiti/engine/RuntimeService.html"&gt;RuntimeService&lt;/a&gt;, one of the services provided by &lt;a href="http://activiti.org/javadocs/org/activiti/engine/ProcessEngine.html"&gt;ProcessEngine&lt;/a&gt;, we start new &lt;i&gt;&lt;b&gt;process instance&lt;/b&gt;&lt;/i&gt;. You can use either process key (name) or process id. The latter allows you to specify exact process definition version, while using process key will always result in starting the latest version. Yes, Activiti supports seamless process versioning. And yes, it's similarities to &lt;a href="http://www.jboss.org/jbpm"&gt;jBPM&lt;/a&gt; are almost to evident – but that's not a &lt;a href="http://processdevelopments.blogspot.com/2010/05/alfresco-creates-activiti.html"&gt;secret&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now when our process is started, we might manipulate it and perform some assertions. And remember: the process was not only created, but it &lt;i&gt;started&lt;/i&gt;&lt;span style="font-style: normal;"&gt;. This means that calling &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;startProcessInstanceByKey()&lt;/span&gt; is blocking and it will return only when process engine has nothing more to do (for instance, it reached user task which requires user interaction). This is the case in our project, the first activity after start is user &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task 0&lt;/span&gt;:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;log.debug("Waiting in Task 0");&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(pid)).containsOnly("Task_0");&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-style: normal;"&gt;Now Activiti waits for user confirmation (this might be a particular user, group or anyone) to proceed further. But before doing so, let's go one step back. We have created one process instance, and every process instance &lt;/span&gt;&lt;i&gt;is&lt;/i&gt;&lt;span style="font-style: normal;"&gt; some type of &lt;/span&gt;&lt;i&gt;&lt;b&gt;execution&lt;/b&gt;&lt;/i&gt;&lt;span style="font-style: normal;"&gt;. This terminology will be extremely important when we &lt;/span&gt;&lt;span style="font-style: normal;"&gt;go&lt;/span&gt;&lt;span style="font-style: normal;"&gt; into Activiti querying API:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;//only one execution&lt;br /&gt;assertThat(&lt;br /&gt;        runtimeService&lt;br /&gt;                .createExecutionQuery()&lt;br /&gt;                .processInstanceId(pid)&lt;br /&gt;                .list()&lt;br /&gt;).hasSize(1);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;We were looking here for all &lt;i&gt;&lt;span style="font-weight: normal;"&gt;executions&lt;/span&gt;&lt;/i&gt; belonging to &lt;i&gt;&lt;span style="font-weight: normal;"&gt;process&lt;/span&gt;&lt;/i&gt; with given id. Now when we are sure that there is only one execution (it is the process itself), we should quickly move forward:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;log.debug("Signaling advances to Task A and B concurrently");&lt;br /&gt;runtimeService.signal(pid);&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(pid)).containsOnly("Task_A", "Task_B");&lt;br /&gt;&lt;br /&gt;//three execution&lt;br /&gt;assertThat(&lt;br /&gt;        runtimeService&lt;br /&gt;                .createExecutionQuery()&lt;br /&gt;                .processInstanceId(pid)&lt;br /&gt;                .list()&lt;br /&gt;).hasSize(3);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-style: normal;"&gt;Are you looking at the process graph on the second display like I &lt;/span&gt;&lt;span style="font-style: normal;"&gt;told you to do&lt;/span&gt;&lt;span style="font-style: normal;"&gt;? After signalling the process it moved forward to Task A &lt;/span&gt;&lt;span style="font-style: normal;"&gt;&lt;b&gt;and&lt;/b&gt;&lt;/span&gt;&lt;span style="font-style: normal;"&gt; Task B. And, same as with &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task 0&lt;/span&gt;, it waits for our interactions. &lt;/span&gt;&lt;span style="font-style: normal;"&gt;But also notice, that we already have three executions! Two executions are representing two concurrent paths (nomen est omen!) of execution, while the remaining third execution is the process itself. And the process waits until &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Join AB&lt;/span&gt; is reached to get the control back.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-style: normal;"&gt;So let's push &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task A&lt;/span&gt; further. By the way don't get the false impression that process engine is only about stopping and waiting for being pushed &lt;/span&gt;&lt;span style="font-style: normal;"&gt;manually&lt;/span&gt;&lt;span style="font-style: normal;"&gt; – it's just silly &lt;/span&gt;&lt;i&gt;hello &lt;/i&gt;&lt;i&gt;forked &lt;/i&gt;&lt;i&gt;world&lt;/i&gt;&lt;span style="font-style: normal;"&gt; &lt;/span&gt;&lt;span style="font-style: normal;"&gt;example&lt;/span&gt;&lt;span style="font-style: normal;"&gt;, we'll dive deeper into more comprehensive example&lt;/span&gt;&lt;span style="font-style: normal;"&gt;s&lt;/span&gt;&lt;span style="font-style: normal;"&gt; later. Now we must learn the basics. Wh&lt;/span&gt;&lt;span style="font-style: normal;"&gt;ere&lt;/span&gt;&lt;span style="font-style: normal;"&gt; was I?&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;final Execution forkA = runtimeService&lt;br /&gt;        .createExecutionQuery()&lt;br /&gt;        .activityId("Task_A")&lt;br /&gt;        .processInstanceId(pid)&lt;br /&gt;        .singleResult();&lt;br /&gt;log.debug("Found forked execution {} in Task A activity for process {}", forkA, pid);&lt;br /&gt;&lt;br /&gt;runtimeService.signal(forkA.getId());&lt;br /&gt;log.debug("Advanced fork A, waiting in Join AB");&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(pid)).containsOnly("Task_B");&lt;br /&gt;&lt;br /&gt;//no active activities in fork A since waiting in join&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(forkA.getId())).isEmpty();&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-style: normal;"&gt;Lots of exciting things happen here (unless, which I can hardly believe, you don't find Java BPMN process engine in action exciting). First we found (via Activiti &lt;a href="http://activiti.org/javadocs/org/activiti/engine/runtime/ExecutionQuery.html"&gt;ExecutionQuery&lt;/a&gt;) exactly one execution that belongs to given process and waits in activity Task A. Then we pushed it further as previously. But what about active activities? Seems like execution representing &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task A&lt;/span&gt; doesn't have any (?), while the whole process has only one (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task B&lt;/span&gt;) active activity available. How come? The &lt;/span&gt;&lt;span style="font-style: normal;"&gt;J&lt;/span&gt;&lt;span style="font-style: normal;"&gt;avadocs state precisely, that executions becomes inactive (i.e. it has no active activity) when one of the following occurs:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;ul&gt;&lt;ul&gt;&lt;li&gt;&lt;div&gt;an   execution enters a nested scope&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;ul&gt;&lt;ul&gt;&lt;li&gt;&lt;div&gt;an   execution is split up into multiple concurrent executions, then the   &lt;b&gt;parent is made inactive&lt;/b&gt;.&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;ul&gt;&lt;ul&gt;&lt;li&gt;&lt;div&gt;an   execution has &lt;b&gt;arrived in a parallel gateway&lt;/b&gt; or join and that   join has not yet activated/fired.&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;ul&gt;&lt;ul&gt;&lt;li&gt;&lt;div&gt;an   execution is ended.&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Because the execution after leaving &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task A&lt;/span&gt; activity reached &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Join AB&lt;/span&gt; as first out of three parties, it waits for the remaining two, making its execution inactive. The main process execution is inactive as well, waiting for &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Join AB&lt;/span&gt;. Understanding this behaviour is essential when it comes to testing parallel process executions. If you aren't convinced, look at Activiti logs:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: plain"&gt;&lt;br /&gt;Leaving activity 'Task_A'&lt;br /&gt;ConcurrentExecution[12256734] takes transition (Task_A)--Flow_4--&amp;gt;(Join_AB)&lt;br /&gt;ConcurrentExecution[12256734] executes Activity(Join_AB): org.activiti.engine.impl.bpmn.ParallelGatewayActivity&lt;br /&gt;parallel gateway 'Join_AB' does not activate: 1 of 3 joined&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Let us make branch A wait no more and advance branch B the same way we already exercised. Look at the process graph and think for a while, how many executions will exist then? How many of them are active? And which activities are active?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;final Execution forkB = runtimeService.createExecutionQuery()&lt;br /&gt;        .activityId("Task_B")&lt;br /&gt;        .processInstanceId(pid)&lt;br /&gt;        .singleResult();&lt;br /&gt;log.debug("Found forked execution {} in Task B activity for process {}", forkB, pid);&lt;br /&gt;&lt;br /&gt;runtimeService.signal(forkB.getId());&lt;br /&gt;log.debug("Advanced fork B, waiting in concurrent activities B1 and B2");&lt;br /&gt;&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(pid)).containsOnly("Task_B1", "Task_B2");&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now we will push forward executions waiting in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task B1&lt;/span&gt; and &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;B2&lt;/span&gt;:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;final Execution forkB1 = runtimeService&lt;br /&gt;        .createExecutionQuery()&lt;br /&gt;        .processInstanceId(pid)&lt;br /&gt;        .activityId("Task_B1")&lt;br /&gt;        .singleResult();&lt;br /&gt;assertThat(forkB1).isNotNull();&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(forkB1.getId())).containsOnly("Task_B1");&lt;br /&gt;&lt;br /&gt;final Execution forkB2 = runtimeService&lt;br /&gt;        .createExecutionQuery()&lt;br /&gt;        .processInstanceId(pid)&lt;br /&gt;        .activityId("Task_B2")&lt;br /&gt;        .singleResult();&lt;br /&gt;assertThat(forkB2).isNotNull();&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(forkB2.getId())).containsOnly("Task_B2");&lt;br /&gt;&lt;br /&gt;log.debug("Found forked executions {} and {} in B1/B2 activities accordingly ", forkB1, forkB2);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;...signalling:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;runtimeService.signal(forkB1.getId());&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(forkB1.getId())).isEmpty();&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(forkB2.getId())).containsExactly("Task_B2");&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(forkA.getId())).isEmpty();&lt;br /&gt;&lt;br /&gt;log.debug("Signalling fork B2 will activate Join AB");&lt;br /&gt;runtimeService.signal(forkB2.getId());&lt;br /&gt;&lt;br /&gt;assertThat(&lt;br /&gt;        runtimeService&lt;br /&gt;                .createExecutionQuery()&lt;br /&gt;                .executionId(forkA.getId())&lt;br /&gt;                .singleResult()&lt;br /&gt;).isNull();&lt;br /&gt;assertThat(&lt;br /&gt;        runtimeService&lt;br /&gt;                .createExecutionQuery()&lt;br /&gt;                .executionId(forkB1.getId())&lt;br /&gt;                .singleResult()&lt;br /&gt;).isNull();&lt;br /&gt;assertThat(&lt;br /&gt;        runtimeService&lt;br /&gt;                .createExecutionQuery()&lt;br /&gt;                .executionId(forkB2.getId())&lt;br /&gt;                .singleResult()&lt;br /&gt;).isNull();&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(pid)).containsOnly("Task_C");&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;...and logs:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;final Execution forkB = runtimeService.createExecutionQuery()&lt;br /&gt;        .activityId("Task_B")&lt;br /&gt;        .processInstanceId(pid)&lt;br /&gt;        .singleResult();&lt;br /&gt;log.debug("Found forked execution {} in Task B activity for process {}", forkB, pid);&lt;br /&gt;&lt;br /&gt;runtimeService.signal(forkB.getId());&lt;br /&gt;log.debug("Advanced fork B, waiting in concurrent activities B1 and B2");&lt;br /&gt;&lt;br /&gt;assertThat(runtimeService.getActiveActivityIds(pid)).containsOnly("Task_B1", "Task_B2");&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As you can see when execution containing &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task B1&lt;/span&gt; reached join activity, nothing happened since the join waits for three executions to join. But when the remaining execution (the one containing &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task B2&lt;/span&gt;) finally made it, &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Join AB&lt;/span&gt; breaks and after so many tiring steps we are waiting at the last &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task C&lt;/span&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now there is only one execution associated with the process back again. Finishing the process while waiting in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Task C&lt;/span&gt; is trivial&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;assertThat(&lt;br /&gt;        runtimeService&lt;br /&gt;                .createExecutionQuery()&lt;br /&gt;                .processInstanceId(pid)&lt;br /&gt;                .list()&lt;br /&gt;).hasSize(1);&lt;br /&gt;log.debug("Signalling Task C to finish the process");&lt;br /&gt;runtimeService.signal(pid);&lt;br /&gt;&lt;br /&gt;assertThat(&lt;br /&gt;        runtimeService&lt;br /&gt;                .createProcessInstanceQuery()&lt;br /&gt;                .processInstanceId(pid)&lt;br /&gt;                .singleResult()&lt;br /&gt;).isNull();&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Fully understanding the difference between process and execution is essential to understand and take advantage of fork/join parallelism. Also it is important to use runtime querying API effectively. You must remember that &lt;a href="http://activiti.org/javadocs/org/activiti/engine/runtime/ProcessInstanceQuery.html"&gt;ProcessInstanceQuery&lt;/a&gt; is used to query process instances (&lt;i&gt;duh!&lt;/i&gt;) (we've created only a single process instance throughout this test) by process id, while &lt;a href="http://activiti.org/javadocs/org/activiti/engine/runtime/ExecutionQuery.html"&gt;ExecutionQuery&lt;/a&gt; allows to find executions (we've created several executions during the test, including the process itself). Execution query is more powerful, as it enables you to find all executions associated with the given process (and also the process itself), executions in a given activity, etc. Both queries can be created using &lt;a href="http://activiti.org/javadocs/org/activiti/engine/RuntimeService.html"&gt;RuntimeService&lt;/a&gt;. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I hope you have a general idea how Activiti manages process execution and how to test it. Full source code of the test case is &lt;a href="https://github.com/nurkiewicz/try-ipad2/blob/process-execution/src/test/java/com/blogspot/nurkiewicz/tryipad2/activiti/ForkJoinTest.java"&gt;available&lt;/a&gt;, as well as the whole working Maven &lt;a href="https://github.com/nurkiewicz/try-ipad2/tree/process-execution"&gt;project&lt;/a&gt;. In the next article I will explain &lt;i&gt;call activities&lt;/i&gt; and &lt;i&gt;sub processes&lt;/i&gt;, but prepare to dive into much more interesting case studies soon.&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-2472688727643024414?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/2472688727643024414/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2011/01/activiti-processes-and-executions.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2472688727643024414'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2472688727643024414'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2011/01/activiti-processes-and-executions.html' title='Activiti processes and executions explained'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_P3ewsGQzHn0/TSiPQwaWLlI/AAAAAAAAAY8/yXtDC4XHXtc/s72-c/ForkJoin.png' height='72' width='72'/><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-3890409264693841643</id><published>2010-12-19T21:32:00.001+01:00</published><updated>2011-11-17T19:07:24.748+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='intellij idea'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='testing'/><category scheme='http://www.blogger.com/atom/ns#' term='junit'/><title type='text'>Speeding up Spring integration tests</title><content type='html'>&lt;div&gt;&lt;a href="http://www.blogger.com/post-edit.g?blogID=6753769565491687768&amp;amp;postID=3890409264693841643" name="__DdeLink__6_1527370377"&gt;&lt;/a&gt;&lt;span&gt;The biggest problem with unit testing using Spring &lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html"&gt;testing support&lt;/a&gt;* is the time it takes to initialize the Spring framework context. Every new test case adds precious seconds to overall build time. After a while it will take minutes or even hours to fully build the application, while most of this time is consumed by Spring itself. But we'll start from the basics.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;In order to make JUnit aware of Spring framework test support, simply add these &lt;/span&gt;&lt;span&gt;annotations on test case class:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration&lt;br /&gt;@Transactional&lt;br /&gt;public class MainControllerTest {&lt;br /&gt;    //...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;While &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@Transactional&lt;/span&gt; is not necessary, it will greatly simplify testing when database is involved (details &lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testcontext-tx"&gt;here&lt;/a&gt;). In IntelliJ IDEA &lt;/span&gt;&lt;span&gt;10 &lt;/span&gt;&lt;span&gt;(I just took &lt;/span&gt;&lt;span&gt;this brand &lt;/span&gt;&lt;span&gt;new version for a test drive) these annotations will raise the following error to occur:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/_P3ewsGQzHn0/TQ5ocRt0jMI/AAAAAAAAAYY/X02PDMxXH_o/s1600/inspection1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://1.bp.blogspot.com/_P3ewsGQzHn0/TQ5ocRt0jMI/AAAAAAAAAYY/X02PDMxXH_o/s1600/inspection1.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;And suggested solution:&lt;a name='more'&gt;&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/_P3ewsGQzHn0/TQ5ojlh6YKI/AAAAAAAAAYc/sc8emChy13c/s1600/inspection2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://1.bp.blogspot.com/_P3ewsGQzHn0/TQ5ojlh6YKI/AAAAAAAAAYc/sc8emChy13c/s1600/inspection2.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;You now have two options: either create the file named the same as your test case with &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;-context.xml&lt;/span&gt; suffix (and in the same package) as suggested or use different file and specify its name explicitly using locations attribute to &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/context/ContextConfiguration.html"&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@ContextConfiguration&lt;/span&gt;&lt;/a&gt;. Following convention over configuration for now I recommend you to follow the Spring naming convention. When using Maven, your class under test should reside in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;src/main/java&lt;/span&gt;, test case in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;src/test/java&lt;/span&gt; and Spring configuration file in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;src/test/resources&lt;/span&gt; (&lt;/span&gt;&lt;span&gt;but &lt;/span&gt;&lt;span&gt;see &lt;a href="http://youtrack.jetbrains.net/issue/IDEA-61829"&gt;IDEA-61829&lt;/a&gt;):&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;span&gt;&lt;pre class="brush: plain"&gt;&lt;br /&gt;pom.xml&lt;br /&gt;src&lt;br /&gt;|-- main&lt;br /&gt;|    -- java&lt;br /&gt;|       `-- com&lt;br /&gt;|           `-- blogspot&lt;br /&gt;|               `-- nurkiewicz&lt;br /&gt;|                   `-- spring&lt;br /&gt;|                       `-- test&lt;br /&gt;|                           `-- web&lt;br /&gt;|                               `-- MainController.java&lt;br /&gt;`-- test&lt;br /&gt;    |-- java&lt;br /&gt;    |   `-- com&lt;br /&gt;    |       `-- blogspot&lt;br /&gt;    |           `-- nurkiewicz&lt;br /&gt;    |               `-- spring&lt;br /&gt;    |                   `-- test&lt;br /&gt;    |                       `-- web&lt;br /&gt;    |                           `-- MainControllerTest.java&lt;br /&gt;    `-- resources&lt;br /&gt;         -- com&lt;br /&gt;            `-- blogspot&lt;br /&gt;                `-- nurkiewicz&lt;br /&gt;                    `-- spring&lt;br /&gt;                        `-- test&lt;br /&gt;                            `-- web&lt;br /&gt;                                `-- MainControllerTest-context.xml&lt;br /&gt;&lt;/pre&gt; &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;In case you'll get lost, IDEA &lt;/span&gt;&lt;span&gt;provides magnificent Packages view in Project explorer:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/_P3ewsGQzHn0/TQ5ojijbRfI/AAAAAAAAAYg/DaiZgz69JdM/s1600/packages.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/_P3ewsGQzHn0/TQ5ojijbRfI/AAAAAAAAAYg/DaiZgz69JdM/s1600/packages.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;As you can see files in different physical directories are all located in the same logic&lt;/span&gt;&lt;span&gt;al&lt;/span&gt;&lt;span&gt; directory corresponding to the package. This is especially useful when working with &lt;a href="http://wicket.apache.org/"&gt;Wicket&lt;/a&gt; web framework, where each page class must have equivalent HTML file, preferably in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;src/main/resources&lt;/span&gt;.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;Coming back to Spring. When running the test case, Spring runner will automatically open the &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;*-context.xml&lt;/span&gt; file and initialize the application context described in this file. The context will typically contain class under test bean definition along with its direct dependencies. Now you can inject every bean from the context directly to your test case class:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration&lt;br /&gt;public class MainControllerTest {&lt;br /&gt;&lt;br /&gt; @Resource&lt;br /&gt; private MainController mainController;&lt;br /&gt;&lt;br /&gt; @Test&lt;br /&gt; public void smokeTest() throws Exception {&lt;br /&gt;  //mainController...&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;The important thing to remember is that spring context will be initialized prior the first test method is executed and (unless you use &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/annotation/DirtiesContext.html"&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;@DirtiesContext&lt;/span&gt;&lt;/a&gt; annotation) will be reused &lt;/span&gt;&lt;span&gt;(rather than recreated) &lt;/span&gt;&lt;span&gt;for every &lt;/span&gt;&lt;span&gt;subsequent test &lt;/span&gt;&lt;span&gt;method &lt;/span&gt;&lt;span&gt;in this test case. This is a way of decreasing the test execution time. Although it is a myth that Spring context initialization takes so much time, but some of your own beans might increase this time significantly. For instance Hibernate/JPA persistence providers or embedded &lt;a href="http://activemq.apache.org/"&gt;ActiveMQ&lt;/a&gt; server are huge facilities taking several seconds to boot up. This is the major drawback of Spring tests, making many developers reluctant to them.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;What &lt;a href="http://kezzler.com/"&gt;we&lt;/a&gt; recently discovered is that Spring out of the box supports reusing once initialized context even in different test case classes &lt;/span&gt;&lt;span&gt;across your artifact&lt;/span&gt;&lt;span&gt;. This means that in best case scenario you pay the price of context startup only once and use the same context across all your tests, making startup time less relevant and insignificant compared to the overall build time.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;In order to benefit from this feature, you must forget everything I said about convention over configuration. Now every test case has its own context configuration file, treated as independent application context. &lt;/span&gt;&lt;span&gt;But if you reuse the same file in every test case, Spring will figure out that every test case points to the same file and simply reuse the context as well, &lt;/span&gt;&lt;span&gt;for example&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration(locations = "classpath:test-context.xml")&lt;br /&gt;@Transactional&lt;br /&gt;public class MainControllerTest {&lt;br /&gt;    //...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//...&lt;br /&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration(locations = "classpath:test-context.xml")&lt;br /&gt;@Transactional&lt;br /&gt;public class BarRepositoryTest {&lt;br /&gt;    //...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//...&lt;br /&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration(locations = "classpath:test-context.xml")&lt;br /&gt;@Transactional&lt;br /&gt;public class BarServiceTest {&lt;br /&gt;    //...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//...&lt;br /&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration(locations = "classpath:test-context.xml")&lt;br /&gt;@Transactional&lt;br /&gt;public class FooRepositoryTest {&lt;br /&gt;    //...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//...&lt;br /&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration(locations = "classpath:test-context.xml")&lt;br /&gt;@Transactional&lt;br /&gt;public class FooServiceTest {&lt;br /&gt;    //...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;By the way if you are disgusted by the annotations repetition, inheritance comes to the rescue.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;There are few consequences of single vs. specialized context for every test case. First of all, the single context must be suitable for &lt;/span&gt;&lt;span&gt;each and &lt;/span&gt;&lt;span&gt;every test case, which means it must contain all beans being tested (effectively: almost whole application). This means that even though the complete build will be much faster, running a separate test case will cost you &lt;/span&gt;&lt;span&gt;much more time&lt;/span&gt;&lt;span&gt;. But there is a workaround for that as well. In your complete test context simply declare:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;beans default-lazy-init="true"&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;This will cause loading only these beans, that are necessary in this particular test. And when running a full test suite, all beans will be lazily initialized one after another. In one context per test case approach each test context has only carefully chosen, fine grained beans. In single context you must have all the beans &lt;/span&gt;&lt;span&gt;declared&lt;/span&gt;&lt;span&gt;, but thanks to lazy loading &lt;/span&gt;&lt;span&gt;not all of them will be created when not needed.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;To sum things up. In order to get the most of your Spring integration testing, take your production application context, mocking only necessary dependencies like database or JMS. Thanks to that you will avoid repeating the bean definitions in production and test XML context files. Once having &lt;/span&gt;&lt;span&gt;one, &lt;/span&gt;&lt;span&gt;&lt;i&gt;master&lt;/i&gt;&lt;/span&gt;&lt;span&gt; test context, point to it in every test case to make efficient use of Spring context caching. Happy testing!&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;* Even bigger problem is that such tests shouldn't be considered as unit tests at all, as they test system as a whole rather than separate class (unit). That is why you should consider Spring-powered tests as integration tests and treat them as complementary to unit tests rather than their substitution.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-3890409264693841643?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/3890409264693841643/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/12/speeding-up-spring-integration-tests.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/3890409264693841643'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/3890409264693841643'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/12/speeding-up-spring-integration-tests.html' title='Speeding up Spring integration tests'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_P3ewsGQzHn0/TQ5ocRt0jMI/AAAAAAAAAYY/X02PDMxXH_o/s72-c/inspection1.png' height='72' width='72'/><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-2059029815651797737</id><published>2010-10-17T16:39:00.001+02:00</published><updated>2011-11-17T19:06:03.745+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><category scheme='http://www.blogger.com/atom/ns#' term='conferences'/><title type='text'>Functional Java Developers’ Day 2010</title><content type='html'>&lt;b&gt;Ted Neward&lt;/b&gt;s’ talk about functional programming in Java and his workshop on Scala (hence the article title) were the most memorable events during the third &lt;a href="http://10.jdd.org.pl/"&gt;JDD&lt;/a&gt; conference that I attended last week. Sadly most memorable, and almost the only ones. But first things first.&lt;br /&gt;&lt;br /&gt;After spending endless hours with great &lt;a href="http://www.amazon.com/gp/product/059600978X?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=390957&amp;amp;creativeASIN=059600978X"&gt;Enterprise JavaBeans 3.0&lt;/a&gt; book by &lt;b&gt;Bill Burke&lt;/b&gt; I’ve expected something fabulous, but Bills’ lecture about JAX-RS was just average, with no coding, only plain API introduction. Scott Davis' presenting REST and ROA &lt;a href="http://nurkiewicz.blogspot.com/2009/10/yesterday-i-had-pleasure-to-participate.html"&gt;last year&lt;/a&gt; was way much better. Thankfully &lt;b&gt;Angelika Langer&lt;/b&gt; talk about Java concurrency pitfalls was much more interesting, although one might argue that she just gave a summary of marvelous &lt;a href="http://www.amazon.com/gp/product/0321349601?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=390957&amp;amp;creativeASIN=0321349601"&gt;Java Concurrency in Practice&lt;/a&gt; book, that I have &lt;a href="http://nurkiewicz.blogspot.com/2009/08/java-concurrency-in-practice-written-by.html"&gt;recommended&lt;/a&gt; long time ago. One new thing I’ve learnt is that updating volatile variable guarantees all other non-volatile variable updated earlier by the same thread to be visible by other threads, as if they were volatile as well (are you following?) After Angelika there was a talk about Java performance testing, but I had a copy of &lt;a href="http://www.amazon.com/gp/product/0596520662?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=390957&amp;amp;creativeASIN=0596520662"&gt;The Art of Application Performance Testing&lt;/a&gt; book in my knapsack, so the presentation didn’t caught a lot of my attention.&lt;br /&gt;&lt;br /&gt;After delicious lunch Ted Neward  gave a talk on functional programming concepts in Java. Charismatic, entertaining, surprising – I knew he will make a great show. In the middle of third or fourth slide he asked innocently who prefers slides to live coding and after finding no such person on the audience, he instantly closed the presentation and opened notepad, writing some Java code from scratch. It looked so natural that I almost believed that he actually had any slides further – but of course this was all set up. Ted mentioned &lt;a href="http://functionaljava.org/"&gt;Functional Java&lt;/a&gt; library as a way to enable functional style of programming in plain old Java. Another libraries I can point out if you have to stick with this language are: &lt;a href="http://www.fun4j.org/"&gt;Fun4J&lt;/a&gt;, Google's &lt;a href="http://code.google.com/p/guava-libraries"&gt;Guava&lt;/a&gt; and &lt;a href="http://code.google.com/p/lambdaj"&gt;LambdaJ&lt;/a&gt;. Also take a look at &lt;a href="http://projectlombok.org/"&gt;Lombok&lt;/a&gt; to write more concise POJOs.&lt;br /&gt;&lt;br /&gt;I’ve seen &lt;b&gt;Piotr Walczyszyn&lt;/b&gt; several times evangelizing Flex and AIR so it came a bit of a surprise that I really enjoyed his talk, even though I don’t like front-end programming. But a real surprise was the &lt;b&gt;Linda Rising&lt;/b&gt; presentation dealing with the problem of introducing change and convincing our coworkers to it. From time to time we need to look at our job from 10,000 ft perspective, see how ridiculously we sometimes behave and how irrational our choices are. &lt;a href="http://www.amazon.com/gp/product/1934356050?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=390957&amp;amp;creativeASIN=1934356050"&gt;See Pragmatic Thinking and Learning...&lt;/a&gt; for a more in-depth analysis on this. Also I recently read marvelous &lt;a href="http://www.amazon.com/gp/product/1400082471?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=390957&amp;amp;creativeASIN=1400082471"&gt;Dreaming in Code&lt;/a&gt; by Scott Rosenberg. Linda’s talk complemented these books excellently.&lt;br /&gt;&lt;br /&gt;On the next day I sacrificed three presentations to participate in Ted Neward’s workshop on Scala – continuing the subject of functional programming. He introduced Scala language step by step, emphasizing the differences and commons misconceptions. I will repeat after him: Scala is compiled, statically typed, &lt;i&gt;consistent&lt;/i&gt; language, don’t compare it with Groovy, these are completely different tools. I was doing my best to follow Ted’s examples on my computer and finally I wrote few simple (compiling!) lines of Scala code. Too bad my first presentation on Scala (&lt;a href="http://nurkiewicz.blogspot.com/2009/05/relacja-z-geecon-2009-w-krakowie.html"&gt;during GeeCON 2009&lt;/a&gt;) by Luc Duponcheel wasn’t that good and simply beyond my comprehension. Here are few examples of Scala concepts that significantly caught my attention. POJO in Scala:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;import org.apache.commons.lang.builder._&lt;br /&gt;&lt;br /&gt;class Book(author: String, title: String, year: Int) {&lt;br /&gt;&lt;br /&gt;  override def toString =&lt;br /&gt;    new ToStringBuilder()&lt;br /&gt;      .append("author", author)&lt;br /&gt;      .append("title", title)&lt;br /&gt;      .append("year", year)&lt;br /&gt;      .toString()&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;Please note few things. Firstly, interacting with Java libraries (Apache Commons Lang in this example) is straightforward. Secondly all the types are objects, including primitives (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Int&lt;/span&gt; – consistency!) But the most important issue is: where are the fields?!? Scala compiler (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;scalac&lt;/span&gt;) is a one clever beast: after finding constructor arguments and variables used in &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;toString()&lt;/span&gt; method matching them it figured out that the programmer’s intention was to assign constructor arguments to fields so that &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;toString()&lt;/span&gt; can use these fields afterwards. Here is the proof:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;//javap -private Book&lt;br /&gt;&lt;br /&gt;Compiled from "Book.scala"&lt;br /&gt;public class Book extends java.lang.Object implements scala.ScalaObject{&lt;br /&gt;    private final java.lang.String author;&lt;br /&gt;    private final java.lang.String title;&lt;br /&gt;    private final int year;&lt;br /&gt;    public java.lang.String toString();&lt;br /&gt;    public Book(java.lang.String, java.lang.String, int);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And a better proof if you are bytecode-capable:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;//javap -c Book&lt;br /&gt;//...&lt;br /&gt;&lt;br /&gt;public Book(java.lang.String, java.lang.String, int);&lt;br /&gt;  Code:&lt;br /&gt;   0:   aload_0&lt;br /&gt;   1:   aload_1&lt;br /&gt;   2:   putfield        #28; //Field author:Ljava/lang/String;&lt;br /&gt;   5:   aload_0&lt;br /&gt;   6:   aload_2&lt;br /&gt;   7:   putfield        #35; //Field title:Ljava/lang/String;&lt;br /&gt;   10:  aload_0&lt;br /&gt;   11:  iload_3&lt;br /&gt;   12:  putfield        #38; //Field year:I&lt;br /&gt;   15:  aload_0&lt;br /&gt;   16:  invokespecial   #49; //Method java/lang/Object."&amp;lt;init&amp;gt;":()V&lt;br /&gt;   19:  return&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Need getters? Prepend every constructor argument with &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;val&lt;/span&gt; keyword. Setters as well? Replace &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;val&lt;/span&gt; (&lt;i&gt;value&lt;/i&gt;) with &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;var&lt;/span&gt; (&lt;i&gt;variable&lt;/i&gt;). No boilerplate code, no code generation needed. Second more comprehensive example is Scala’s &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;match&lt;/span&gt; operator:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;&lt;br /&gt;def capitalizeAfterHash(list: List[Char]): List[Char] =&lt;br /&gt;  list match {&lt;br /&gt;    case '#' :: rest =&amp;gt;&lt;br /&gt;      rest.map(_.toUpper)&lt;br /&gt;    case _ :: rest =&amp;gt;&lt;br /&gt;      capitalizeAfterHash(rest)&lt;br /&gt;    case Nil =&amp;gt;&lt;br /&gt;      Nil&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;println(capitalizeAfterHash('a' :: 'b' :: '#' :: 'c' :: 'd' :: Nil))&lt;br /&gt;println(capitalizeAfterHash('#' :: 'c' :: 'd' :: Nil))&lt;br /&gt;println(capitalizeAfterHash('a' :: 'b' :: Nil))&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Match is like switch on steroids. In this example it is used to match list of characters against some patterns. The last case means: "&lt;i&gt;if list is empty (&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;Nil&lt;/span&gt;), return empty list&lt;/i&gt;." The first case states: "&lt;i&gt;if the first element of the list is ‘#’, take the rest of the list and call &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;toUpper()&lt;/span&gt; on every item ("&lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;_&lt;/span&gt;" placeholder)&lt;/i&gt;". Finally the second case is: "&lt;i&gt;if the first element of the list has any value (except ‘#’ examined earlier), call recursively capitalizeAfterHash with the rest of the list (effectively: repeat without the first element)&lt;/i&gt;". Can you guess what does this function do?&lt;br /&gt;&lt;br /&gt;Scala is not for everybody and you need to have some solid programming background to fully appreciate its expressiveness. I don’t think I will choose Scala from my toolbox anytime soon,  but I will definitely follow this language development. Actually, after observing what is currently happening with JDK 7 (and 8...) I will say loudly: "Java (the language) is dead, long live Java (the JVM)". Some time ago Sun was waiting for so long to develop new, easier and more productive version of their EJB 2.1 standard that competitors came up with much better, although non-standard solutions (think: Spring). Now the same thing is happening with Java (the language) and other JVM languages. That’s why interoperability between new JVM languages and Java code is so important: one day we will end up with tons of legacy code in (dead) Java language (because Sun/Oracle was too reluctant to update the language; see F#, LINQ, etc.), adding new features and rewriting parts of old systems in new, dynamic and more productive languages. JVM is great, but one day Java will become only a historic language, reference and exemplary implementation, not used anymore. Like &lt;a href="http://en.wikipedia.org/wiki/Reference_counting"&gt;reference counting&lt;/a&gt; as a way of implementing garbage collection.&lt;br /&gt;&lt;br /&gt;Where was I? Oh, JDD 2010. To be honest, nothing interesting happened after marvelous Ted Neward’s workshop. At least two presentations were extremely boring, but I had no choice, as there was only one track. Actually, if we exclude workshops, the amount of presentations was comparable to last year, even though the conference lasted for 2 days in the contrary to one day in 2009. But last year there were two independent tracks. So the conference was two times longer (which was the biggest demand of the participants last year, including myself) but introduced similar number of presentations – nice marketing trick! The second demand was to change the place where the conference was taking place last year (sports hall with plastic chairs? &lt;i&gt;C'mon!&lt;/i&gt;) Seems like this suggestion was somehow missed...&lt;br /&gt;&lt;br /&gt;Thankfully I attended very interesting presentations by Ted Neward, Linda Rising and Angelika Langer. Without them I would be somewhat disappointed by this year’s Java Developers’ Day. Main tips for organizers: find a comfortable conference centre and don’t force people to attend sponsored talks. And don’t stop! As still JDD is a great event with lots of potential.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-2059029815651797737?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/2059029815651797737/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/10/functional-java-developers-day-2010.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2059029815651797737'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2059029815651797737'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/10/functional-java-developers-day-2010.html' title='Functional Java Developers’ Day 2010'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-913626062211997442</id><published>2010-09-25T21:13:00.004+02:00</published><updated>2011-11-17T18:41:49.774+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='tdd'/><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='testing'/><category scheme='http://www.blogger.com/atom/ns#' term='junit'/><category scheme='http://www.blogger.com/atom/ns#' term='aop'/><title type='text'>Testing for exceptions in JUnit revised</title><content type='html'>In his recent &lt;a href="http://monkeyisland.pl/2010/07/26/expected-exception-in-tests"&gt;post&lt;/a&gt; the author of fantastic mocking framework &lt;a href="http://mockito.org/"&gt;Mockito&lt;/a&gt; collected few rules about testing exceptions. What caught my attention is the advice to use JUnit rules (&lt;i&gt;nomen est omen&lt;/i&gt;!) for testing exceptions. &lt;a href="http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/ExpectedException.html"&gt;ExpectedException&lt;/a&gt; rule gathers advantages of both &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;expected&lt;/span&gt; &lt;span style="font-family: &amp;quot;;"&gt;@Test&lt;/span&gt; attribute clarity  and &lt;span style="font-family: &amp;quot;;"&gt;try-catch&lt;/span&gt; strictness. Here is the example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class DefaultFooServiceTest {&lt;br /&gt;&lt;br /&gt; private FooService fooService = new DefaultFooService();&lt;br /&gt;&lt;br /&gt; @Rule&lt;br /&gt; public ExpectedException exception = new ExpectedException();&lt;br /&gt;&lt;br /&gt; @Test&lt;br /&gt; public void shouldThrowNpeWhenNullName() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  String name = null;&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  exception.expect(NullPointerException.class);&lt;br /&gt;  fooService.echo(name);&lt;br /&gt;&lt;br /&gt;  //then&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Szczepan claims that &lt;span style="font-family: &amp;quot;Courier New&amp;quot;, &amp;quot;Courier&amp;quot;, monospace;"&gt;ExpectedException&lt;/span&gt; fits into &lt;i&gt;given/when/then&lt;/i&gt; test template nicely. I disagree! Look at the code snippet above – what is the most natural place to put assertions on exception being thrown? From the obvious reasons it must be the last line before the line that actually throws the exceptions. So you have a choice to put assertion as the last statement in &lt;i&gt;given&lt;/i&gt; block or as first in &lt;i&gt;when&lt;/i&gt; block. You are right, this is how this test should look like in an ideal world:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Test&lt;br /&gt;public void shouldThrowNpeWhenNullName() throws Exception {&lt;br /&gt; //given&lt;br /&gt; String name = null;&lt;br /&gt;&lt;br /&gt; //when&lt;br /&gt; fooService.echo(name);&lt;br /&gt;&lt;br /&gt; //then&lt;br /&gt; exception.expect(NullPointerException.class);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;No we’re talking! There’s just this tiny problem with example above – we expect code in &lt;i&gt;when&lt;/i&gt; block to throw an exception and put assertions afterwards in &lt;i&gt;then&lt;/i&gt; block. See the problem? If we could somehow transparently catch the exception, store it somewhere, return normally and let assertions to run against it... With AOP it is actually pretty easy, but I wanted to implement this feature using pure Java and with JUnit framework. First, I will introduce &lt;span style="font-family: &amp;quot;;"&gt;@UnderTest&lt;/span&gt; marker annotation:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Retention(RetentionPolicy.RUNTIME)&lt;br /&gt;@Target(ElementType.FIELD)&lt;br /&gt;public @interface UnderTest {&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now put this annotation above the field in your test case corresponding to class under test:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@UnderTest&lt;br /&gt;private FooService fooService = new DefaultFooService();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Although the annotation brings some value itself, marking which object is actually being tested, it is not meant for documentation and test readability, I am going to use it together with some Java reflection. I mentioned that AOP would solve our problems. JUnit 4.7 ships with AOP-like mechanism called &lt;a href="http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/MethodRule.html"&gt;rules&lt;/a&gt;. By writing a rule (&lt;span style="font-family: &amp;quot;;"&gt;ExpectedException&lt;/span&gt; is an example of a JUnit built-in rule) you simply create an interceptor around every test method. With this interceptor you can, for instance, run test method in separate thread, do some setup and cleanup, etc. My custom rule will do two things:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;wrap class under test in Java proxy to catch every exception, store it and return normally&lt;/li&gt;&lt;li&gt;verify thrown exception against assertions introduced in &lt;i&gt;then&lt;/i&gt; block&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Skeleton of the rule code is as follows:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;package com.blogspot.nurkiewicz.junit.exceptionassert;&lt;br /&gt;&lt;br /&gt;public class ExceptionAssert implements MethodRule {&lt;br /&gt;&lt;br /&gt; @Override&lt;br /&gt; public Statement apply(Statement base, FrameworkMethod method, Object testCase) {&lt;br /&gt;  this.testCase = testCase;&lt;br /&gt;  return new ExceptionAssertStatement(base);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private class ExceptionAssertStatement extends Statement {&lt;br /&gt;&lt;br /&gt;  private final Statement base;&lt;br /&gt;&lt;br /&gt;  private Throwable exceptionThrownFromClassUnderTest;&lt;br /&gt;  private Field underTestField;&lt;br /&gt;&lt;br /&gt;  public ExceptionAssertStatement(Statement base) {&lt;br /&gt;   this.base = base;&lt;br /&gt;   underTestField = findClassUnderTestField(testCase);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  public void evaluate() throws Throwable {&lt;br /&gt;   final Object originalClassUnderTest = wrapClassUnderTest(testCase);&lt;br /&gt;   try {&lt;br /&gt;    base.evaluate();&lt;br /&gt;   } finally {&lt;br /&gt;    setUnderTestField(originalClassUnderTest);&lt;br /&gt;   }&lt;br /&gt;   verifyException();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: &amp;quot;;"&gt;ExceptionAssertStatement&lt;/span&gt; is an example of &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorator&lt;/a&gt; pattern: it takes original &lt;span style="font-family: &amp;quot;;"&gt;Statement&lt;/span&gt; instance (representing test method execution) and replaces it with wrapped  (decorated) custom class, also implementing &lt;span style="font-family: &amp;quot;;"&gt;Statement&lt;/span&gt;. &lt;span style="font-family: &amp;quot;;"&gt;ExceptionAssertStatement&lt;/span&gt; adds some additional logic and calls original’s statement &lt;span style="font-family: &amp;quot;;"&gt;evaluate()&lt;/span&gt; method. This additional logic is pretty straightforward:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;first, take class under test and wrap it (wrapping again!) in a proxy&lt;/li&gt;&lt;li&gt;execute the test method (evaluate())&lt;/li&gt;&lt;li&gt;(revert to original class under test)&lt;/li&gt;&lt;li&gt;when test method exits, verify exception throw from class under test (if any)&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;The last interesting piece is the proxy wrapping class under test itself:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;private Object wrapWithProxy(final Object classUnderTest) {&lt;br /&gt; return Proxy.newProxyInstance(classUnderTest.getClass().getClassLoader(), new Class[]{underTestField.getType()}, new InvocationHandler() {&lt;br /&gt;  @Override&lt;br /&gt;  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {&lt;br /&gt;   try {&lt;br /&gt;    return method.invoke(classUnderTest, args);&lt;br /&gt;   } catch (InvocationTargetException e) {&lt;br /&gt;    exceptionThrownFromClassUnderTest = e.getCause();&lt;br /&gt;    return null;&lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt; });&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Nothing fancy: if class under test throws an exception, store it somewhere and return normally. Not that hard. Enough of the internals, let’s look at our brand new rule in action:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public class DefaultFooServiceTest {&lt;br /&gt;&lt;br /&gt; @UnderTest&lt;br /&gt; private FooService fooService = new DefaultFooService();&lt;br /&gt;&lt;br /&gt; @Rule&lt;br /&gt; public ExceptionAssert exception = new ExceptionAssert();&lt;br /&gt;&lt;br /&gt; @Test&lt;br /&gt; public void shouldReturnHelloString() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  String name = "Tomek";&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  final String result = fooService.echo(name);&lt;br /&gt;&lt;br /&gt;  //then&lt;br /&gt;  assertEquals("Hello, Tomek!", result);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; @Test&lt;br /&gt; public void shouldThrowNpeWhenNullName() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  String name = null;&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  fooService.echo(name);&lt;br /&gt;&lt;br /&gt;  //then&lt;br /&gt;  exception.expect(NullPointerException.class);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; @Test&lt;br /&gt; public void shouldThrowIllegalArgumentWhenNameJohn() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  String name = "John";&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  fooService.echo(name);&lt;br /&gt;&lt;br /&gt;  //then&lt;br /&gt;  exception.expect(IllegalArgumentException.class)&lt;br /&gt;    .expectMessage("Name: 'John' is not allowed");&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;First test method does not expect any exception to be thrown – it if will, test will fail. Second test expects &lt;span style="font-family: &amp;quot;;"&gt;NullPointerException&lt;/span&gt;. Please note that if the exception will be thrown from any other line than &lt;span style="font-family: &amp;quot;;"&gt;fooService.echo()&lt;/span&gt; (or &lt;span style="font-family: &amp;quot;;"&gt;fooService.echo()&lt;/span&gt; won’t throw &lt;span style="font-family: &amp;quot;;"&gt;NullPointerException&lt;/span&gt;), test will fail. The last test shows that you can also assert exception message as well.&lt;br /&gt;&lt;br /&gt;Few things are still missing in &lt;a href="http://github.com/nurkiewicz/junit-exception-assert-rule/downloads"&gt;0.0.1&lt;/a&gt; "version", mainly proxying classes (CGLIB, anyone?); also, some syntactic sugar together with DSL-like (&lt;a href="http://code.google.com/p/fest"&gt;FEST&lt;/a&gt;-like) assertions could be introduced:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Test&lt;br /&gt;public void shouldThrowIllegalArgumentWhenNameJohn() throws Exception {&lt;br /&gt; //given&lt;br /&gt; String name = "John";&lt;br /&gt;&lt;br /&gt; //when&lt;br /&gt; fooService.echo(name);&lt;br /&gt;&lt;br /&gt; //then&lt;br /&gt; expect(IllegalArgumentException.class)&lt;br /&gt;   .withMessage("Name: 'John' is not allowed");&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Also I had to copy&amp;amp;paste big parts of JUnit’s &lt;span style="font-family: &amp;quot;;"&gt;ExpectedException&lt;/span&gt;, as most obvious inheritance was not possible due to private constructor. But still, take a look at &lt;span style="font-family: &amp;quot;;"&gt;ExceptionAssert&lt;/span&gt; rule and see for yourself how readable exception testing can be. As always, source code can be cloned and downloaded from my GitHub &lt;a href="http://github.com/nurkiewicz/junit-exception-assert-rule"&gt;account&lt;/a&gt;. Any comments and contributions are welcome!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-913626062211997442?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/913626062211997442/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/09/testing-for-exceptions-in-junit-revised.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/913626062211997442'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/913626062211997442'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/09/testing-for-exceptions-in-junit-revised.html' title='Testing for exceptions in JUnit revised'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-7845273221647314404</id><published>2010-09-24T20:12:00.002+02:00</published><updated>2011-11-17T18:40:34.139+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='spring-js'/><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='jruby'/><category scheme='http://www.blogger.com/atom/ns#' term='tdd'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='groovy'/><title type='text'>JavaScript dynamic language support in Spring framework</title><content type='html'>Miško Hevery’s blog &lt;a href="http://misko.hevery.com/2010/04/07/move-over-java-i-have-fallen-in-love-with-javascript"&gt;post&lt;/a&gt; about JavaScript opened my eyes and changed the way I thought about this language completely. Miško practices TDD and advices this technique at every occasion. JavaScript, being dynamic language, needs tests even more than statically and strongly typed languages. This immediately invalidates main objections against JavaScript and dynamic languages at all – that lack of compile time checks inevitably lead to poor quality and runtime bugs instead of compile time. But what is more convincing to you: that your code passes very strict compile time rules or that it passes unit tests covering all the use cases?&lt;br /&gt;&lt;br /&gt;After going through the first few chapters of &lt;a href="http://www.amazon.com/gp/product/1847194141?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=390957&amp;amp;creativeASIN=1847194141"&gt;Object-Oriented JavaScript...&lt;/a&gt; I couldn’t help myself to try this new, very productive language with functional aspirations. But then I realized that, unlike Java, JavaScript misses:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;good runtime environment: it’s hard to name handful of web browsers, each implementing different dialect of the language, decent runtime&lt;/li&gt;&lt;li&gt;good development environment: debugger, editor with code completion, profiler – I mean, &lt;a href="http://getfirebug.com/"&gt;Firebug&lt;/a&gt; is wonderful, but...&lt;/li&gt;&lt;li&gt;testing capabilities – aforementioned vast number of web browser in countless versions, actually, how to run such tests on your continuous integration server?&lt;/li&gt;&lt;li&gt;server-side attitude. C’mon, I’m a &lt;a href="http://geekandpoke.typepad.com/geekandpoke/2010/07/how-to-make-enterprise-software.html"&gt;back-end guy&lt;/a&gt;, running my code inside a web browser to manipulate page DOM and debug using browser plugin? This just doesn’t feel right. Let me run this script clustered on a farm of 16-core servers to make me excited!&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;And when I say server-side, I mean Spring Framework. The idea to run JavaScript on server-side &lt;a href="http://en.wikipedia.org/wiki/Comparison_of_Server-side_JavaScript_solutions"&gt;isn’t new&lt;/a&gt;, so it would be nice to introduce JavaScript in Spring. Since version 2.0 Spring supports developing beans using few dynamic languages, namely Groovy, JRuby and BeanShell. The support includes:&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Implementing given Java interface using one of the dynamic languages above&lt;/li&gt;&lt;li&gt;Injecting beans implemented in dynamic language to standard Java beans (other beans simply use Java interface as their client view)&lt;/li&gt;&lt;li&gt;...and vice-versa – injecting standard Spring beans into dynamic language scripts&lt;/li&gt;&lt;li&gt;Automatic refresh of script source with configured frequency – sources can be located somewhere on the file system or over the network , allowing hot-deployment and reevaluation without Spring context restart&lt;/li&gt;&lt;li&gt;Scripted beans can participate in Spring aspects, transactions, etc.&lt;/li&gt;&lt;/ol&gt;The list of features (and possible use cases) for scripted beans is impressive and the whole concept is very powerful. But the list of languages supported is somewhat limited, and – you’ve guessed, but no prize this time – I will add JavaScript to this list in the next few pages. This isn’t going to be very hard since &lt;a href="http://www.mozilla.org/rhino"&gt;Rhino&lt;/a&gt;, JavaScript engine for Java, is now embedded in JRE.&lt;br /&gt;&lt;br /&gt;Please at least take a look at Spring dynamic languages support &lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/dynamic-language.html"&gt;documentation&lt;/a&gt; before proceeding, as I will start from the example how I wish the JavaScript support would look like in TDD spirit. Let’s start from simple Java interface:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;package org.springframework.scripting.js;&lt;br /&gt;&lt;br /&gt;public interface HelloService {&lt;br /&gt;&lt;br /&gt; String hello(String name);&lt;br /&gt;&lt;br /&gt; String helloParameterized(String name, Date effectiveDate, int age, Locale locale);&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is the client view of our bean, the implementation is completely transparent to the users of this interface. What we would like to achieve is to be able to implement this interface using JavaScript similar to Groovy or JRuby support in Spring:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;       xmlns:lang="http://www.springframework.org/schema/lang"&lt;br /&gt;       xsi:schemaLocation="&lt;br /&gt;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&lt;br /&gt;http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd"&amp;gt;&lt;br /&gt;&lt;br /&gt; &amp;lt;lang:js id="javaScriptHelloService" script-interfaces="org.springframework.scripting.js.HelloService"&amp;gt;&lt;br /&gt;  &amp;lt;lang:inline-script&amp;gt;&lt;br /&gt;   function hello(name) {&lt;br /&gt;    return "Hello, " + name + "!"&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   function helloParameterized(name, effectiveDate, age, locale) {&lt;br /&gt;    return "" + effectiveDate + ": " + name + " (" + (age + 1) + ", " +&lt;br /&gt;     locale.getDisplayCountry(java.util.Locale.US) + ")" &lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;  &amp;lt;/lang:inline-script&amp;gt;&lt;br /&gt; &amp;lt;/lang:js&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And finally the test case stub:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;package org.springframework.scripting.js;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration&lt;br /&gt;public class JavaScriptScriptFactoryHelloTest {&lt;br /&gt;&lt;br /&gt; @Resource&lt;br /&gt; private HelloService helloService;&lt;br /&gt;&lt;br /&gt; @Test&lt;br /&gt; public void shouldReturnHelloStringFromJs() throws Exception {&lt;br /&gt;  //given&lt;br /&gt;  final String name = "Tomek";&lt;br /&gt;&lt;br /&gt;  //when&lt;br /&gt;  final String result = helloService.hello(name);&lt;br /&gt;&lt;br /&gt;  //then&lt;br /&gt;  assertThat(result).isEqualTo("Hello, Tomek!");&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; //other tests&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Typical Spring integration test looks for file named after the test case name with “&lt;span style="font-family: &amp;quot;;"&gt;-context.xml&lt;/span&gt;” suffix (see above). As you can see, no JavaScript is visible, test case (being &lt;span style="font-family: &amp;quot;;"&gt;HelloService&lt;/span&gt; client) uses injected interface and calls its operations. The fact that this works and runs JavaScript using Rhino behind the scenes is completely hidden by Spring Framework. Maybe hidden – but not yet implemented. Test fails, we must provide the implementation.&lt;br /&gt;&lt;br /&gt;First, one line must be added to &lt;span style="font-family: &amp;quot;;"&gt;LangNamespaceHandler&lt;/span&gt;, simply mapping &lt;span style="font-family: &amp;quot;;"&gt;&amp;lt;lang:js&amp;gt;&lt;/span&gt; tag to so-called &lt;i&gt;script factory&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;package org.springframework.scripting.config;&lt;br /&gt;&lt;br /&gt;public class LangNamespaceHandler extends NamespaceHandlerSupport {&lt;br /&gt;&lt;br /&gt; public void init() {&lt;br /&gt;  registerScriptBeanDefinitionParser("groovy", "org.springframework.scripting.groovy.GroovyScriptFactory");&lt;br /&gt;  registerScriptBeanDefinitionParser("jruby", "org.springframework.scripting.jruby.JRubyScriptFactory");&lt;br /&gt;  registerScriptBeanDefinitionParser("bsh", "org.springframework.scripting.bsh.BshScriptFactory");&lt;br /&gt;  registerScriptBeanDefinitionParser("js", "org.springframework.scripting.js.JavaScriptScriptFactory");&lt;br /&gt;  registerBeanDefinitionParser("defaults", new ScriptingDefaultsParser());&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The purpose of &lt;span style="font-family: &amp;quot;;"&gt;JavaScriptScriptFactory&lt;/span&gt; is pretty straightforward: it gets set of Java interfaces (have you mentioned the &lt;i style="font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;"&gt;script-interfaces&lt;/i&gt; attribute?) and script source and is suppose to return some implementation of all these interfaces, of course utilizing script source provided:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;package org.springframework.scripting.js;&lt;br /&gt;&lt;br /&gt;public class JavaScriptScriptFactory implements ScriptFactory {&lt;br /&gt;&lt;br /&gt; public boolean requiresConfigInterface() {&lt;br /&gt;  return true;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public Object getScriptedObject(ScriptSource scriptSource, Class[] actualInterfaces) throws IOException, ScriptCompilationException {&lt;br /&gt;  return //It's a kind of magic&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Actually, there is no magic out there, just plain &lt;a href="http://jcp.org/en/jsr/detail?id=223"&gt;JSR-223&lt;/a&gt; API abstracting Rhino engine. But still dynamic proxies, reflection and creating Java interfaces from scratch using CGLIB is taking place out there (luckily Spring manages most of this), so if you are really curious, take a look at my GitHub &lt;a href="http://github.com/nurkiewicz/spring-js/tree/master/src/main/java/org/springframework/scripting/js"&gt;account&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;What have we achieved? Take for instance this JavaScript Spring bean declaration:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;lang:js id="javaScriptUserService"&lt;br /&gt; script-interfaces="org.springframework.scripting.js.UserService"&lt;br /&gt; script-source="http://somehost:8080/scripts/UserService.js"&lt;br /&gt; refresh-check-delay="15000"/&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Enough to make Spring download &lt;span style="font-family: &amp;quot;;"&gt;UserService.js&lt;/span&gt; file from external HTTP server and reload its contents every 15 seconds. Now in order to change &lt;span style="font-family: &amp;quot;;"&gt;UserService&lt;/span&gt; behavior simply put new version of &lt;span style="font-family: &amp;quot;;"&gt;.js&lt;/span&gt; file on your web server (or FTP folder, or file system directory, or...) – no restarts, no class-loaders juggling, no OSGi – unbelievably flexible, deadly simple and terribly dangerous toy – but that’s a different story.&lt;br /&gt;&lt;br /&gt;We, programmers, love Hello World &lt;a href="http://en.wikibooks.org/wiki/List_of_hello_world_programs"&gt;examples&lt;/a&gt;. Some of us even judge technologies based on their “&lt;i&gt;hello&lt;/i&gt;” incarnation. But how could you use scripted bean in a real world application? The last feature we haven’t covered yet is dependency injection into JavaScript bean (not injecting the bean somewhere else). Spring already provides syntax for that:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&lt;br /&gt;&amp;lt;bean id="resourceBundleMessageSource" class="org.springframework.context.support.ResourceBundleMessageSource"&amp;gt;&lt;br /&gt; &amp;lt;property name="basename" value="org.springframework.scripting.js.i18n.hello"/&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;bean id="greatBritainLocale" class="java.util.Locale"&amp;gt;&lt;br /&gt; &amp;lt;constructor-arg value="en_GB"/&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;lang:js id="javaScriptHelloService"&lt;br /&gt;  script-interfaces="org.springframework.scripting.js.HelloService"&lt;br /&gt;  script-source="/org/springframework/scripting/js/HelloService.js"&amp;gt;&lt;br /&gt; &amp;lt;lang:property name="city" value="Warsaw"/&amp;gt;&lt;br /&gt; &amp;lt;lang:property name="locale" ref="greatBritainLocale"/&amp;gt;&lt;br /&gt; &amp;lt;lang:property name="messages" ref="resourceBundleMessageSource"/&amp;gt;&lt;br /&gt;&amp;lt;/lang:js&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;As you can see we ask Spring to inject three properties (Spring bean, Java built-in object and primitive) into the script. How can the script use this dependencies? I have decided to enable them directly as implicit variables:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: js"&gt;&lt;br /&gt;function hello(name) {&lt;br /&gt; return messages.getMessage("hello", [name, city], locale);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: &amp;quot;;"&gt;name&lt;/span&gt; is &lt;span style="font-family: &amp;quot;;"&gt;hello&lt;/span&gt;’s argument, but where does the &lt;span style="font-family: &amp;quot;;"&gt;messages&lt;/span&gt;, &lt;span style="font-family: &amp;quot;;"&gt;city&lt;/span&gt; and &lt;span style="font-family: &amp;quot;;"&gt;locale&lt;/span&gt; come from? Scripted bean can easily interact with other Spring beans (not necessarily written in Java nor JavaScript!), for example asking &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/support/ReloadableResourceBundleMessageSource.html"&gt; ResourceBundleMessageSource&lt;/a&gt; to return internationalized message. I have a &lt;a href="http://github.com/nurkiewicz/spring-js/blob/master/src/test/java/org/springframework/scripting/js/JavaScriptScriptFactoryPropertiesTest.java"&gt;test case&lt;/a&gt; for that (actually, I started from it), believe me, it works!&lt;br /&gt;&lt;br /&gt;Finally I can get my hands dirty wit JavaScript. Writing unit tests using JUnit feels much more natural than observing web browser output. Also Spring-enabled scripted beans give me much richer environment to work with. From my complete novice point of view JavaScript isn’t as good as Groovy, but still it’s worth trying, especially when embedding few MiB groovy.jar is out of the question in your Java 6 app. If you want to experiment with JavaScript support in Spring Framework, just clone my GitHub’s &lt;a href="http://github.com/nurkiewicz/spring-js"&gt;spring-js&lt;/a&gt; repository. And you really like concept of JavaScript running from within Spring, vote for &lt;a href="https://jira.springframework.org/browse/SPR-7592"&gt;SPR-7592&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-7845273221647314404?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/7845273221647314404/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/09/javascript-dynamic-language-support-in.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/7845273221647314404'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/7845273221647314404'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/09/javascript-dynamic-language-support-in.html' title='JavaScript dynamic language support in Spring framework'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-8577147422073830592</id><published>2010-08-05T23:44:00.006+02:00</published><updated>2011-03-30T19:04:36.893+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='cglib'/><category scheme='http://www.blogger.com/atom/ns#' term='intellij idea'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><title type='text'>Creating prototype Spring beans on demand using lookup-method</title><content type='html'>The strength of the Spring Framework is its emphasis on stateless services. Being totally against OOP, this approach has many pragmatic advantages, with low memory consumption, no cost of pooling and multithreaded safety at the top of the list. But sometimes you really need the context and having non-singleton beans with different state attached to each instance makes your code a lot cleaner and easier to read. Let’s start from stateless code and do some consecutive refactorings.&lt;br /&gt;&lt;br /&gt;Every time a new flight is entered into the system, we validate it with multiple business rules using &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; class (please forgive my complete absence of domain knowledge):&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public class FlightValidator {&lt;br /&gt;&lt;br /&gt;@Resource&lt;br /&gt;//Many services&lt;br /&gt;&lt;br /&gt;public boolean validate(Flight flight) {&lt;br /&gt;return validateSourceAndTarget(flight) &amp;amp;&amp;amp;&lt;br /&gt;isAirplaneAvailable(flight) &amp;amp;&amp;amp;&lt;br /&gt;isAirportFree(flight) &amp;amp;&amp;amp;&lt;br /&gt;!buyerBlackListed(flight) &amp;amp;&amp;amp;&lt;br /&gt;reservationLimitReached(flight);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//Many more methods&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There is something really disturbing in this code. The context (&lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;Flight &lt;/span&gt;instance being validated) is passed over and over through subsequent method invocations. On the other hand, because the context exists on the stack (which is thread local in the contrary to the heap), the class is thread safe by its definition. But still the code is so awkward that having &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;flight&lt;/span&gt; field accessible to every method in the class (and sacrificing thread safety) is very tempting*. The easiest solution is to have a new, separate instance of &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; every time we need to validate a flight. So we create &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; bean with prototype scope:&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&amp;lt;bean id="flightValidator" class="com.blogspot.nurkiewicz.lookup.FlightValidator" scope="prototype" lazy-init="true"/&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now, every time there is a need for flight validation, we should ask Spring to create a new instance of &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; (imagine the class has multiple dependencies on other beans, has some aspects woven, etc. – we can’t simply use new operator). The easiest way to do this is to implement &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/BeanFactoryAware.html"&gt;&lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;BeanFactoryAware&lt;/span&gt;&lt;/a&gt; and use injected &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/BeanFactory.html"&gt;&lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;BeanFactory&lt;/span&gt;&lt;/a&gt; to fetch any bean from the client code:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java; highlight: [10]"&gt;public class SomeSpringBean implements BeanFactoryAware {&lt;br /&gt;private BeanFactory beanFactory;&lt;br /&gt;&lt;br /&gt;@Override&lt;br /&gt;public void setBeanFactory(BeanFactory beanFactory) throws BeansException {&lt;br /&gt;this.beanFactory = beanFactory;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//client code:&lt;br /&gt;FlightValidator validator = beanFactory.getBean("flightValidator", FlightValidator.class);&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Every time the code in line 10 is executed, new instance (prototype scope) of &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; is created and returned. Maybe the goal is achieved, but the solution is pretty cumbersome. Not only we tie ourselves with the Spring API, but also we fetch bean by name (which is very verbose). Last but not least, prior to Spring 3.0 the &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;getBean()&lt;/span&gt; always returned &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;Object&lt;/span&gt; instance, forcing client code to downcast the result.&lt;br /&gt;&lt;br /&gt;I used this pattern several times, always being disgusted. But then, by accident, I found &lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lookup-method-injection"&gt;lookup-method&lt;/a&gt; feature in Spring docs. BTW Spring documentation is a gift... and a curse (like &lt;a href="http://www.imdb.com/title/tt0312172/quotes"&gt;detective Monk&lt;/a&gt; used to say) -  so exhaustive and comprehensive that it’s hard to read it and get to know with everything. But back to Spring – the idea behind the lookup method is to drop BeanFactoryAware interface and simply create abstract no-arg method that returns bean of type we are willing to create (i.e. &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt;). Now the best part: we just tell Spring declaratively we want this abstract method to create FlightValidator instance every time it is called and Spring will implement this method at runtime (using &lt;a href="http://cglib.sourceforge.net/"&gt;CGLIB&lt;/a&gt;) for us! Just look how easy it is comparing to &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;BeanFactory&lt;/span&gt; approach:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public abstract class SomeSpringBean {&lt;br /&gt;&lt;br /&gt;protected abstract FlightValidator createValidator();&lt;br /&gt;&lt;br /&gt;//client code somewhere in the class:&lt;br /&gt;FlightValidator validator = createValidator();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml; highlight: 4"&gt;&amp;lt;bean id="flightValidator" class="com.blogspot.nurkiewicz.lookup.FlightValidator" scope="prototype" lazy-init="true"/&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;bean id="someBean" class="com.blogspot.nurkiewicz.lookup.SomeSpringBean"&amp;gt;&lt;br /&gt;&amp;lt;lookup-method name="createValidator" bean="flightValidator"/&amp;gt;&lt;br /&gt;&amp;lt;/bean&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The 4th line of Spring XML is essential. We basically say: &lt;i&gt;hey, createValidator method is abstract and every time it is called, return new instance (using lookup-method and BeanFactory with singleton beans doesn’t make any sense) of bean named flightValidator&lt;/i&gt;. And Spring is clever enough to harness CGLIB and dynamically implement &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;createValidator()&lt;/span&gt; method instead of trying to instantiate abstract class. Pretty awesome!&lt;br /&gt;&lt;br /&gt;This approach looks much nicer, does not involve the Spring API or force us to hardcode bean name in Java code. Now, when we have a fresh new instance of &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt;, we can perform some refactorings to take advantage of class instance variables:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;private Flight flight;&lt;br /&gt;&lt;br /&gt;public boolean validate(Flight flight) {&lt;br /&gt;this.flight = flight;&lt;br /&gt;return validateSourceAndTarget() &amp;amp;&amp;amp;&lt;br /&gt;isAirplaneAvailable() &amp;amp;&amp;amp;&lt;br /&gt;isAirportFree() &amp;amp;&amp;amp;&lt;br /&gt;!buyerBlackListed() &amp;amp;&amp;amp;&lt;br /&gt;reservationLimitReached();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;First, we assign flight to a private field available for all validating methods. Now, every method can access this field and there’s no need for passing arguments all over. But sadly, it is just the beginning. One day we had to make all validating methods publicly accessible in order to call them separately. But now we need some way to initialize &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;flight&lt;/span&gt; field and we certainly don’t want to go back to flight parameter in every method and flight field assignment at the beginning of each one. There is another accidental disadvantage of our solution: if particular instance of FlightValidator leaks to some other thread, this thread can call &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;validate()&lt;/span&gt; method with other &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;Flight&lt;/span&gt; causing race condition. If only we could make &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; immutable by passing &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;flight&lt;/span&gt; only once, binding &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; permanently with this flight and being able to easily call every public validation method...&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;private final Flight flight;&lt;br /&gt;&lt;br /&gt;public FlightValidator(Flight flight) {&lt;br /&gt;this.flight = flight;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public boolean validate() {&lt;br /&gt;return validateSourceAndTarget() &amp;amp;&amp;amp;&lt;br /&gt;isAirplaneAvailable() &amp;amp;&amp;amp;&lt;br /&gt;isAirportFree() &amp;amp;&amp;amp;&lt;br /&gt;!buyerBlackListed() &amp;amp;&amp;amp;&lt;br /&gt;reservationLimitReached();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is it! Our Holy Object Oriented Grail! Compiler forces us to pass valid flight instance (you may add validation to assert that) and after the &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; is created, it will always reference the same flight. API is simple, class is thread safe, everybody is happy... Except our favorite framework... According to the documentation, lookup method discussed above mustn’t have any arguments. But suppose I don’t read the docs and simply add &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;Flight&lt;/span&gt; parameter to lookup method and expect the magic to happen:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;protected abstract FlightValidator createValidator(Flight flight);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I thought to myself that Spring will transparently pass lookup method parameter(s) to the FlightValidator constructor matching its declaration – and we have just created such a constructor. I run the application and it starts fine, but when I try to call lookup method I get:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: plain"&gt;java.lang.AbstractMethodError: com.blogspot.nurkiewicz.lookup.SomeSpringBean.createValidator(Lcom/blogspot/nurkiewicz/lookup/Flight;)Lcom/blogspot/nurkiewicz/lookup/FlightValidator;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Seems like Spring ignored lookup method with arguments and simply didn’t implement it using CGLIB. I would expect context startup to fail or at least warning that lookup won’t work (I even created &lt;a href="https://jira.springframework.org/browse/SPR-7426"&gt;SPR-7426&lt;/a&gt;) but sadly only unit tests can prevent you from such a mistake. And IntelliJ IDEA:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://1.bp.blogspot.com/_P3ewsGQzHn0/TFsxE3JoW0I/AAAAAAAAAWg/_OwefRkJmJo/s1600/IntelliJ+IDEA+lookup-method+inspection.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"&gt;&lt;img alt="" border="0" id="BLOGGER_PHOTO_ID_5502045329356774210" src="http://1.bp.blogspot.com/_P3ewsGQzHn0/TFsxE3JoW0I/AAAAAAAAAWg/_OwefRkJmJo/s400/IntelliJ+IDEA+lookup-method+inspection.png" style="cursor: pointer; display: block; height: 118px; margin: 0px auto 10px; text-align: center; width: 400px;" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;We might work around this limitation and create some sort of &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;init(Flight flight)&lt;/span&gt; method instead of constructor. But what if we forget to call this method or call it twice? Thread safety, immutability and consistency are lost... Spring does not allow us to parameterize creation of prototype beans created by lookup method but come on, it’s open source and I am a programmer, I wouldn’t sleep at night if I at least didn’t try...&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Patching Spring...&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;The stacktrace following &lt;a href="http://download-llnw.oracle.com/javase/6/docs/api/java/lang/AbstractMethodError.html"&gt;AbstractMethodError&lt;/a&gt; didn’t help me but after turning on verbose Spring logging I immediately spotted &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.html"&gt;&lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;org.springframework.beans.factory.support.CglibSubclassingInstantiationStrategy&lt;/span&gt;&lt;/a&gt; class that is responsible for dynamic creation of abstract lookup method code and other features using CGLIB. But first I had to discover why my parameterized lookup method is ignored by this mechanism. After few minutes of studying I came across &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/support/LookupOverride.html"&gt;&lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;org.springframework.beans.factory.support.LookupOverride&lt;/span&gt;&lt;/a&gt; class with method:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;@Override&lt;br /&gt;public boolean matches(Method method) {&lt;br /&gt;return (method.getName().equals(getMethodName()) &amp;amp;&amp;amp; method.getParameterTypes().length == 0);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;So I changed too rigorous constraint and removed no arguments condition:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;@Override&lt;br /&gt;public boolean matches(Method method) {&lt;br /&gt;return method.getName().equals(getMethodName());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I quickly run my unit tests and now Spring generated code for my abstract lookup method (&lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;AbstractMethodError&lt;/span&gt; is gone) but still framework tries to instantiate &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;FlightValidator&lt;/span&gt; bean using no-arg constructor, ignoring lookup method parameters. First success, another challenge.&lt;br /&gt;&lt;br /&gt;Half hour later I finally make out how CGLIB works and how Spring uses it. I’ll skip CGLIB tutorial (maybe we’ll come back to this great library later), enough is to say that every time we call lookup abstract method, CGLIB synthesized class calls provided callback method, that for lookup method looks like this (excerpt from LookupOverrideMethodInterceptor  inner class in org.springframework.beans.factory.support.CglibSubclassingInstantiationStrategy.CglibSubclassCreator):&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java; highlight: 3"&gt;public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable {&lt;br /&gt;LookupOverride lo = (LookupOverride) beanDefinition.getMethodOverrides().getOverride(method);&lt;br /&gt;return owner.getBean(lo.getBeanName());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Third line is crucial. We take bean name defined in Spring XML and fetch it from &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;BeanFactory&lt;/span&gt; named &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;owner&lt;/span&gt;. But hey, what is that, args array argument?!? And take a look at overloaded &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean%28java.lang.String,%20java.lang.Object...%29"&gt;&lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;getBean(String name, Object... args)&lt;/span&gt;&lt;/a&gt; method, ready to be used! I’ll give it a try and see what happens:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java; highlight: 3"&gt;public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable {&lt;br /&gt;LookupOverride lo = (LookupOverride) beanDefinition.getMethodOverrides().getOverride(method);&lt;br /&gt;return owner.getBean(lo.getBeanName(), args);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Can you spot the difference? I run unit tests and can’t believe my own eyes – it works! It’s amazing, I only changed – not even added, changed! – two lines of code and unlocked this great feature. Now I can pass arbitrary set of parameters to the lookup method and they are going to be passed straight to the constructor of newly created object. Finally the lookup method idea makes sense – create new, fully customized and initialized object every time you request it. No need for further setup and danger of data inconsistency. Long live the Spring Framework!&lt;br /&gt;&lt;br /&gt;If you like this feature, I opened &lt;a href="https://jira.springframework.org/browse/SPR-7431"&gt;SPR-7431&lt;/a&gt; ticket, watch it and vote for it.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;* one might argue that &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;validate()&lt;/span&gt; should actually be a method of &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;Flight&lt;/span&gt; and is an example of &lt;a href="https://industriallogic.com/gh/submit?Action=PageAction&amp;amp;album=recognizingSmells&amp;amp;path=recognizingSmells/moreUncommonSmells/featureEnvyExample&amp;amp;devLanguage=Java"&gt;&lt;span style="font-style: italic;"&gt;Feature Envy&lt;/span&gt;&lt;/a&gt; (see &lt;a href="http://martinfowler.com/"&gt;Martin Fowlers&lt;/a&gt;’ &lt;a href="http://www.amazon.com/gp/product/0201485672?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=390957&amp;amp;creativeASIN=0201485672"&gt;book&lt;/a&gt;) code smell. I already &lt;a href="http://nurkiewicz.blogspot.com/2009/10/ddd-in-spring-made-easy-with-aspectj.html"&gt;discussed&lt;/a&gt; how to get rid of this smell using Spring&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-8577147422073830592?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/8577147422073830592/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/08/creating-prototype-spring-beans-on.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/8577147422073830592'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/8577147422073830592'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/08/creating-prototype-spring-beans-on.html' title='Creating prototype Spring beans on demand using lookup-method'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_P3ewsGQzHn0/TFsxE3JoW0I/AAAAAAAAAWg/_OwefRkJmJo/s72-c/IntelliJ+IDEA+lookup-method+inspection.png' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-2281361457388887889</id><published>2010-08-02T23:32:00.006+02:00</published><updated>2011-03-30T19:06:55.576+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='nosql'/><category scheme='http://www.blogger.com/atom/ns#' term='conferences'/><title type='text'>Few words after Javarsovia 2010</title><content type='html'>It is never too late to mention about such a great event like &lt;a href="http://www.javarsovia.pl/"&gt;&lt;span style="font-weight: bold;"&gt;Javarsovia 2010 conference&lt;/span&gt;&lt;/a&gt;. The conference was really successful, even though I was one of the speakers ;-). If you were near Warsaw on 26th of June and missed the conference I feel really sorry for you. But first things first.&lt;br /&gt;&lt;br /&gt;I was really surprised not seeing long queues for the registration, so not wasting a lot of time, equipped with good-looking conference T-shirt, we went to see the first presentation. &lt;span style="font-weight: bold;"&gt;Tomasz Bujok&lt;/span&gt; with his &lt;span style="font-style: italic;"&gt;From zero to jBPM hero!&lt;/span&gt; lecture did a great job introducing &lt;a href="http://jboss.org/jbpm"&gt;jBPM&lt;/a&gt; framework. I have seen quite a few presentations about this engine already, thankfully Tomasz made one step further in the topic and have shown some anti-patterns and other tips for jBPM developers. This was really interesting as anyone, after reading a book or two, can have a "How-to" talk. But having "How-not-to" talk requires knowledge and experience in the technology far beyond  the typical tutorial-driven "experts". I would really like to work with jBPM for a while, but I’m also full of concerns about the future of this framework.&lt;br /&gt;&lt;br /&gt;I have seen &lt;span style="font-weight: bold;"&gt;Wojciech Seliga&lt;/span&gt; last year on &lt;a href="http://nurkiewicz.blogspot.com/2009/10/yesterday-i-had-pleasure-to-participate.html"&gt;Java Developers’ Day&lt;/a&gt;, where he’s been talking about &lt;a href="http://www.atlassian.com/software/crucible"&gt;Crucible&lt;/a&gt;, code review tool his &lt;a href="http://www.spartez.com/"&gt;company&lt;/a&gt; is developing for &lt;a href="http://www.atlassian.com/"&gt;Atlassian&lt;/a&gt;. This time he shared with us some of his experience in working using agile methodologies. I must admit I was pretty amazed how well they adapted Scrum, especially in the field of their relationships with customers. Some people didn’t believe them when they promised to deliver first running software version after a week (one sprint). But they did and this is how they achieve customer trust. Probably one of the most successful companies implementing agile, proving it can really work and bring money. Lots of respect to you &lt;a href="http://www.spartez.com/en/our-people-agile-developers.html"&gt;guys&lt;/a&gt;!&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Piotr Jagielski&lt;/span&gt; had a whole speech about test code refactoring (and actually – test code quality at all). The most important idea from his lecture: if some setup/data is not important for the test, it is important to not include it in this test. For instance, suppose you are testing that creating &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;Person&lt;/span&gt; object with birth date in the future should throw &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;IllegalArgumentException&lt;/span&gt;. Unfortunately, the only available constructor requires, besides &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;birthDate&lt;/span&gt;, also &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;firstName &lt;/span&gt;and &lt;span style="font-family: &amp;quot;courier new&amp;quot;;"&gt;lastName&lt;/span&gt;. Supplying fake names would do the trick, but the test method is now cluttered with irrelevant setup code. Moreover, the reader of this test code might not be so sure about fake names irrelevancy. Some flavor of &lt;a href="http://en.wikipedia.org/wiki/Builder_pattern"&gt;Builder&lt;/a&gt; pattern, introduced by Piotr, is the good solution for this problem. Or one can simply use Groovy with its &lt;a href="http://mrhaki.blogspot.com/2009/09/groovy-goodness-using-lists-and-maps-as.html"&gt;ability&lt;/a&gt; to pass arbitrary property -&amp;gt; value map to the constructor call. I suggested Piotr he could benefit from using Groovy, but seems like he’s not using it for &lt;a href="http://www.ibm.com/developerworks/java/library/j-pg11094/index.html"&gt;testing purposes&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;After the lunch my time has come. &lt;span style="font-style: italic;"&gt;&lt;a href="http://project-voldemort.com/"&gt;Project Voldemort&lt;/a&gt; - when relation database is not enough (too much?)&lt;/span&gt; lecture taken place in Boolean room (BTW: great idea of naming conference rooms after Java data types according to their size!), here is the English translation of the presentation:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div id="__ss_4674050" style="text-align: center;"&gt;&lt;br /&gt;&lt;object height="355" id="__sse4674050" width="425"&gt; &lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=projektvoldemort-eng-100703172941-phpapp01&amp;amp;rel=0&amp;amp;stripped_title=projekt-voldemort-when-relation-database-is-not-enough-too-much"&gt; &lt;param name="allowFullScreen" value="true"&gt; &lt;param name="allowScriptAccess" value="always"&gt; &lt;embed name="__sse4674050" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=projektvoldemort-eng-100703172941-phpapp01&amp;amp;rel=0&amp;amp;stripped_title=projekt-voldemort-when-relation-database-is-not-enough-too-much" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt; &lt;/object&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;...and one of the photos taken during my presentation, thanks to Javarsovia 2010 &lt;a href="http://www.javarsovia.pl/galeria-2.html"&gt;gallery&lt;/a&gt;:&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://2.bp.blogspot.com/_P3ewsGQzHn0/TFc8d9W1ySI/AAAAAAAAAWY/ci4o21pT1ok/s1600/javarsovia2010_266.jpg" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"&gt;&lt;img alt="" border="0" id="BLOGGER_PHOTO_ID_5500931955240585506" src="http://2.bp.blogspot.com/_P3ewsGQzHn0/TFc8d9W1ySI/AAAAAAAAAWY/ci4o21pT1ok/s400/javarsovia2010_266.jpg" style="cursor: pointer; display: block; height: 267px; margin: 0px auto 10px; text-align: left; width: 400px;" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;All about me. For those who have seen me, hope you didn’t regret it! Personally I would choose &lt;span style="font-weight: bold;"&gt;Sławomir Sobótka&lt;/span&gt; talk about design patterns, so thank you for choosing me instead :-).&lt;br /&gt;&lt;br /&gt;Many times I was a bit jealous of American speakers, but after seeing &lt;span style="font-weight: bold;"&gt;Paweł Lipiński&lt;/span&gt; (and &lt;a href="http://nurkiewicz.blogspot.com/2010/05/impressions-after-geecon-2010.html"&gt;&lt;span style="font-weight: bold;"&gt;Dawid Weiss&lt;/span&gt;&lt;/a&gt; few month earlier) I find some Polish speakers being at least as charismatic and entertaining as those coming from the other side of the Ocean. Paweł came out with a toothbrush in his mouth, wearing a dressing-gown. Instantly everybody knew that he’s going to talk about clean... not code, but tests - although wonderful Uncle Bob’s &lt;a href="http://www.amazon.com/gp/product/0132350882?ie=UTF8&amp;amp;tag=javaandneighb-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=390957&amp;amp;creativeASIN=0132350882"&gt;book&lt;/a&gt; has been mentioned many times.&lt;br /&gt;&lt;br /&gt;The truth is, I keep hearing the same things about TDD over and over. Same techniques, same principles, same dos and donts. But still some people live in their caves and don’t realize how could they benefit by using TDD (and even unit testing at all!) Some time ago a friend of mine, after developing in &lt;a href="http://wicket.apache.org/"&gt;Wicket&lt;/a&gt; for a few months (and hundreds of my persuasions), finally tried out &lt;a href="https://cwiki.apache.org/WICKET/unit-test.html"&gt;WicketTester&lt;/a&gt; class. "It’s great", he said, "how could I live without it?" If only I had such a charisma and experience like Paweł, maybe he would have tried earlier. Why can’t people wake up and keep manually testing their code, redeploying and restarting EARs over and over? If Paweł’s talk didn’t opened their eyes, they should at least be ashamed. It was not a developer or project manager lecture. He looked more like a rock-star, shouting with anger, desperately trying to convince the audience. Next time I will attend Paweł Lipiński’s talk, even if it will be on National Crocheting Congress. Great job, wonderful speech.&lt;br /&gt;&lt;br /&gt;I really couldn’t wait to see &lt;span style="font-weight: bold;"&gt;Jarosław Pałka&lt;/span&gt; cross-sectional talk on NoSQL. Unfortunately, being short on time, he only managed to show &lt;a href="http://neo4j.org/"&gt;Neo4j&lt;/a&gt; database and skipped promised &lt;a href="http://www.oracle.com/technetwork/database/berkeleydb/overview/index.html"&gt;CouchDB &lt;/a&gt;and BerkeleyDB. Although Neo4j is the most interesting NoSQL software from these three, it’s a shame there was no time for other players. The speaker had some technical issues while running the examples and focused too much on irrelevant details. Too bad, because the beginning of the lecture was very promising. I would really like to hear the lecture again, but it seemed to lack one or two days of preparation.&lt;br /&gt;&lt;br /&gt;I must say Javarsovia 2010 was a really successful conference, that could easily compete with &lt;a href="http://2010.geecon.org/"&gt;GeeCON&lt;/a&gt; or &lt;a href="http://jdd.org.pl/"&gt;JDD&lt;/a&gt;. More than 600 attendees, 4 independent tracks and very good organization. Oh, did I mention the conference was completely free, including after party in pub? See you next year, good job!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-2281361457388887889?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/2281361457388887889/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/08/few-words-after-javarsovia-2010.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2281361457388887889'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/2281361457388887889'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/08/few-words-after-javarsovia-2010.html' title='Few words after Javarsovia 2010'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_P3ewsGQzHn0/TFc8d9W1ySI/AAAAAAAAAWY/ci4o21pT1ok/s72-c/javarsovia2010_266.jpg' height='72' width='72'/><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-4222227573134757128</id><published>2010-07-06T23:11:00.006+02:00</published><updated>2010-07-06T23:42:10.834+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='jpa'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='hades'/><title type='text'>Hades: DRY principle in JPA/Spring development</title><content type='html'>It's almost two weeks after great &lt;a href="http://javarsovia.pl"&gt;Javarsovia 2010&lt;/a&gt; conference, but before I write few words about this event, let me mention about really clever library called &lt;a href="http://redmine.synyx.org/projects/hades"&gt;Hades&lt;/a&gt;. I owe you this after my attendance in &lt;a href="http://nurkiewicz.blogspot.com/2010/05/impressions-after-geecon-2010.html"&gt;GeeCON 2010&lt;/a&gt;, where I discovered this tool during its author talk.&lt;br /&gt;&lt;br /&gt;DRY stands for &lt;a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself"&gt;Don't Repeat Yourself&lt;/a&gt; and if you were developing in JPA for a while you have violated this principal several times. Take for example this piece of code:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_P3ewsGQzHn0/TDOc1Bj2PWI/AAAAAAAAAWE/t7wRzGF28LI/s1600/Hades.png"&gt;&lt;img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 400px; height: 64px;" src="http://4.bp.blogspot.com/_P3ewsGQzHn0/TDOc1Bj2PWI/AAAAAAAAAWE/t7wRzGF28LI/s400/Hades.png" alt="" id="BLOGGER_PHOTO_ID_5490904805460557154" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Although IntelliJ IDEA has a wonderful &lt;a href="http://www.jetbrains.com/idea/features/jpa_hibernate.html"&gt;support for JPA&lt;/a&gt; (have you noticed this little popup suggesting me the proper named query parameter  name &lt;span style="font-style: italic;"&gt;since&lt;/span&gt;?), I still have to write the same boilerplate code over and over. Basically for each entity object I need a DAO class and 90% of them look the same except they have different entity type. Same CRUD, same paging and sorting logic, same unit tests, similar queries. We are getting bored after writing fifth or tenth DAO like this, especially if we are lazy (which is good!) So Hades provides nice abstraction, at least all your DAOs would follow same naming convention:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public interface GenericDao&amp;lt;T, PK extends Serializable&amp;gt; {&lt;br /&gt;    T save(final T entity);&lt;br /&gt;    List&amp;lt;T&amp;gt; save(final List&amp;lt;T&amp;gt; entities);&lt;br /&gt;    T saveAndFlush(final T entity);&lt;br /&gt;    T readByPrimaryKey(final PK primaryKey);&lt;br /&gt;    boolean exists(final PK primaryKey);&lt;br /&gt;    List&amp;lt;T&amp;gt; readAll();&lt;br /&gt;    List&amp;lt;T&amp;gt; readAll(final Sort sort);&lt;br /&gt;    Page&amp;lt;T&amp;gt; readAll(final Pageable pageable);&lt;br /&gt;    Long count();&lt;br /&gt;    void delete(final T entity);&lt;br /&gt;    void delete(final List&amp;lt;T&amp;gt; entities);&lt;br /&gt;    void deleteAll();&lt;br /&gt;    void flush();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Nice, but you probably came out with similar generic interface long time ago. But Hades goes one step further and it automatically implements this interface for you… For any entity bean you provide!&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public interface MoneyTransferDao extends GenericDao&amp;lt;MoneyTransfer, Long&amp;gt; {}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;But let's start from the beginning. First get necessary dependencies:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&amp;lt;!-- Spring --&amp;gt;&lt;br /&gt;&amp;lt;dependency&amp;gt;&lt;br /&gt;    &amp;lt;groupId&amp;gt;org.springframework&amp;lt;/groupId&amp;gt;&lt;br /&gt;    &amp;lt;artifactId&amp;gt;spring-orm&amp;lt;/artifactId&amp;gt;&lt;br /&gt;    &amp;lt;version&amp;gt;3.0.3.RELEASE&amp;lt;/version&amp;gt;&lt;br /&gt;&amp;lt;/dependency&amp;gt;&lt;br /&gt;&amp;lt;dependency&amp;gt;&lt;br /&gt;    &amp;lt;groupId&amp;gt;org.springframework&amp;lt;/groupId&amp;gt;&lt;br /&gt;    &amp;lt;artifactId&amp;gt;spring-test&amp;lt;/artifactId&amp;gt;&lt;br /&gt;    &amp;lt;version&amp;gt;3.0.3.RELEASE&amp;lt;/version&amp;gt;&lt;br /&gt;    &amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;&lt;br /&gt;&amp;lt;/dependency&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!-- Persistence --&amp;gt;&lt;br /&gt;&amp;lt;dependency&amp;gt;&lt;br /&gt;    &amp;lt;groupId&amp;gt;com.h2database&amp;lt;/groupId&amp;gt;&lt;br /&gt;    &amp;lt;artifactId&amp;gt;h2&amp;lt;/artifactId&amp;gt;&lt;br /&gt;    &amp;lt;version&amp;gt;1.1.119&amp;lt;/version&amp;gt;&lt;br /&gt;    &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;&lt;br /&gt;&amp;lt;/dependency&amp;gt;&lt;br /&gt;&amp;lt;dependency&amp;gt;&lt;br /&gt;    &amp;lt;groupId&amp;gt;commons-dbcp&amp;lt;/groupId&amp;gt;&lt;br /&gt;    &amp;lt;artifactId&amp;gt;commons-dbcp&amp;lt;/artifactId&amp;gt;&lt;br /&gt;    &amp;lt;version&amp;gt;1.4&amp;lt;/version&amp;gt;&lt;br /&gt;    &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;&lt;br /&gt;&amp;lt;/dependency&amp;gt;&lt;br /&gt;&amp;lt;dependency&amp;gt;&lt;br /&gt;    &amp;lt;groupId&amp;gt;org.hibernate.java-persistence&amp;lt;/groupId&amp;gt;&lt;br /&gt;    &amp;lt;artifactId&amp;gt;jpa-api&amp;lt;/artifactId&amp;gt;&lt;br /&gt;    &amp;lt;version&amp;gt;2.0-cr-1&amp;lt;/version&amp;gt;&lt;br /&gt;&amp;lt;/dependency&amp;gt;&lt;br /&gt;&amp;lt;dependency&amp;gt;&lt;br /&gt;    &amp;lt;groupId&amp;gt;org.hibernate&amp;lt;/groupId&amp;gt;&lt;br /&gt;    &amp;lt;artifactId&amp;gt;hibernate-entitymanager&amp;lt;/artifactId&amp;gt;&lt;br /&gt;    &amp;lt;version&amp;gt;3.5.1-Final&amp;lt;/version&amp;gt;&lt;br /&gt;&amp;lt;/dependency&amp;gt;&lt;br /&gt;&amp;lt;dependency&amp;gt;&lt;br /&gt;    &amp;lt;groupId&amp;gt;org.synyx.hades&amp;lt;/groupId&amp;gt;&lt;br /&gt;    &amp;lt;artifactId&amp;gt;org.synyx.hades&amp;lt;/artifactId&amp;gt;&lt;br /&gt;    &amp;lt;version&amp;gt;2.0.0.RC2&amp;lt;/version&amp;gt;&lt;br /&gt;    &amp;lt;exclusions&amp;gt;&lt;br /&gt;        &amp;lt;exclusion&amp;gt;&lt;br /&gt;            &amp;lt;groupId&amp;gt;org.springframework&amp;lt;/groupId&amp;gt;&lt;br /&gt;            &amp;lt;artifactId&amp;gt;org.springframework.orm&amp;lt;/artifactId&amp;gt;&lt;br /&gt;        &amp;lt;/exclusion&amp;gt;&lt;br /&gt;    &amp;lt;/exclusions&amp;gt;&lt;br /&gt;&amp;lt;/dependency&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!-- ... --&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;repository&amp;gt;&lt;br /&gt;    &amp;lt;id&amp;gt;repo.synyx.de&amp;lt;/id&amp;gt;&lt;br /&gt;    &amp;lt;name&amp;gt;Synyx Maven2 Repository&amp;lt;/name&amp;gt;&lt;br /&gt;    &amp;lt;url&amp;gt;http://repo.synyx.org&amp;lt;/url&amp;gt;&lt;br /&gt;&amp;lt;/repository&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;All other dependencies necessary to run Spring-managed integration test with JPA 2.0 backed by Hibernate 3.5 will be downloaded transitively. You also need logging dependencies, take a look &lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-use-appropriate.html"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;As an example we are going to use these two entities:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public class MoneyTransfer implements Serializable {&lt;br /&gt;    private long id;&lt;br /&gt;    private Account from;&lt;br /&gt;    private Account to;&lt;br /&gt;    private BigDecimal amount;&lt;br /&gt;    private Calendar date;&lt;br /&gt;&lt;br /&gt;    //get/set&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public class Account implements Serializable {&lt;br /&gt;    private int id;&lt;br /&gt;    private String ownerName;&lt;br /&gt;&lt;br /&gt;    //get/set&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Personally, I find JPA annotations great for rapid prototyping, but awful in production code, especially when fine-tuning your mapping (database sequence names in Java annotations attributes?!?) So here is my orm.xml excerpt:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&amp;lt;entity class="com.blogspot.nurkiewicz.hades.MoneyTransfer"&amp;gt;&lt;br /&gt;    &amp;lt;attributes&amp;gt;&lt;br /&gt;        &amp;lt;id name="id"&amp;gt;&lt;br /&gt;            &amp;lt;generated-value/&amp;gt;&lt;br /&gt;        &amp;lt;/id&amp;gt;&lt;br /&gt;        &amp;lt;basic name="date" optional="false"&amp;gt;&lt;br /&gt;            &amp;lt;temporal&amp;gt;DATE&amp;lt;/temporal&amp;gt;&lt;br /&gt;        &amp;lt;/basic&amp;gt;&lt;br /&gt;        &amp;lt;basic name="amount" optional="false"&amp;gt;&lt;br /&gt;            &amp;lt;column precision="20" scale="2"/&amp;gt;&lt;br /&gt;        &amp;lt;/basic&amp;gt;&lt;br /&gt;        &amp;lt;many-to-one name="from" optional="false"&amp;gt;&lt;br /&gt;            &amp;lt;cascade&amp;gt;&lt;br /&gt;                &amp;lt;cascade-all/&amp;gt;&lt;br /&gt;            &amp;lt;/cascade&amp;gt;&lt;br /&gt;        &amp;lt;/many-to-one&amp;gt;&lt;br /&gt;        &amp;lt;many-to-one name="to" optional="false"&amp;gt;&lt;br /&gt;            &amp;lt;cascade&amp;gt;&lt;br /&gt;                &amp;lt;cascade-all/&amp;gt;&lt;br /&gt;            &amp;lt;/cascade&amp;gt;&lt;br /&gt;        &amp;lt;/many-to-one&amp;gt;&lt;br /&gt;    &amp;lt;/attributes&amp;gt;&lt;br /&gt;&amp;lt;/entity&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;entity class="com.blogspot.nurkiewicz.hades.Account"&amp;gt;&lt;br /&gt;    &amp;lt;attributes&amp;gt;&lt;br /&gt;        &amp;lt;id name="id"&amp;gt;&lt;br /&gt;            &amp;lt;generated-value/&amp;gt;&lt;br /&gt;        &amp;lt;/id&amp;gt;&lt;br /&gt;        &amp;lt;basic name="ownerName" optional="false"&amp;gt;&lt;br /&gt;            &amp;lt;column length="120"/&amp;gt;&lt;br /&gt;        &amp;lt;/basic&amp;gt;&lt;br /&gt;    &amp;lt;/attributes&amp;gt;&lt;br /&gt;&amp;lt;/entity&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We all love XML, admit it! And finally unit test itself:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java; highlight: [10]"&gt;@RunWith(SpringJUnit4ClassRunner.class)&lt;br /&gt;@ContextConfiguration&lt;br /&gt;@Transactional&lt;br /&gt;public class MoneyTransferDaoTest {&lt;br /&gt;&lt;br /&gt;    @PersistenceContext&lt;br /&gt;    private EntityManager em;&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private MoneyTransferDao dao;&lt;br /&gt;&lt;br /&gt;    @Resource&lt;br /&gt;    private AccountDao accountDao;&lt;br /&gt;&lt;br /&gt;    @Test&lt;br /&gt;    public void shouldReturnNothingWhenReadingNotExistingMoneyTransfer() throws Exception {&lt;br /&gt;        //when&lt;br /&gt;        final MoneyTransfer moneyTransfer = dao.readByPrimaryKey(17L);&lt;br /&gt;&lt;br /&gt;        //then&lt;br /&gt;        assertThat(moneyTransfer).isNull();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Test&lt;br /&gt;    public void shouldReturnExistingMoneyTransfer() throws Exception {&lt;br /&gt;        //given&lt;br /&gt;        final MoneyTransfer newTransfer = new MoneyTransfer();&lt;br /&gt;        em.persist(newTransfer);&lt;br /&gt;&lt;br /&gt;        //when&lt;br /&gt;        final MoneyTransfer moneyTransfer = dao.readByPrimaryKey(newTransfer.getId());&lt;br /&gt;&lt;br /&gt;        //then&lt;br /&gt;        assertThat(moneyTransfer).isNotNull();&lt;br /&gt;        assertThat(moneyTransfer.getId()).isEqualTo(newTransfer.getId());&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;//...&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Following Spring unit test naming convention, this test case will start Spring context located in &lt;span style="font-style: italic;"&gt;MoneyTransferDaoTest-context.xml&lt;/span&gt;:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml; highlight: [39]"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;       xmlns:context="http://www.springframework.org/schema/context"&lt;br /&gt;       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:hades="http://schemas.synyx.org/hades"&lt;br /&gt;       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&lt;br /&gt;            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&lt;br /&gt;            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://schemas.synyx.org/hades http://schemas.synyx.org/hades/hades.xsd"&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;tx:annotation-driven transaction-manager="transactionManager"/&amp;gt;&lt;br /&gt;    &amp;lt;context:annotation-config/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/&amp;gt;&lt;br /&gt;    &amp;lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&amp;gt;&lt;br /&gt;        &amp;lt;property name="driverClassName" value="org.h2.Driver"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="url" value="jdbc:h2:mem:moneytransfers;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&amp;gt;&lt;br /&gt;        &amp;lt;property name="entityManagerFactory" ref="entityManagerFactory"/&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&amp;gt;&lt;br /&gt;        &amp;lt;property name="dataSource" ref="dataSource"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="jpaVendorAdapter" ref="jpaAdapter"/&amp;gt;&lt;br /&gt;        &amp;lt;property name="jpaProperties"&amp;gt;&lt;br /&gt;            &amp;lt;props&amp;gt;&lt;br /&gt;                &amp;lt;prop key="hibernate.format_sql"&amp;gt;true&amp;lt;/prop&amp;gt;&lt;br /&gt;                &amp;lt;prop key="hibernate.ejb.naming_strategy"&amp;gt;org.hibernate.cfg.DefaultComponentSafeNamingStrategy&amp;lt;/prop&amp;gt;&lt;br /&gt;                &amp;lt;prop key="hibernate.hbm2ddl.auto"&amp;gt;update&amp;lt;/prop&amp;gt;&lt;br /&gt;            &amp;lt;/props&amp;gt;&lt;br /&gt;        &amp;lt;/property&amp;gt;&lt;br /&gt;    &amp;lt;/bean&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;hades:dao-config base-package="com.blogspot.nurkiewicz.hades"/&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now run the test, it should pass. That's right, we haven't written even single line of DAO code and still our &lt;span style="font-style: italic;"&gt;MoneyTransferDao&lt;/span&gt;, injected in line 10, works perfectly! The whole magic is hidden under line 39 of Spring context file. hades:dao-config element discovers all interfaces extending &lt;span style="font-style: italic;"&gt;org.synyx.hades.dao.GenericDao&amp;lt;T, PK extends Serializable&amp;gt;&lt;/span&gt; and dynamically implements them based on their generic types. We automatically get methods like:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public interface MoneyTransferDao extends GenericDao&amp;lt;MoneyTransfer, Long&amp;gt; {&lt;br /&gt;    MoneyTransfer readByPrimaryKey(final Long primaryKey);&lt;br /&gt;    Page&amp;lt;MoneyTransfer&amp;gt; readAll(final Pageable pageable);&lt;br /&gt; //...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Yep, Hades also provides built in support for paging and sorting – especially annoying when has to be implemented and tested manually for several entities.&lt;br /&gt;&lt;br /&gt;OK, to be honest, there was no magic in what we have seen until now and you might have even written similar utilities for your internal usage. Although &lt;span style="font-style: italic;"&gt;GenericDao&lt;/span&gt; has some built in methods that cover, let's say, 50% of typical queries, what about the rest? What if I would like to find all money transfers with amount greater than given value?&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public interface MoneyTransferDao extends GenericDao&amp;lt;MoneyTransfer, Long&amp;gt; {&lt;br /&gt;    List&amp;lt;MoneyTransfer&amp;gt; findByAmountGreaterThan(BigDecimal amount);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Where to put the implementation of this custom DAO method? Well, now the magic part begins – nowhere! Similar to GORM, Hades will parse this method name and create the query for you. All you have to do is to follow some naming convention. No custom queries, no boilerplate code. Hades will even set the parameter for you. It's such a clever tool, that simply by adding argument of type Pageable Hades will include paging clauses (like TOP, LIMIT, OFFSET, etc.):&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public interface MoneyTransferDao extends GenericDao&amp;lt;MoneyTransfer, Long&amp;gt; {&lt;br /&gt;    List&amp;lt;MoneyTransfer&amp;gt; findByDateGreaterThan(Calendar date, Pageable page);&lt;br /&gt; //...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;moneyTransferDao.findByDateGreaterThan(&lt;br /&gt;        Calendar.getInstance(),&lt;br /&gt;        new PageRequest(1, 20, new Sort(Order.ASCENDING, "amount")));&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;So, Hades can transparently implement basic CRUD operations with sorting/paging support. It can also synthesize queries based only on interface method name and arguments. But once you discover that this feature is very limited (for instance it does not support &lt;span style="font-style: italic;"&gt;Not&lt;/span&gt;, &lt;span style="font-style: italic;"&gt;Like&lt;/span&gt;, &lt;span style="font-style: italic;"&gt;IsNull&lt;/span&gt;, &lt;span style="font-style: italic;"&gt;In&lt;/span&gt; and other modifiers known from &lt;a href="http://www.grails.org/GORM"&gt;GORM&lt;/a&gt;, see issue &lt;a href="http://redmine.synyx.org/issues/274"&gt;#274&lt;/a&gt;), you'll eventually end up with a need for a custom JPA query like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: xml"&gt;&amp;lt;named-query name="MoneyTransfer.getAverageTransferAmountSince"&amp;gt;&lt;br /&gt;    &amp;lt;query&amp;gt;&lt;br /&gt;        SELECT AVG(transfer.amount)&lt;br /&gt;        FROM MoneyTransfer transfer&lt;br /&gt;        WHERE transfer.date &amp;gt; ?1&lt;br /&gt;    &amp;lt;/query&amp;gt;&lt;br /&gt;&amp;lt;/named-query&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now we add method in our DAO interface that will execute this query:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;public interface MoneyTransferDao extends GenericDao&amp;lt;MoneyTransfer, Long&amp;gt; {&lt;br /&gt;    BigDecimal getAverageTransferAmountSince(Calendar since);&lt;br /&gt; //...&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The implementation is trivial (see screenshot at the beginning of this article), so Hades implements this method for us as well. Name of the method matches name of the named query (prefixed by the  entity name), which is enough for Hades. Few lines of code (repeated hundreds of times) are saved.&lt;br /&gt;&lt;br /&gt;But what if you really want to implement custom DAO method, but still having all other methods implemented for you? There are two reasons: do some validation and parameters transformation before the query is executed and post-process results after query execution.  The latter reason can be often eliminated using not very well known JPA query language feature. Take for instance this query:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: plain"&gt;SELECT transfer.amount, transfer.from.id, transfer.to.id&lt;br /&gt;FROM MoneyTransfer transfer&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;It will return &lt;span style="font-style: italic;"&gt;List&amp;lt;Object[]&amp;gt;&lt;/span&gt;, which isn't very object-orientish. Instead, our DAO layer should do some transformation and return more user friendly object. JPA can do this for you with this simple expression:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: plain"&gt;SELECT NEW RawMoneyTransfer(transfer.amount, transfer.from.id, transfer.to.id)&lt;br /&gt;FROM MoneyTransfer transfer&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;RawMoneyTransfer&lt;/span&gt; is any Java object (not necessarily JPA entity) with constructor matching given parameters being only requirement. But once again, what if you really need custom DAO method? For example JPA does not define any date expressions, so there is no straightforward way to define "&lt;span style="font-style: italic;"&gt;30 days before today&lt;/span&gt;" when generating report for last month in JPA QL. Unfortunately, Hades way of defining custom DAO methods is troublesome and a bit counterintuitive. I will open an issue and try to introduce simpler (although harder in implementation) solution. Meanwhile take a look at great Hades reference &lt;a href="http://redmine.synyx.org/projects/hades/wiki"&gt;documentation&lt;/a&gt; for further details.&lt;br /&gt;&lt;br /&gt;Hades also has support for entity auditing, but &lt;a href="http://www.jboss.org/envers"&gt;Envers&lt;/a&gt;, being part of Hibernate portfolio, is probably more mature solution. As of version 2.0 it also has built in support to participate in Spring transactions. As you have seen, Hades aims to increase your productivity by writing less code, less unit tests (comprehensive unit testing of Hades-generated methods isn't necessary) and promoting convention over configuration approach. It still has some limitations but give it a try, I recently will.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-4222227573134757128?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/4222227573134757128/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/07/hades-dry-principle-in-jpaspring.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/4222227573134757128'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/4222227573134757128'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/07/hades-dry-principle-in-jpaspring.html' title='Hades: DRY principle in JPA/Spring development'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/_P3ewsGQzHn0/TDOc1Bj2PWI/AAAAAAAAAWE/t7wRzGF28LI/s72-c/Hades.png' height='72' width='72'/><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-7756002699879628937</id><published>2010-05-19T23:35:00.004+02:00</published><updated>2010-05-20T18:43:32.823+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='logging'/><category scheme='http://www.blogger.com/atom/ns#' term='commons'/><title type='text'>Clean code, clean logs: easy to read, easy to parse (10/10)</title><content type='html'>There are two groups of receivers particularly interested in your application logs: human beings (you might disagree, but programmers belong to this group as well) and computers (typically shell scripts written by system administrators). Logs should be suitable for both of these groups. If someone looking from behind your back at your application logs sees:&lt;br /&gt;&lt;br /&gt;&lt;div style="text-align: center;"&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_P3ewsGQzHn0/S_RbsVXuRzI/AAAAAAAAAVM/IcD0g7MqJaU/s1600/The.Matrix.glmatrix.png"&gt;&lt;img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 200px; height: 160px;" src="http://2.bp.blogspot.com/_P3ewsGQzHn0/S_RbsVXuRzI/AAAAAAAAAVM/IcD0g7MqJaU/s200/The.Matrix.glmatrix.png" alt="" id="BLOGGER_PHOTO_ID_5473100264371013426" border="0" /&gt;&lt;/a&gt;&lt;span style="font-size:78%;"&gt;from &lt;a href="http://commons.wikimedia.org/wiki/Category:The_Matrix"&gt;Wikipedia&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;then you were probably not reading my tips carefully enough. The reference to famous &lt;a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"&gt;Clean code&lt;/a&gt; book in the title of this series is not accidental: logs should be readable and easy to understand just like the code should.&lt;br /&gt;&lt;br /&gt;On the other hand, if your application produces half GiB of logs each hour, no man and no graphical text editor will ever manage to read them entirely. This is where old-school &lt;a href="http://www.gnu.org/software/grep"&gt;grep&lt;/a&gt;, &lt;a href="http://www.gnu.org/software/sed"&gt;sed&lt;/a&gt; and &lt;a href="http://www.gnu.org/software/gawk"&gt;awk&lt;/a&gt; come in handy. If it is possible, try to write logging messages in such a way, that they could be understood both by humans and computers, e.g. avoid formatting of numbers, use patterns that can be easily recognized by regular expressions, etc. If it is not possible, print the data in two formats:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;log.debug("Request TTL set to: {} ({})", new Date(ttl), ttl);&lt;br /&gt;// Request TTL set to: Wed Apr 28 20:14:12 CEST 2010 (1272478452437)&lt;br /&gt;&lt;br /&gt;final String duration = DurationFormatUtils.formatDurationWords(durationMillis, true, true);&lt;br /&gt;log.info("Importing took: {}ms ({})", durationMillis, duration);&lt;br /&gt;//Importing took: 123456789ms (1 day 10 hours 17 minutes 36 seconds)&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Computers will appreciate "ms after 1970 epoch" time format, while people would be delighted seeing "&lt;span style="font-style: italic;"&gt;1 day 10 hours 17 minutes 36 seconds&lt;/span&gt;" text. BTW take a look at &lt;a href="http://commons.apache.org/lang/api-release/org/apache/commons/lang/time/DateFormatUtils.html"&gt;DurationFormatUtils&lt;/a&gt;, nice tool.&lt;br /&gt;&lt;br /&gt;I thought this article is going to be short, but after writing it I decided to split it into 10 parts, each in separate post. Hope you enjoyed my logging series, although still not everything has been covered. This only proves how logging is important and how many pitfalls should be avoided. Remember, logging code should also be clean and reading your logs is supposed to be as pleasant as reading your code.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-use-appropriate.html"&gt;Clean code, clean logs: use appropriate tools (1/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-logging-levels.html"&gt;Clean code, clean logs: logging levels are there for you (2/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-do-you-know-what.html"&gt;Clean code, clean logs: do you know what you are logging? (3/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-avoid-side.html"&gt;Clean code, clean logs: avoid side effects (4/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-concise-and.html"&gt;Clean code, clean logs: concise and descriptive (5/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-tune-your-pattern.html"&gt;Clean code, clean logs: tune your pattern (6/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-log-method.html"&gt;Clean code, clean logs: log method arguments and return values (7/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-watch-out-for.html"&gt;Clean code, clean logs: watch out for external systems (8/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-log-exceptions.html"&gt;Clean code, clean logs: log exceptions properly (9/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Clean code, clean logs: easy to read, easy to parse (10/10)&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-7756002699879628937?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/7756002699879628937/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-easy-to-read-easy.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/7756002699879628937'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/7756002699879628937'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-easy-to-read-easy.html' title='Clean code, clean logs: easy to read, easy to parse (10/10)'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_P3ewsGQzHn0/S_RbsVXuRzI/AAAAAAAAAVM/IcD0g7MqJaU/s72-c/The.Matrix.glmatrix.png' height='72' width='72'/><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-3334557185902869182</id><published>2010-05-19T00:10:00.004+02:00</published><updated>2010-05-20T18:42:05.679+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='slf4j'/><category scheme='http://www.blogger.com/atom/ns#' term='logging'/><title type='text'>Clean code, clean logs: log exceptions properly (9/10)</title><content type='html'>First of all, avoid logging exceptions, let your framework or container (whatever it is) do it for you*. Logging exceptions is one of the most important roles of logging at all, but many programmers tend to treat logging as a way to handle the exception. They sometimes return default value (typically null, 0 or empty string) and pretend that nothing has happened. Other times they first log the exception and then wrap it and throw back:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;log.error("IO exception", e);&lt;br /&gt;throw new MyCustomException(e);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This construct will almost always print the same stack trace two times, because something will eventually catch &lt;span style="font-family: courier new;"&gt;MyCustomException&lt;/span&gt; and log its cause. Log or wrap and throw back (which is preferable), never both, otherwise your logs will be confusing.&lt;br /&gt;&lt;br /&gt;But if we really do WANT to log the exception? For some reason (&lt;span style="font-style: italic;"&gt;because we don’t read APIs and documentation?&lt;/span&gt;), about half of the logging statements I see are wrong. Quick quiz, which of the following  log the NPE properly?&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;try {&lt;br /&gt;    Integer x = null;&lt;br /&gt;    ++x;&lt;br /&gt;} catch (Exception e) {&lt;br /&gt;    log.error(e);        //A&lt;br /&gt;    log.error(e, e);        //B&lt;br /&gt;    log.error("" + e);        //C&lt;br /&gt;    log.error(e.toString());        //D&lt;br /&gt;    log.error(e.getMessage());        //E&lt;br /&gt;    log.error(null, e);        //F&lt;br /&gt;    log.error("", e);        //G&lt;br /&gt;    log.error("{}", e);        //H&lt;br /&gt;    log.error("{}", e.getMessage());        //I&lt;br /&gt;    log.error("Error reading configuration file: " + e);        //J&lt;br /&gt;    log.error("Error reading configuration file: " + e.getMessage());        //K&lt;br /&gt;    log.error("Error reading configuration file", e);        //L&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Surprisingly, only G and preferably L are correct! A and B don’t even compile in &lt;a href="http://www.slf4j.org"&gt;SLF4J&lt;/a&gt;, others discard stack traces and/or print improper messages. For example, E won’t print anything as NPE typically don’t provide any exception message and stack trace won’t be printed as well. Remember, first argument is always the text message, write something about the nature of the problem. Don’t include exception message, as it will be printed automatically after the log statement,  preceding stack trace. But in order to do so, you must pass the exception itself as the second argument.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;* There is one, ekhem, &lt;span style="font-style: italic;"&gt; exception&lt;/span&gt; to this rule: if you throw exceptions from some remote service (RMI, EJB remote session bean, etc.), that are capable to serialize exceptions, make sure all of them are available to the client (are part of the API). Otherwise the client will receive &lt;span style="font-family: courier new;"&gt;NoClassDefFoundError: SomeFancyException&lt;/span&gt; instead of "true" error.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-use-appropriate.html"&gt;Clean code, clean logs: use appropriate tools (1/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-logging-levels.html"&gt;Clean code, clean logs: logging levels are there for you (2/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-do-you-know-what.html"&gt;Clean code, clean logs: do you know what you are logging? (3/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-avoid-side.html"&gt;Clean code, clean logs: avoid side effects (4/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-concise-and.html"&gt;Clean code, clean logs: concise and descriptive (5/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-tune-your-pattern.html"&gt;Clean code, clean logs: tune your pattern (6/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-log-method.html"&gt;Clean code, clean logs: log method arguments and return values (7/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-watch-out-for.html"&gt;Clean code, clean logs: watch out for external systems (8/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Clean code, clean logs: log exceptions properly (9/10)&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-easy-to-read-easy.html"&gt;Clean code, clean logs: easy to read, easy to parse (10/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-3334557185902869182?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/3334557185902869182/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-log-exceptions.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/3334557185902869182'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/3334557185902869182'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-log-exceptions.html' title='Clean code, clean logs: log exceptions properly (9/10)'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-8466122454784362301</id><published>2010-05-17T22:46:00.006+02:00</published><updated>2010-05-20T18:41:22.100+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='esb'/><category scheme='http://www.blogger.com/atom/ns#' term='logging'/><category scheme='http://www.blogger.com/atom/ns#' term='apache cxf'/><category scheme='http://www.blogger.com/atom/ns#' term='web services'/><category scheme='http://www.blogger.com/atom/ns#' term='mule'/><title type='text'>Clean code, clean logs: watch out for external systems (8/10)</title><content type='html'>This is the special case of the previous &lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-log-method.html"&gt;tip&lt;/a&gt;: if you communicate with any external system, consider logging every piece of data that comes out from your application and gets in. Period. Integration is a tough job and diagnosing problems between two applications (think two different vendors, environments, technology stacks and teams) is particularly hard. Recently, for example, we've discovered that logging full messages contents, &lt;a href="http://cxf.apache.org/docs/debugging-and-logging.html"&gt;including&lt;/a&gt; SOAP and HTTP headers in &lt;a href="http://cxf.apache.org"&gt;Apache CXF&lt;/a&gt; web services is extremely useful during integration and system testing.&lt;br /&gt;&lt;br /&gt;This is a big overhead and if performance is an issue, you can always disable logging. But what is the point of having fast, but broken application, that no one can fix? Be extra careful when integrating with external systems and prepare to pay that cost. If you are lucky and all your integration is handled by ESB, bus is probably the best place to log every incoming request and response. See for example &lt;a href="http://www.mulesoft.org"&gt;Mule&lt;/a&gt;s' &lt;a href="http://www.mulesoft.org/documentation/display/MULE2USER/Configuring+Components"&gt;&amp;lt;log-component/&amp;gt;&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Sometimes the amount of information exchanged with external systems makes it unacceptable to log everything. On the other hand during testing and for short period of time on production (for example when something wrong is happening) we would like to have everything saved in logs and are ready to pay performance cost. This can be achieved by carefully using logging levels. Just take a look at the following idiom:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;Collection&amp;lt;Integer&amp;gt; requestIds = //...&lt;br /&gt;&lt;br /&gt;if(log.isDebugEnabled())&lt;br /&gt;    log.debug("Processing ids: {}", requestIds);&lt;br /&gt;else&lt;br /&gt;    log.info("Processing ids size: {}", requestIds.size());&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If this particular logger is configured to log &lt;span style="font-family: courier new;"&gt;DEBUG&lt;/span&gt; messages, it will print the whole &lt;span style="font-family: courier new;"&gt;requestIds&lt;/span&gt; collection contents. But if it is configured to print &lt;span style="font-family: courier new;"&gt;INFO&lt;/span&gt; messages, only the size of collection will be outputted. If you are wondering why I forgot about &lt;span style="font-family: courier new;"&gt;isInfoEnabled()&lt;/span&gt; condition, go back to this &lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-logging-levels.html"&gt;tip&lt;/a&gt;. One thing worth mentioning is that &lt;span style="font-family: courier new;"&gt;requestIds&lt;/span&gt; collection should not be &lt;span style="font-family: courier new;"&gt;null&lt;/span&gt; in this case. Although it will be logged correctly as null if &lt;span style="font-family: courier new;"&gt;DEBUG&lt;/span&gt; is enabled, but big fat &lt;span style="font-family: courier new;"&gt;NullPointerException&lt;/span&gt; will be thrown if logger is configured to &lt;span style="font-family: courier new;"&gt;INFO&lt;/span&gt;. Remember my lesson about &lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-avoid-side.html"&gt;side effects&lt;/a&gt;?&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-use-appropriate.html"&gt;Clean code, clean logs: use appropriate tools (1/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-logging-levels.html"&gt;Clean code, clean logs: logging levels are there for you (2/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-do-you-know-what.html"&gt;Clean code, clean logs: do you know what you are logging? (3/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-avoid-side.html"&gt;Clean code, clean logs: avoid side effects (4/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-concise-and.html"&gt;Clean code, clean logs: concise and descriptive (5/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-tune-your-pattern.html"&gt;Clean code, clean logs: tune your pattern (6/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-log-method.html"&gt;Clean code, clean logs: log method arguments and return values (7/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Clean code, clean logs: watch out for external systems (8/10)&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-log-exceptions.html"&gt;Clean code, clean logs: log exceptions properly (9/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-easy-to-read-easy.html"&gt;Clean code, clean logs: easy to read, easy to parse (10/10)&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6753769565491687768-8466122454784362301?l=nurkiewicz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nurkiewicz.blogspot.com/feeds/8466122454784362301/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-watch-out-for.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/8466122454784362301'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6753769565491687768/posts/default/8466122454784362301'/><link rel='alternate' type='text/html' href='http://nurkiewicz.blogspot.com/2010/05/clean-code-clean-logs-watch-out-for.html' title='Clean code, clean logs: watch out for external systems (8/10)'/><author><name>Tomasz Nurkiewicz</name><uri>https://profiles.google.com/104737943609231749396</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh3.googleusercontent.com/-I9y0FYiRHSM/AAAAAAAAAAI/AAAAAAAAAfQ/cW9vNTS_1ps/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6753769565491687768.post-6769129648169860524</id><published>2010-05-16T18:37:00.003+02:00</published><updated>2010-05-16T18:41:20.729+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='warsaw-jug'/><category scheme='http://www.blogger.com/atom/ns#' term='jpa'/><category scheme='http://www.blogger.com/atom/ns#' term='gorm'/><category scheme='http://www.blogger.com/atom/ns#' term='hades'/><category scheme='http://www.blogger.com/atom/ns#' term='conferences'/><title type='text'>Impressions after GeeCON 2010</title><content type='html'>Two days ago I came back from &lt;a href="http://en.wikipedia.org/wiki/Pozna%C3%85%C2%84"&gt;Poznań&lt;/a&gt;, Poland, where second edition  of &lt;a href="http://2010.geecon.org/"&gt;GeeCON&lt;/a&gt; conference took place. After &lt;a href="http://nurkiewicz.blogspot.com/2009/05/relacja-z-geecon-2009-w-krakowie.html"&gt;attending the first edition&lt;/a&gt; my expectations were very high and sadly I left Poznań a bit disappointed. It is most likely a matter of my personal taste, but still just a few presentations are worth mentioning.&lt;br /&gt;&lt;br /&gt;The biggest surprise and most fabulous piece of lecture has been given by &lt;a href="http://www.cs.put.poznan.pl/dweiss/xml/index.xml?lang=en"&gt;&lt;span style="font-weight: bold;"&gt;Dawid Weiss&lt;/span&gt;&lt;/a&gt; on &lt;span style="font-style: italic;"&gt;Java in high-performance computing&lt;/span&gt;. He managed to combine great show with lots of non-trivial examples. Lots of humour, brilliant slides and great contact with the audience. One of the most charismatic speakers I have seen. But on the other hand it was not a stand-up comedy, where you have lots of fun during the lecture but you don’t gain anything useful after them. Dawid given plenty of examples and micro-benchmarks during his speech, making us believe that tuning, benchmarking and even studying bytecode and assembly language might be interesting. Bravo for Dawid, I was really proud to see Polish speaker doing so well. Dawid also mentioned about his library &lt;a href="http://labs.carrotsearch.com/hppc.html"&gt;HPPC&lt;/a&gt;, besides I found pretty amazing search clustering tool called &lt;a href="http://search.carrot2.org/"&gt;Carrot2&lt;/a&gt;, authored by his company.&lt;br /&gt;&lt;br /&gt;Dawids’ speech has been mentioned several times by &lt;a href="http://hollycummins.blogspot.com/"&gt;&lt;span style="font-weight: bold;"&gt;Holly Cummins&lt;/span&gt;&lt;/a&gt; in her lecture: &lt;span style="font-style: italic;"&gt;Java Performance Tuning - not so scary after all&lt;/span&gt;. It was quite good presentation with nice demo and good slides. It is true that all performance-related Java speeches are similar (few months ago I have seen &lt;a style="font-weight: bold;" href="http://www.kodewerk.com/"&gt;Kirk Pepperdine&lt;/a&gt; presentation on &lt;a href="http://groups.google.com/group/warszawa-jug"&gt;Warsaw JUG&lt;/a&gt; and it had pretty similar structure) but still it is worth to know as much as possible when you need to instantly discover performance bottlenecks in your application.&lt;br /&gt;&lt;br /&gt;But before Holly I must mention about &lt;a href="http://www.java.net/blogs/edburns"&gt;&lt;span style="font-weight: bold;"&gt;Ed Burns&lt;/span&gt;&lt;/a&gt;’ talk &lt;span style="font-style: italic;"&gt;Secrets of the Rockstar Programmers&lt;/span&gt;. Presentation was based mainly on &lt;a href="http://www.amazon.com/Secrets-Rock-Star-Programmers-Riding/dp/0071490833"&gt;his book&lt;/a&gt; and consisted many audio-video interviews. Two things that stayed in my mind are levels of programmers ignorance and underlying the importance of using your good tools. Learning all these silly keyboard shortcuts and knowing absolutely everything about your debugger capabilities is important and makes you much more productive in both reading and writing code.&lt;br /&gt;&lt;br /&gt;&lt;a style="font-weight: bold;" href="http://www.olivergierke.de/"&gt;Oliver Gierkes'&lt;/a&gt; talk maybe wasn’t outstanding, but the tool he presented, &lt;a href="http://hades.synyx.org/"&gt;&lt;span style="font-weight: bold;"&gt;Hades&lt;/span&gt;&lt;/a&gt;, was. If you are writing DAO layer using JPA, Hades greatly simplifies development. Basic idea behind this tool is that you provide only an interface for DAO service and Hades will do its best to dynamically implement your DAO. Basic CRUD with paging and sorting is given out-of-box, but Hades can also generate queries based on method name and arguments. If you enjoy &lt;a href="http://www.grails.org/GORM"&gt;GORM&lt;/a&gt;, definitely try this library. And my enthusiasm has nothing to do with the &lt;a href="http://www.springsource.com/"&gt;SpringSource&lt;/a&gt; memory stick I got for asking a question ;-).&lt;br /&gt;&lt;br /&gt;Although I am a backend guy, I found &lt;span style="font-style: italic;"&gt;HTML5 Web Sockets: All-You-Can-Eat Real Time!&lt;/span&gt; presentation by &lt;a href="http://www.kaazing.com/"&gt;&lt;span style="font-weight: bold;"&gt;Peter Lubbers&lt;/span&gt;&lt;/a&gt; very interesting. Co-author of &lt;a href="http://www.amazon.com/Pro-HTML5-Programming-Application-Development/dp/1430227907"&gt;&lt;span style="font-style: italic;"&gt;Pro HTML5 Programming&lt;/span&gt;&lt;/a&gt; uncovered weaknesses of &lt;a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29"&gt;AJAX&lt;/a&gt; and &lt;a href="http://en.wikipedia.org/wiki/Comet_%28programming%29"&gt;Comet&lt;/a&gt; and presented a remedy: &lt;a href="http://en.wikipedia.org/wiki/Web_Sockets"&gt;Web Sockets&lt;/a&gt;. After some brief theory behind asynchronous web communication, he showed few examples of web applications using Comet and web sockets. &lt;a href="http://
