<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Java and Spring development</title>
	<atom:link href="http://blog.espenberntsen.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.espenberntsen.net</link>
	<description></description>
	<lastBuildDate>Wed, 22 May 2013 20:20:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.espenberntsen.net' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/b060b2b11c6dc61ea2a0e381a3f1cf6f?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Java and Spring development</title>
		<link>http://blog.espenberntsen.net</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.espenberntsen.net/osd.xml" title="Java and Spring development" />
	<atom:link rel='hub' href='http://blog.espenberntsen.net/?pushpress=hub'/>
		<item>
		<title>SLF4J logging with Log4J and JCL</title>
		<link>http://blog.espenberntsen.net/2010/06/06/slf4j-logging-with-log4j-and-jcl/</link>
		<comments>http://blog.espenberntsen.net/2010/06/06/slf4j-logging-with-log4j-and-jcl/#comments</comments>
		<pubDate>Sun, 06 Jun 2010 19:02:16 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Logging]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JCL]]></category>
		<category><![CDATA[Log4J]]></category>
		<category><![CDATA[Logback]]></category>
		<category><![CDATA[SLF4J]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blog.espenberntsen.net/?p=413</guid>
		<description><![CDATA[More and more frameworks logs with the SLF4J framework. Many applications must relate to several different logging frameworks. This tutorial shows how one logger framework can handle log messages from other logging frameworks with SLF4J as the central part. The demo application used in this tutorial logs with Log4J and have dependencies to Spring and [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=413&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>More and more frameworks logs with the SLF4J framework. Many applications must relate to several different logging frameworks. This tutorial shows how one logger framework can handle log messages from other logging frameworks with SLF4J as the central part.</p>
<p>The demo application used in this tutorial logs with Log4J and have dependencies to Spring and Hibernate. Here&#8217;s the different loggers and where they are used:</p>
<ul>
<li>JCL <a href="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png"><img class="alignnone size-full wp-image-490" style="border:0 none;margin:0;" title="arrow-small" src="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png?w=700" alt=""   /></a> Spring</li>
<li>SLF4J <a href="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png"><img style="border:0 none;margin:0;" title="arrow-small" src="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png?w=20&#038;h=10" alt="" width="20" height="10" /></a> Hibernate 3.3+</li>
<li>Log4J <a href="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png"><img style="border:0 none;margin:0;" title="arrow-small" src="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png?w=20&#038;h=10" alt="" width="20" height="10" /></a> Demo application</li>
</ul>
<p>Log4J integrates well with JCL, but can&#8217;t handle log messages from SLF4J. This forces the use of SLF4J to connect the different loggers together.</p>
<h2>SLF4J</h2>
<p>A description of SLF4J from their <a href="http://slf4j.org/">homepage</a>:</p>
<blockquote><p>The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at <em>deployment</em> time.</p></blockquote>
<p>In addition to the extra flexibility, the API also contains a nice feature with support for arguments.</p>
<pre class="brush: java; light: true; title: ; notranslate">
logger.debug(&quot;The date is: {}&quot;, date);
</pre>
<p>The old way with Log4J:</p>
<pre class="brush: java; light: true; title: ; notranslate">
if (logger.isDebugEnabled()) {
	logger.debug(&quot;The date is: &quot; + date);
}
</pre>
<p>Both examples prints:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
 DEBUG [demo.Slf4jDemo] - &lt;The date is: Sun Jun 06 11:34:11 CEST 2010&gt;
</pre>
<p>The difference is that SLF4J doesn&#8217;t merge the dynamic and static data into a new string in the debug method, but sends the dynamic part(s) as argument(s). If the logger is configured to only log messages with info level or higher, the debug message above gets discarded without any string processing and without the need for an extra if sentence for performance reasons.</p>
<p>For information about SLF4J and its alternatives on a high level, Bruce Snyder has written a good post <a href="http://bsnyderblog.blogspot.com/2007/08/my-soapbox-for-slf4j.html">here</a>.</p>
<h2>Two scenarios that will support central log handling</h2>
<p>The first option is to bind the SLF4J logger against Log4J. It works nice and enables management of JCL and SLF4J log messages from the Log4J configuration. In my case with the <span style="color:#000080;">log4j.properties</span> file.</p>
<p><a href="http://espenberntsen.files.wordpress.com/2010/06/log4j-with-slf4j-and-jcl1.png"><img class="alignnone size-full wp-image-482" style="border:0 none;" title="log4j-with-slf4j-and-jcl" src="http://espenberntsen.files.wordpress.com/2010/06/log4j-with-slf4j-and-jcl1.png?w=700&#038;h=124" alt="" width="700" height="124" /></a></p>
<p>The other alternative which is also recommended in the SLF4J&#8217;s manual is to log messages to the SLF4J framework and bind SLF4J to the new <a href="http://logback.qos.ch/">logback</a> framework like this:</p>
<p><a href="http://espenberntsen.files.wordpress.com/2010/06/slf4j-with-jcl-and-log4j.png"><img class="alignnone size-full wp-image-483" style="border:0 none;" title="slf4j-with-jcl-and-log4j" src="http://espenberntsen.files.wordpress.com/2010/06/slf4j-with-jcl-and-log4j.png?w=700&#038;h=216" alt="" width="700" height="216" /></a></p>
<p>With the second solution, SLF4J&#8217;s binder framework will receive all the log messages.</p>
<h2>SLF4J and and binding against a backend logger</h2>
<p>You can only bind against one backend logging framework. With no binding framework on the classpath, the silent logger (NOP) will be used by default.</p>
<p>The frameworks supported by SLF4J:</p>
<ul>
<li>Logback-classic</li>
<li>Log4J</li>
<li>java.util.logging (JUL)</li>
<li>Simple</li>
<li>NOP</li>
<li>Jakarta Commons Logging (JCL)</li>
</ul>
<p>The preferred backend logging framework with SLF4J is <a href="http://logback.qos.ch/">Logback</a>.</p>
<h2>Logback</h2>
<p>Logbac is written by the same people who have written SLF4J. It natively implements the SLF4J API.</p>
<p>Their description of the framework:</p>
<blockquote><p>The logback-classic module can be assimilated to a 		significantly improved version of log4j</p></blockquote>
<p>A nice feature with Logback is that you can see which jar file that contains a class in the stacktrace. And if the jar file contains an <span style="color:#000080;">Implemented-Version</span> property in the <span style="color:#000080;">/META-INF/MANIFEST.MF </span>file, then you can see the version number to the right for the jar file name.</p>
<pre class="brush: plain; highlight: [5]; light: true; title: ; notranslate">
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'unkownBeanId'
        is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition
        (DefaultListableBeanFactory.java:510)
        ~[org.springframework.beans-3.0.2.RELEASE.jar:3.0.2.RELEASE]
</pre>
<p>You can find more reasons to upgrade from Log4J to Logback on their site <a href="http://logback.qos.ch/reasonsToSwitch.html">here</a>.</p>
<h2>Logging with the SLF4J API</h2>
<p>A simple example:</p>
<pre class="brush: java; highlight: [3,4,8]; light: true; title: ; notranslate">
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Slf4jDemo {

	private final Logger logger = LoggerFactory.getLogger(Slf4jDemo.class);

	public void demo() {
		Date date = new Date();

		logger.debug(&quot;The date is: {}&quot;, date);
	}

	public static void main(String[] args) {
		new Slf4jDemo().demo();
	}
}
</pre>
<p>A basic logback.xml configuration file:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;configuration&gt;
  &lt;appender name=&quot;stdout&quot;&gt;
    &lt;encoder&gt;
      %-5p [%c] - &lt;%m&gt;%n
    &lt;/encoder&gt;
  &lt;/appender&gt;
  &lt;logger name=&quot;demo&quot; level=&quot;DEBUG&quot;/&gt;
  &lt;root level=&quot;WARN&quot;&gt;
    &lt;appender-ref ref=&quot;stdout&quot;/&gt;
  &lt;/root&gt;
&lt;/configuration&gt;
</pre>
<h2>Handle JCL log messages with SLF4J</h2>
<p>With SLF4J&#8217;s JCL bridge implementation, you can program against the JCL API without adding the JCL jar file, since the bridge implementation contains the necessary classes to route the log messages to the SLF4J&#8217;s backend implementation.</p>
<p><a href="http://espenberntsen.files.wordpress.com/2010/06/jcl-over-slf4j.png"><img class="alignnone size-full wp-image-486" style="border:0 none;" title="jcl-over-slf4j" src="http://espenberntsen.files.wordpress.com/2010/06/jcl-overslf4j.png?w=700" alt=""   /></a></p>
<p>An example that logs with the JCL API like the Spring framework does:</p>
<pre class="brush: java; highlight: [3,4,8]; light: true; title: ; notranslate">
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ApacheCommonsLoggerDemo {

	private final static Log logger = LogFactory.getLog(ApacheCommonsLoggerDemo.class);

	public void demo() {
		Date date = new Date();

		logger.debug(&quot;The date is: &quot; + date);
	}

	public static void main(String[] args) {
		new ApacheCommonsLoggerDemo().demo();
	}
}
</pre>
<h2>Log4J messages and SLF4J</h2>
<p>Many applications logs with Log4J. These log messages can also be handled by SLF4J&#8217;s backend logger with adding the log4j-over-slf4j library to your build path. This library works similar to the JCL bridge implementation described above. The important class is the <span style="color:#000080;">org.apache.log4j.Logge</span><span style="color:#000080;">r</span> and is instantiated like this:</p>
<pre class="brush: java; light: true; title: ; notranslate">
private final Logger logger = Logger.getLogger(Log4jDemo.class);
</pre>
<h2>Summary</h2>
<p>SLF4J is the new common logging API for new open-source projects. With its facade pattern implementation, it&#8217;s a very flexible framework that let you easily integrate different logging frameworks used by the application&#8217;s dependencies. It&#8217;s also modular by nature with a loose coupling between the SLF4J API and the backend logger framework.</p>
<p>In addition to the modularity, I like the enhanced stacktrace that&#8217;s printed with the configuration illustrated in the second scenario without changing a single line of code!</p>
<p>If you in the future wants to standardize logging with SLF4J, then you can use this <a href="http://slf4j.org/migrator.html">migrator</a> that&#8217;s bundled with the SLF4J distribution and migrate your<span style="color:#000080;"> log4j.properties</span> file to a <span style="color:#000080;">logback.xml</span> file with this online <a href="http://logback.qos.ch/translator/">translator</a>.</p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/logging/'>Logging</a> Tagged: <a href='http://blog.espenberntsen.net/tag/hibernate/'>Hibernate</a>, <a href='http://blog.espenberntsen.net/tag/jcl/'>JCL</a>, <a href='http://blog.espenberntsen.net/tag/log4j/'>Log4J</a>, <a href='http://blog.espenberntsen.net/tag/logback/'>Logback</a>, <a href='http://blog.espenberntsen.net/tag/slf4j/'>SLF4J</a>, <a href='http://blog.espenberntsen.net/tag/spring/'>Spring</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=413&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/06/06/slf4j-logging-with-log4j-and-jcl/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png" medium="image">
			<media:title type="html">arrow-small</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png" medium="image">
			<media:title type="html">arrow-small</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/06/arrow1.png" medium="image">
			<media:title type="html">arrow-small</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/06/log4j-with-slf4j-and-jcl1.png" medium="image">
			<media:title type="html">log4j-with-slf4j-and-jcl</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/06/slf4j-with-jcl-and-log4j.png" medium="image">
			<media:title type="html">slf4j-with-jcl-and-log4j</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/06/jcl-overslf4j.png" medium="image">
			<media:title type="html">jcl-over-slf4j</media:title>
		</media:content>
	</item>
		<item>
		<title>Pitfalls with aspect technologies</title>
		<link>http://blog.espenberntsen.net/2010/06/05/pitfalls-with-aspectj/</link>
		<comments>http://blog.espenberntsen.net/2010/06/05/pitfalls-with-aspectj/#comments</comments>
		<pubDate>Sat, 05 Jun 2010 15:11:04 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Aspects]]></category>
		<category><![CDATA[AspectJ]]></category>

		<guid isPermaLink="false">http://blog.espenberntsen.net/?p=403</guid>
		<description><![CDATA[Even though aspect technologies are very powerful. Especially to address cross-cutting concerns like transactions, it shouldn&#8217;t be used everywhere it&#8217;s possible. The first part of this post consists of a simple example that uses AspectJ to return an unexpected value. The last part is about where aspects fits and where you should consider to avoid [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=403&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Even though aspect technologies are very powerful. Especially to address cross-cutting concerns like transactions, it shouldn&#8217;t be used everywhere it&#8217;s possible.</p>
<p>The first part of this post consists of a simple example that uses AspectJ to return an unexpected value. The last part is about where aspects fits and where you should consider to avoid it.</p>
<p>A quote from the Spider-Man movie:</p>
<blockquote><p>With great power comes great responsibility</p></blockquote>
<p>This applies to some degree to aspect technologies too. Since it can change the behaviour of an application at compilation, startup or at runtime. Even without leaving a trace in the source code.</p>
<p><a name="example"></a></p>
<h2>An aspect that changes the return value of String&#8217;s toLowerCase()</h2>
<p>To demonstrate an unexpected result from a method, I have created a StringAspect with AspectJ that returns the opposite of what the method name says.</p>
<p>When some code calls on <span style="color:#000080;">String</span>&#8216;s<span style="color:#000080;"> toLowerCase()</span> method, the <span style="color:#000080;">StringAspect</span> below reroutes the call to <span style="color:#000080;">String</span>&#8216;s <span style="color:#000080;">toUpperCase()</span> method instead:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Aspect
public class StringAspect {

	@Pointcut(&quot;call(* String.toLowerCase())&quot;)
	public void toLowerCasePointcut() {}

	@Around(&quot;toLowerCasePointcut()&quot;)
	public String toLowerCaseAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {

//		String text = (String) joinPoint.proceed();
		String text = ((String) joinPoint.getTarget()).toUpperCase();

		return text;
	}
}
</pre>
<p>To get the expected result, you can remove the comment on the line with<span style="color:#000080;"> joinPoint.proceed()</span> and remove the line below. Eventually remove the AspectJ compiler or the JVM agent to avoid weaving in the advice.</p>
<p>The test class that asserts that the <span style="color:#000080;">String</span>&#8216;s <span style="color:#000080;">toLowerCase()</span> method works as expected:</p>
<pre class="brush: java; light: true; title: ; notranslate">
public class StringTest {

	@Test
	public void testAroundAdvice() {
		String demoText = &quot;tHiS iS a TeSt&quot;;

		assertEquals(&quot;this is a test&quot;, demoText.toLowerCase());
	}
}
</pre>
<p>Without AspectJ weaving, the test finishes successfully, but with weaving the result is:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
org.junit.ComparisonFailure: expected:&lt;[this is a test]&gt; but was:&lt;[THIS IS A TEST]&gt;
</pre>
<p><a name="best-practice-from-enterprise-frameworks"></a></p>
<h2>Best practice from enterprise frameworks</h2>
<p>Features like transaction handling, security and concurrency support are good candidates to be done with aspects. Spring, Guice and EJB implementations all use aspects to provide such enterprise capabilities without cluttering the application&#8217;s source code with infrastructure logic.</p>
<p>You can see this <a href="http://blog.espenberntsen.net/2010/04/01/declaratively-add-enterprise-functionality/">post</a> for a good example. Best practice with Java 5 and later is to add an annotation on methods that will be intercepted.</p>
<p>Annotations that says this method should be executed asynchronously in a transaction:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Async
@Transactional
public void demoMethod() {
	// logic ..
}
</pre>
<p>These annotations are excellent pointcuts for enterprise frameworks.</p>
<p><a name="cases-where-aspects-should-be-avoided"></a></p>
<h2>Cases where aspects should be avoided</h2>
<p>To change the target method like the StringAspect above should be avoided. You can replace an instance with a mock/stub object with AspectJ. In situations where the called instance is an object of a final class that doesn&#8217;t implement any interfaces, then an aspect is your only choice. It mocks away the dependency, but refactoring the code and use a mocking framework should be the preferred choice. It makes the code much more readable.</p>
<p>Especially without a tool like AJDT that visualizes the joinpoints in the source code. Here&#8217;s an <a href="http://blog.espenberntsen.net/2010/03/18/aspectj-examples-with-pointcuts-based-on-annotations/#screenshot">example</a> with the AJDT Eclipse plugin.</p>
<p>You should be really careful about adding or changing any data inside an advice. Such modifications makes the code almost impossible to read and the chance for bugs are higher.</p>
<p>Else, if many of the developers in a team isn&#8217;t familiar with aspects, you should also limit the use since it adds &#8220;magic&#8221; to the application that only a few developers on the team can understand.</p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/aspects/'>Aspects</a> Tagged: <a href='http://blog.espenberntsen.net/tag/aspectj/'>AspectJ</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=403&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/06/05/pitfalls-with-aspectj/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>
	</item>
		<item>
		<title>Declaratively add enterprise functionality</title>
		<link>http://blog.espenberntsen.net/2010/04/01/declaratively-add-enterprise-functionality/</link>
		<comments>http://blog.espenberntsen.net/2010/04/01/declaratively-add-enterprise-functionality/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 14:21:34 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Aspects]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[Decorator pattern]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[transaction handling]]></category>

		<guid isPermaLink="false">http://blog.espenberntsen.net/?p=207</guid>
		<description><![CDATA[This tutorial demonstrates several ways to implement enterprise functionality without adding boilerplate code to your business classes. It demonstrates using the Decorator pattern, an aspect and how to delegate the enterprise functionality to the application container. In this example to the Spring container.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=207&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The goal with this tutorial is to explain how you can add enterprise functionality declaratively and how an application container does it.</p>
<p>Enterprise functionality like transaction handling and security are often handled by an application container. I will demonstrate how to add transactional handling with the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator pattern</a>, an interceptor (<a href="http://eclipse.org/aspectj/">AspectJ</a>) and an interceptor configured with the <a href="http://www.springsource.org/">Spring</a> framework. All the alternatives works without adding boilerplate transaction logic to the business classes.</p>
<p>The decorator pattern can add behaviour to your business implementation without polluting the business implementation. The limitation with the decorator pattern compared to an interceptor is that the decorator must implement your business class&#8217; interface. An interceptor implemented with the <a href="http://eclipse.org/aspectj/">AspectJ</a> technology modifies the class either at compile or load-time. A general practice is to add business functionality with decorators, while you add enterprise functionality like transaction handling and security logic with interceptors.</p>
<h2>Example case for this tutorial</h2>
<p>This tutorial consist of four examples all using the interfaces on the image below with transaction logic around the transferAmount(..) method. The sequence diagram illustrates a successful transaction that will be commited.</p>
<p><a href="http://espenberntsen.files.wordpress.com/2010/03/transfer-amount-sequence-diagram.png"><img class="alignnone size-full wp-image-230" title="Transfer amount sequence diagram" src="http://espenberntsen.files.wordpress.com/2010/03/transfer-amount-sequence-diagram.png?w=700&#038;h=162" alt="Transfer amount sequence diagram" width="700" height="162" /></a></p>
<p>The other case demonstrated is when the credit method fails. Then the amount transferred from the debit account must be cancelled with a roll back. The roll back is triggered with a RuntimeException. This is the default way with EJB as well as the lightweight containers like Spring and Google Juice.</p>
<p>All the examples except the last one uses stub implementations for the repository and the transaction logic. The last example with Spring uses an embedded database and a JDBC transaction manager.</p>
<h2>Transaction handling with the decorator pattern</h2>
<p>This decorator example consist of the interfaces on the sequence diagram above as well as implementations of them and a transaction decorator that also implements the AccountService.</p>
<p>The business interface:</p>
<pre class="brush: java; light: true; title: ; notranslate">
public interface AccountService {

	public boolean transferAmount(final Amount amount, final Account debetAccount,
             final Account creditAccount);
}
</pre>
<p>The transferAmount() method in the business implementation:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Transactional
public boolean transferAmount(final Amount amount,
		final Account debetAccount, final Account creditAccount) {
	final boolean transferred;

	final Amount debetAccountBalance = accountRepository
			.getBalance(debetAccount);

	logger.debug(&quot;Balance on debet account before transfer: {}&quot;, debetAccountBalance.getAmount());

	if (debetAccountBalance.isLargerThanOrEqualTo(amount)) {
		debetAmount(amount, debetAccount);
		creditAmount(amount, creditAccount);

		transferred = true;
		logger.debug(&quot;{} amount was transferred from {} to {}&quot;,
				new Object[] { amount, debetAccount, creditAccount });
	} else {
		transferred = false;
		logger.debug(&quot;The transfer amount: {} is higher than the balance available on the &quot; +
                     &quot;debet account&quot;, amount.getAmount());
	}

	return transferred;
}
</pre>
<p>The method doesn&#8217;t contain any transactional logic. Since this example doesn&#8217;t use any interceptors, the @Transactional annotation is ignored.</p>
<p>When I execute the method with sufficient balance on the debit account, the following line is printed to the log:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
INFO  [com.redpill.linpro.service.impl.AccountServiceImpl] -
</pre>
<p>With the transaction decorator the output is:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
DEBUG [com.redpill.linpro.service.impl.AccountTransactionDecorator] -
INFO  [com.redpill.linpro.service.impl.AccountServiceImpl] - &lt;Amount [amount=50] was transferred from Account [accountNumber=1] to Account [accountNumber=2]&gt;
DEBUG [com.redpill.linpro.service.impl.AccountTransactionDecorator] - &lt;Commit transaction&gt;
</pre>
<p>The transaction decorator stub implementation:</p>
<pre class="brush: java; light: true; title: ; notranslate">
package com.redpill.linpro.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redpill.linpro.integration.Account;
import com.redpill.linpro.integration.Amount;
import com.redpill.linpro.service.AccountService;

public class AccountTransactionDecorator implements AccountService {

	private final AccountService accountService;

	private final Logger logger = LoggerFactory.getLogger(AccountTransactionDecorator.class);

	private int commitCounter = 0;

	private int rollbackCounter = 0;

	public AccountTransactionDecorator(AccountService accountService) {
		this.accountService = accountService;
	}

	@Override
	public boolean transferAmount(Amount amount, Account debetAccount,
			Account creditAccount) {
		final boolean transferred;

		logger.debug(&quot;Begin transaction&quot;);

		try {
			transferred = accountService.transferAmount(amount, debetAccount, creditAccount);
			commitCounter++;
			logger.debug(&quot;Commit transaction&quot;);
		} catch (RuntimeException e) {
			rollbackCounter++;
			logger.debug(&quot;Rollback transaction&quot;);
			throw e;
		}
		return transferred;
	}

	public int getCommitCounter() {
		return commitCounter;
	}

	public int getRollbackCounter() {
		return rollbackCounter;
	}
}
</pre>
<p>The decorator must implement the business interface like the business implementation above. Then it must have a reference to the interface. This enables the decorator to call the next decorator/service recursively. The decorator doesn&#8217;t know if the reference to the interface is to the implementation or to another decorator. Only the factory method knows that. This enables loose coupling and the ability to add behaviour to your service with only a configuration change. The decorator adds behaviour before and after the service is executed. And if a RuntimeException is throwed back, it will be catched and a roll back will be simulated. With normal execution, the decorator will simulate a commit like you can see in the log message above.</p>
<p>An implementation that uses the decorator pattern, should also use the factory pattern. In this example the factory logic is in the constructor of the test class. The important part in this factory method is that the accountService instance points to the transaction decorator object. And that the transaction decorator is instantiated with a reference to the business implementation.</p>
<pre class="brush: java; light: true; title: ; notranslate">
private final AccountService accountService;

public AccountServiceWithTransactionDecoratorTest() {
	accountRepositoryStub = new AccountRepositoryStub();

	// Basic service
	AccountService basicAccountService = new AccountServiceImpl(accountRepositoryStub);

	// Decorator
	accountTransactionDecorator = new AccountTransactionDecorator(basicAccountService);

	// The decorated service
	accountService = accountTransactionDecorator;
}
</pre>
<p>If the accountService instance had pointed to the business implementation instead of the decorator, then no transaction logic would have been executed.</p>
<p>The last part of this decorator example is the JUnit test. As you can see from the highlighted code, the test doesn&#8217;t know about the implementation or any decorators. It just executes the transferAmount() method on the accountService instance. And this instance is declared to be of the interface type.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Test
public void testTransferAmount() {
	Amount amount = new Amount(50);
	Account debetAccount = new Account(&quot;1&quot;);
	Account creditAccount = new Account(&quot;2&quot;);

	boolean transferred = accountService.transferAmount(amount, debetAccount, creditAccount);

	assertTrue(transferred);
	assertEquals(1, accountTransactionDecorator.getCommitCounter());
}
</pre>
<p><a name="transaction-handling-with-aspect"></a></p>
<h2>Transaction handling with aspect</h2>
<p><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-spring-or-aspectj">Spring Aspects</a> supports Spring AOP (Dynamic Objects and CGLIB) and AspectJ. Both alternatives support the AspectJ syntax. AspectJ is more powerful while Spring AOP is easier to use together with the Spring container. In this interceptor example I will use AspectJ. This is because it also works without the Spring container. I&#8217;m using compile-time weaving for simplicity, since <a href="http://www.springsource.com/products/sts">STS</a> will do the weaving for me with the AJDT plugin and an AspectJ nature on the project.</p>
<p>An aspect doesn&#8217;t need to know anything about the class it will modify. All that&#8217;s necessary is to know the joinpoint where the extra functionality should be added. In this example the pointcut will be the @Transactional annotation which is showed here:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Transactional
public boolean transferAmount(final Amount amount,
		final Account debetAccount, final Account creditAccount) { .. }
</pre>
<p>To enable AspectJ functionality with Java annotations, the @Aspect annotation must be above the class name with the AspectJ logic. Further, you have to declare the pointcut in a new annotation like this:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;execution(@org.springframework.transaction.annotation.Transactional * *(..))&quot;)
public void transactionalMethod() {}
</pre>
<p>A pointcut doesn&#8217;t add anything without advices. The three advises below supports the transaction handling example:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Before(&quot;transactionalMethod()&quot;)
public void beforeTransactionalMethod(JoinPoint joinPoint) {
	transactionService.beginTransaction();
}

@AfterReturning(&quot;transactionalMethod()&quot;)
public void afterTransactionalMethod(JoinPoint joinPoint) {
	transactionService.commit();
}

@AfterThrowing(pointcut = &quot;transactionalMethod()&quot;)
public void afterThrowingFromTransactionalMethod(JoinPoint joinPoint) {
	transactionService.rollback();
}
</pre>
<p>All the advises delegates to an instance of TransactionService. The last advice doesn&#8217;t swallow the exception, but throws it further after the rollback functionality is executed. The link below shows the TransactionAspect:</p>
<pre class="brush: java; light: true; title: ; notranslate">
package com.redpill.linpro.transaction;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import com.redpill.linpro.transaction.impl.TransactionServiceNull;

@Aspect
public class TransactionAspect {

	private TransactionService transactionService = new TransactionServiceNull();

	@Pointcut(&quot;execution(@org.springframework.transaction.annotation.Transactional * *(..))&quot;)
	public void transactionalMethod() {}

	@Before(&quot;transactionalMethod()&quot;)
	public void beforeTransactionalMethod(JoinPoint joinPoint) {
		transactionService.beginTransaction();
	}

	@AfterReturning(&quot;transactionalMethod()&quot;)
	public void afterTransactionalMethod(JoinPoint joinPoint) {
		transactionService.commit();
	}

	@AfterThrowing(pointcut = &quot;transactionalMethod()&quot;, throwing = &quot;e&quot;)
	public void afterThrowingFromTransactionalMethod(JoinPoint joinPoint, RuntimeException e) {
		transactionService.rollback();
	}

	public void setTransactionService(final TransactionService transactionService) {
		this.transactionService = transactionService;
	}
}
</pre>
<p>If you have enabled AspectJ nature on the Eclipse project, then you should see an orange arrow to the left of the transferAmount(..) method name.</p>
<p><a href="http://espenberntsen.files.wordpress.com/2010/03/transfer-amount-ajdt-support.png"><img class="alignnone size-full wp-image-231" title="transfer-amount-ajdt-support" src="http://espenberntsen.files.wordpress.com/2010/03/transfer-amount-ajdt-support.png?w=700" alt="transfer-amount-ajdt-support"   /></a></p>
<p>In the factory method in the JUnit test, the difference between this method and the decorator test is that the accountService instance doesn&#8217;t know about the aspect and the aspect doesn&#8217;t know about the AccountService implementation. In this case, the transaction logic will be weaved in at compile-time with the AspectJ compiler.</p>
<pre class="brush: java; light: true; title: ; notranslate">
public AccountServiceWithTransactionAspectTest() {
	accountRepositoryStub = new AccountRepositoryStub();

	accountService = new AccountServiceImpl(accountRepositoryStub);

	transactionServiceStub = new TransactionServiceStub();
	TransactionAspect transactionAspect = Aspects.aspectOf(TransactionAspect.class);
	transactionAspect.setTransactionService(transactionServiceStub);
}
</pre>
<p>The test class consist of two test methods. The first test method asserts that the normal flow works and the output from the log can be seen here:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
DEBUG [com.redpill.linpro.transaction.impl.TransactionServiceStub] - &lt;Begin transaction&gt;
INFO  [com.redpill.linpro.service.impl.AccountServiceImpl] - &lt;Amount [amount=50] was transferred from Account [accountNumber=1] to Account [accountNumber=2]&gt;
DEBUG [com.redpill.linpro.transaction.impl.TransactionServiceStub] - &lt;Commit transaction&gt;
</pre>
<p>The other test try to transfer to an invalid account which should cause an exception. The after throwing advice should roll back the transaction which the log indicates:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
DEBUG [com.redpill.linpro.transaction.impl.TransactionServiceStub] - &lt;Begin transaction&gt;
DEBUG [com.redpill.linpro.transaction.impl.TransactionServiceStub] - &lt;Rollback transaction&gt;
</pre>
<p><a name="transaction-handling-with-spring"></a></p>
<h2>Transaction handling with Spring</h2>
<p>With Spring it&#8217;s possible to add declarative transaction handling with Spring AOP and AspectJ. This example will use the default Spring AOP, since it&#8217;s the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-spring-or-aspectj">simplest and most used alternative</a>.</p>
<p>The default way to add transaction support with Spring and Java 5 or better is to annotate the transactional methods with @Transactional. This alternative requires the  element in the configuration. It&#8217;s higlighted below. This element requires a transaction manager that implements Spring&#8217;s PlatformTransactionManager interface. The example uses just a stub implementation. The component-scan elements below finds all the Spring beans annotated with a specialization of the @Component annotation.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;context:component-scan base-package=&quot;com.redpill.linpro.service&quot; /&gt;
&lt;context:component-scan base-package=&quot;com.redpill.linpro.integration.stub&quot; /&gt;

&lt;tx:annotation-driven /&gt;

&lt;bean id=&quot;transactionManager&quot; class=&quot;com.redpill.linpro.transaction.impl.PlatformTransactionManagerStub&quot; /&gt;
</pre>
<p>The most used implementations of the PlatformTransactionManager is DataSourceTransactionManager for JDBC, JpaTransactionManager, HibernateTransactionManager and JtaTransactionManager. The stub implementation used in this example just counts and logs every time a method in the interface are executed. Below are the overriden interface methods in the stub implementation:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Repository
public class PlatformTransactionManagerStub implements PlatformTransactionManager {

	@Override
	public void commit(TransactionStatus status) throws TransactionException {
		commitTransactionCounter++;
		logger.debug(&quot;Commit transaction&quot;);
	}

	@Override
	public TransactionStatus getTransaction(TransactionDefinition definition)
                        throws TransactionException {
		beginTransactionCounter++;
		logger.debug(&quot;Begin transaction&quot;);
		return new SimpleTransactionStatus();
	}

	@Override
	public void rollback(TransactionStatus status) throws TransactionException {
		rollbackTransactionCounter++;
		logger.debug(&quot;Rollback transaction&quot;);
	}
}
</pre>
<p>The test below demonstrates how to instantiate the Spring container with annotations and how to inject Spring beans into class variables. Further it executes the transferAmount(..) method on the accountService instance. This instance is of AccountServiceImpl type because the component-scan element in the configuration found the @Service annotation above that class and the class implements the AccountService interface. It doesn&#8217;t know about any aspects. And in this case with Spring AOP, the transaction logic will be added at runtime. No extra compiler or JVM agent is required.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(&quot;stub-config.xml&quot;)
public class AccountServiceWithTransactionManagerStubTest {

@Inject
private AccountService accountService;

@Inject
private PlatformTransactionManagerStub platformTransactionManagerStub;

@Test
public void testTransferAmount() {
Amount amount = new Amount(50);
Account debitAccount = new Account(&quot;1&quot;);
Account creditAccount = new Account(&quot;2&quot;);

boolean transferred = accountService.transferAmount(amount, debitAccount, creditAccount);

assertTrue(transferred);
assertEquals(1, platformTransactionManagerStub.getBeginTransactionCounter());
assertEquals(0, platformTransactionManagerStub.getRollbackTransactionCounter());
assertEquals(1, platformTransactionManagerStub.getCommitTransactionCounter());
}

@Test
public void testTransferAmountThatShouldRollback() {..}
}
</pre>
<p>The test prints the following to the log:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
DEBUG [com.redpill.linpro.transaction.impl.PlatformTransactionManagerStub] - &lt;Begin transaction&gt;
INFO  [com.redpill.linpro.service.impl.AccountServiceImpl] - &lt;Amount [amount=50] was transferred from Account [accountNumber=1] to Account [accountNumber=2]&gt;
DEBUG [com.redpill.linpro.transaction.impl.PlatformTransactionManagerStub] - &lt;Commit transaction&gt;
</pre>
<h2>Transaction handling with Spring and database</h2>
<p>In all the examples so far in this tutorial, I have used stub implementations for the transaction handling and only simulated a repository with another stub. In this last example, I will use plain JDBC against HSQL database and a DataSourceTransactionManager.</p>
<p>First, the respository stub is replaced with this:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Repository
public class AccountRepositoryImpl implements AccountRepository {

	@Inject
	private SimpleJdbcTemplate jdbcTemplate;

	private final String GET_BALANCE_SQL =
                &quot;select BALANCE from ACCOUNT where ACCOUNT_NUMBER = ?&quot;;

	private final String UPDATE_AMOUNT_SQL =
                &quot;update ACCOUNT set BALANCE = BALANCE + ? where ACCOUNT_NUMBER = ?&quot;;

	private final String VALIDATE_ACCOUNT_EXIST_SQL =
                &quot;select count(*) from ACCOUNT where ACCOUNT_NUMBER = ?&quot;;

	@Override
	public Amount getBalance(Account account) {
		int balance = jdbcTemplate.queryForInt(GET_BALANCE_SQL, account.getAccountNumber());
		return new Amount(balance);
	}

	@Override
	public void updateBalance(Amount balance, Account account) {
		jdbcTemplate.update(UPDATE_AMOUNT_SQL, balance.getAmount(), account.getAccountNumber());
	}

	public boolean isAccountExisting(final Account account) {
		int accountsWithAccountNumber = jdbcTemplate.queryForInt(VALIDATE_ACCOUNT_EXIST_SQL,
                         account.getAccountNumber());
		return (accountsWithAccountNumber == 1 ? true : false);
	}
}
</pre>
<p>Second, the configuration must contain a DataSourceTransactionManager, a data source and the AccountRepository implementation above.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;context:component-scan base-package=&quot;com.redpill.linpro.service&quot; /&gt;
&lt;context:component-scan base-package=&quot;com.redpill.linpro.integration.db&quot; /&gt;

&lt;tx:annotation-driven /&gt;

&lt;bean id=&quot;transactionManager&quot;
	class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot;&gt;
	&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot; /&gt;
&lt;/bean&gt;

jdbc.core.simple.SimpleJdbcTemplate&quot;&gt;
	&lt;constructor-arg ref=&quot;dataSource&quot; /&gt;
&lt;/bean&gt;

&lt;jdbc:embedded-database id=&quot;dataSource&quot; type=&quot;HSQL&quot;&gt;
 	&lt;jdbc:script location=&quot;classpath:com/redpill/linpro/integration/db/schema.sql&quot;/&gt;
 	&lt;jdbc:script location=&quot;classpath:com/redpill/linpro/integration/db/data.sql&quot;/&gt;
 &lt;/jdbc:embedded-database&gt;
</pre>
<p>The test below asserts that the balance on the debit account is the same after the roll back as it was before the transaction</p>
<pre class="brush: java; light: true; title: ; notranslate">
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({&quot;config.xml&quot;, &quot;../integration/db/database-config.xml&quot;})
public class AccountServiceWithSpringTest {

	@Inject
	private AccountService accountService;

	@Inject
	private AccountRepository accountRepository;

	@Test
	public void testTransfer() {..}

	@Test
	public void testTransferWithInvalidCreditAccount() {
		Amount amount = new Amount(100);
		Account debetAccount = new Account(&quot;789&quot;);
		Account creditAccount = new Account(&quot;INVALID&quot;);

		try {
			accountService.transferAmount(amount, debetAccount, creditAccount);
			fail(&quot;transferAmount() should have throwed exception.&quot;);
		} catch (IllegalArgumentException e) {
			Amount debetBalanceAfterTransfer = accountRepository.getBalance(debetAccount);
			assertEquals(new Amount(100), debetBalanceAfterTransfer);
		}
	}
}
</pre>
<h2>Summary</h2>
<p>The Decorator pattern and aspect technologies enables enterprise functionality without an application container and boilerplate code in your business logic.The simplest solution if you&#8217;re already are familiar with an application container is to delegate the enterprise functionality to the container like the last two examples in this tutorial.</p>
<p>The coded used in this article was developed in my work time at Redpill Linpro. It can be downloaded from: <a href="http://samplecode-espenberntsen.googlecode.com/svn/enterprise.functionality/trunk/">http://samplecode-espenberntsen.googlecode.com/svn/enterprise.functionality/trunk/</a></p>
<p><a title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." href="http://www.redpill-linpro.com" target="_blank"><br />
<img class="size-full wp-image-212 aligncenter" style="border:0 none;" title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." src="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png?w=700" alt="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region."   /></a></p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/aspects/'>Aspects</a> Tagged: <a href='http://blog.espenberntsen.net/tag/aspectj/'>AspectJ</a>, <a href='http://blog.espenberntsen.net/tag/decorator-pattern/'>Decorator pattern</a>, <a href='http://blog.espenberntsen.net/tag/spring/'>Spring</a>, <a href='http://blog.espenberntsen.net/tag/transaction-handling/'>transaction handling</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=207&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/04/01/declaratively-add-enterprise-functionality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/transfer-amount-sequence-diagram.png" medium="image">
			<media:title type="html">Transfer amount sequence diagram</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/transfer-amount-ajdt-support.png" medium="image">
			<media:title type="html">transfer-amount-ajdt-support</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png" medium="image">
			<media:title type="html">Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.</media:title>
		</media:content>
	</item>
		<item>
		<title>@AspectJ cheat sheet</title>
		<link>http://blog.espenberntsen.net/2010/03/20/aspectj-cheat-sheet/</link>
		<comments>http://blog.espenberntsen.net/2010/03/20/aspectj-cheat-sheet/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 17:28:08 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Aspects]]></category>
		<category><![CDATA[Advice]]></category>
		<category><![CDATA[Annotation]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[Pointcut]]></category>

		<guid isPermaLink="false">http://blog.espenberntsen.net/?p=242</guid>
		<description><![CDATA[This cheat sheet uses AspectJ&#8217;s @AspectJ style. It&#8217;s also possible to use the original AspectJ syntax like this example demonstrates, but I prefer to use standard Java classes with the AspectJ logic inside annotations. Pointcuts The definition of a pointcut from the AspectJ homepage: A pointcut is a program element that picks out join points [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=242&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>This cheat sheet uses AspectJ&#8217;s @AspectJ style. It&#8217;s also possible to use the original <a title="http://eclipse.org/aspectj/doc/released/progguide/language.html" rel="nofollow" href="http://eclipse.org/aspectj/doc/released/progguide/language.html">AspectJ syntax</a> like this <a href="http://www.ibm.com/developerworks/java/library/j-aopwork8/#code8">example</a> demonstrates, but I prefer to use standard Java classes with the AspectJ logic inside annotations.</p>
<h2>Pointcuts</h2>
<p>The definition of a pointcut from the AspectJ <a href="http://www.eclipse.org/aspectj/doc/next/progguide/semantics-pointcuts.html">homepage</a>:</p>
<blockquote><p>A pointcut is a program element that picks out join points and       exposes data from the execution context of those join points.       Pointcuts are used primarily by advice.  They can be composed with       boolean operators to build up other pointcuts.</p></blockquote>
<p>A pointcut example:</p>
<p><a href="http://espenberntsen.files.wordpress.com/2010/03/aspectj-pointcut-explanation.png"><img class="alignnone size-full wp-image-243" title="aspectj-pointcut-explanation" src="http://espenberntsen.files.wordpress.com/2010/03/aspectj-pointcut-explanation.png?w=700&#038;h=231" alt="" width="700" height="231" /></a></p>
<h2>Pointcut designators</h2>
<p>A method pointcut:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;[method designator](* aspects.trace.demo.*.*(..))&quot;)
public void traceMethodsInDemoPackage() {}
</pre>
<ul>
<li>call &#8211; The pointcut will find all methods that calls a method in the demo package.</li>
<li>execution &#8211; The pointcut will find all methods in the demo package.</li>
<li>withincode &#8211; All the statements inside the methods in the demo package.</li>
</ul>
<p>A type pointcut:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;[type designator](*..*Test)&quot;)
public void inTestClass() {}
</pre>
<ul>
<li>within &#8211; all statements inside the a class that ends with Test.</li>
</ul>
<p>A field pointcut:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;[field designator](private org.springframework.jdbc.core.JdbcTemplate &quot; +
       &quot;integration.db.*.jdbcTemplate)&quot;)
public void jdbcTemplateGetField() {}
</pre>
<ul>
<li>get &#8211; all reads to jdbcTemplate fields of type JdbcTemplate in the integration.db package. Includes all methods on this field if it&#8217;s an object.</li>
<li>set &#8211; when you set the jdbcTemplate field of type JdbcTemplate in the integration.db package to a new value.</li>
</ul>
<h2>Signature pointcuts</h2>
<p>This chapter explains more advanced signature pointcuts than illustrated on the image above.</p>
<p>Support for sub packages is provided with &#8220;..&#8221;:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;within(*..*Test)&quot;)
public void inTestClass() {}
</pre>
<p>To find the joinpoints inside a type that ends with Test inside the ..demo package:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;within(com.redpill.linpro.demo..*Test)&quot;)
public void inDemoProjectTestClass() {}
</pre>
<p>All statements inside all classes except test classes in the ..demo package with the &#8220;!&#8221; before the designator:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;!within(com.redpill.linpro.demo..*Test)&quot;)
public void notInDemoProjectTestClass() {}
</pre>
<p>All methods in the Service class or a subtype of it:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;execution(void *..service.Service+.*(..))&quot;)
public void servicePointcut() {}
</pre>
<p>All getCoffeeType methods in a class that begins with CoffeeTypeRepository:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;execution(CoffeeType integration.db.CoffeeTypeRepository*.getCoffeeType(CoffeeTypeName))&quot; +
    &quot; &amp;&amp; args(coffeeTypeName)&quot;)
public void getCoffeeTypePointcut(CoffeeTypeName coffeeTypeName) {}
</pre>
<p>Note that the pointcut also contains args(coffeeTypeName) and that the Java method has a method with a CoffeeTypeName as input parameter. An advice that advices this pointcut must also have this input parameter.</p>
<p>This field pointcut finds all the places in the integration package where a field named jdbcTemplate gets a new value of type JdbcOperations or a subtype of it like JdbTemplate.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;set(private org.springframework.jdbc.core.JdbcOperations+ &quot; +
    &quot;integration..*.jdbcTemplate)&quot;)
public void jdbcTemplateSetField() {}
</pre>
<h2>Annotation pointcuts</h2>
<p>A pointcut can declare an annotation before the signature pattern.</p>
<p>An example of an annotation used as a marker interface:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PerformanceLogable {}
</pre>
<p>All it does is to provide meta information to methods.</p>
<p>A pointcut that finds all methods marked with the @PerformanceLogable on the classpath:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;execution(@aspects.log.performance.PerformanceLogable * *(..))&quot;)
public void performanceLogableMethod() {}
</pre>
<p>The @Transactional annotation supports both method and type target. Which means it can be used with both method and type designators. The pointcut below is the same as the performanceLogableMethod pointcut, except it finds methods with Spring&#8217;s @Transactional annotation.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;execution(@org.springframework.transaction.annotation.Transactional * *(..))&quot;)
public void transactionalMethod() {}
</pre>
<p>A pointcut that finds all constructors marked with @Inject and have an integer as input parameter:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;execution(@javax.inject.Inject *.new(Integer)) &amp;&amp; args(integer)&quot;)
public void constructorAnnotatedWithInjectAndIndemoPackage(Integer integer) {}
</pre>
<p>The @Service annotation has target set to type and can therefore only annotate types. The pointcut below will find all statements in all types marked with @Service.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;within(@org.springframework.stereotype.Service *)&quot;)
public void serviceBean() {}
</pre>
<p>The joinpoint will be all statements inside a type marked with the @Component annotation or a specialization of it:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;within(@(@org.springframework.stereotype.Component *) *)&quot;)
public void beanAnnotatedWithComponentOrASpecializationOfIt() {}
</pre>
<p>Finds all statements that&#8217;s not inside a method marked with @Test:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;!withincode(@org.junit.Test * *(..))&quot;)
public void notInTestMethod() {}
</pre>
<p>Finds all methods with one or more parameters marked with the @MyParamAnnotation:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;execution(public * *(.., @aspects.MyParamAnnotation (*), ..))&quot;)
public void methodWithAnnotationOnAtLeastOneParameter() {}
</pre>
<p>For a full example with explanations, see this  <a href="http://stackoverflow.com/questions/2766844/pointcut-matching-methods-with-annotated-parameters/2766981#2766981">post</a>.</p>
<p>A pointcut with a runtime condition and a required public static method:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;execution(* *.actionPerformed(java.awt.event.ActionEvent)) &quot; +
		&quot;&amp;&amp; args(actionEvent) &amp;&amp; if()&quot;)
public static boolean button1Pointcut(ActionEvent actionEvent) {
	return (actionEvent.getSource() == j1);
}
</pre>
<p>More information can be found in this <a href="http://http://stackoverflow.com/questions/2939879/how-to-capture-button-click-if-more-than-one-button-in-aspectj/2940141#2940141">post</a></p>
<h2>Combining pointcuts</h2>
<p>Instead of having a large pointcut, it&#8217;s a much better approach to combine several pointcuts into one.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Pointcut(&quot;traceMethodsInDemoPackage() &amp;&amp; notInTestClass() &amp;&amp; notSetMethodsInTraceDemoPackage()&quot;)
public void filteredTraceMethodsInDemoPackage() {}
</pre>
<h2>Advices</h2>
<p>The definition from the AspectJ <a href="http://eclipse.org/aspectj/doc/released/progguide/language-anatomy.html#advice">homepage</a>:</p>
<blockquote><p>A piece of advice brings together a pointcut and a body of code to         define aspect implementation that runs at join points picked out by         the pointcut.</p></blockquote>
<p>An advice can be executed before, after, after returning, after throwing or around the joinpoint.</p>
<p>The before advice below is executed before the target method specified in filteredTraceMethodsInDemoPackage pointcut:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Before(&quot;filteredTraceMethodsInDemoPackage()&quot;)
public void beforeTraceMethods(JoinPoint joinPoint) {
	// trace logic ..
}
</pre>
<p>This after advice is executed after the target method.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@After(&quot;filteredTraceMethodsInDemoPackage()&quot;)
public void afterTraceMethods(JoinPoint joinPoint) {
	// trace logic ..
}
</pre>
<p>The afterThrowing advice will be executed if the method that matches the pointcut throws an exception. You can also declare the Exception and handle it like this:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@AfterThrowing(value=&quot;serviceMethodAfterExpcetionFromIntegrationLayerPointcut()&quot;, throwing=&quot;e&quot;)
public void serviceMethodAfterExceptionFromIntegrationLayer(JoinPoint joinPoint,
                RuntimeException e) {
	StringBuilder arguments = generateArgumentsString(joinPoint.getArgs());

	logger.error(&quot;Error in service &quot; + joinPoint.getSignature() + &quot; with the arguments: &quot; +
			arguments, e);
}
</pre>
<p>The AfterReturning advice will only be executed if the adviced method returns successfully.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@AfterReturning(&quot;transactionalMethod()&quot;)
public void afterTransactionalMethod(JoinPoint joinPoint) {
	transactionService.commit();
}
</pre>
<p>The around advice is quite powerful, but also consumes more resources and should only be used if you can&#8217;t make it work with other advices. The example below simulates some logic before and after the adviced method. The ProceedingJoinPoint extends the JoinPoint class and is required to call the adviced method with the proceed() method.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Around(&quot;performanceLogablePointcut()&quot;)
public void aroundPerformanceLogableMethod(ProceedingJoinPoint point) {

    // Pre processing work..

    point.proceed();

    // Post processing work..
}
</pre>
<p>Note: You don&#8217;t need an around advice to monitor the execution time for a method. It&#8217;s just the simplest option and therefore used in this example.</p>
<p>The advice below combines two pointcuts and the last one has an integer object as input parameter. This requires the Java method to also have an integer parameter. It enables the advice logic to access the input parameter directly and in a type safe manner. A less elegant alternative is to access the parameter with the joinPoint&#8217;s getArgs() method.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@AfterReturning(&quot;beanAnnotatedWithComponentOrASpecializationOfIt() &amp;&amp;  &quot; +
	&quot;constructorAnnotatedWithInjectAndIndemoPackage(integer)&quot;)
public void afterReturningFromConstructorInSpringBeanWithIntegerParameter(
		JoinPoint joinPoint, Integer integer) {

	// Advice logic..
}
</pre>
<h2>Summary</h2>
<p>This cheat sheet consist of many simple pointcuts. Often you have to combine them to add value to your application. This <a href="http://blog.espenberntsen.net/2010/03/18/aspectj-examples-with-pointcuts-based-on-annotations/">example article</a> combines pointcuts with a class marked with @Service and a constructor and method marked with @Inject. It also filters away the test method with the @Test annotation.</p>
<p>The code used in this article was developed in my work time at Redpill Linpro. </p>
<p><a title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." href="http://www.redpill-linpro.com" target="_blank"><br />
<img class="size-full wp-image-212 aligncenter" style="border:0 none;" title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." src="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png?w=700" alt="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region."   /></a></p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/aspects/'>Aspects</a> Tagged: <a href='http://blog.espenberntsen.net/tag/advice/'>Advice</a>, <a href='http://blog.espenberntsen.net/tag/annotation/'>Annotation</a>, <a href='http://blog.espenberntsen.net/tag/aspectj/'>AspectJ</a>, <a href='http://blog.espenberntsen.net/tag/pointcut/'>Pointcut</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=242&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/03/20/aspectj-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/aspectj-pointcut-explanation.png" medium="image">
			<media:title type="html">aspectj-pointcut-explanation</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png" medium="image">
			<media:title type="html">Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.</media:title>
		</media:content>
	</item>
		<item>
		<title>@AspectJ examples with pointcuts based on annotations</title>
		<link>http://blog.espenberntsen.net/2010/03/18/aspectj-examples-with-pointcuts-based-on-annotations/</link>
		<comments>http://blog.espenberntsen.net/2010/03/18/aspectj-examples-with-pointcuts-based-on-annotations/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 21:28:32 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Aspects]]></category>
		<category><![CDATA[Advice]]></category>
		<category><![CDATA[Annotation]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[Pointcut]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blog.espenberntsen.net/?p=251</guid>
		<description><![CDATA[This example demonstrates how to trace methods, constructors and fields annotated with @Inject and that&#8217;s inside a class annotated with @Component or a specialization of it like @Service. The aspect has three advices that combines different pointcuts. All the pointcuts uses primary marker interfaces (annotations) to determine where to place the adviced code. The annotations [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=251&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>This example demonstrates how to trace methods, constructors and fields annotated with @Inject and that&#8217;s inside a class annotated with @Component or a specialization of it like @Service. The aspect has three advices that combines different pointcuts. All the pointcuts uses primary marker interfaces (annotations) to determine where to place the adviced code. The annotations used in the pointcuts have target set to either method or type.</p>
<p>The example consist of a Demo class, a TraceAspect, a Spring configuration file and a JUnit test. The test starts the Spring container and the container injects all fields, methods and constructors in the Demo and DemoTest classes annotated with @Inject. It&#8217;s this dependency injection that the aspect will monitor and trace. The last part is when the test method calls the toString() method on the demo object and the toString() method reads the value in the text field. This get operation on the field is also monitored and traced by the aspect.</p>
<h2>The Demo class</h2>
<p>The Demo class has a text field that&#8217;s impossible to advice when the field gets set, since the Spring container injects the value with reflection and it&#8217;s no places in the code that sets this field. But it&#8217;s possible to advice the toString() method that reads this field. The constructor and method annotated with @Inject are adviced after they have returned successfully.</p>
<pre class="brush: java; light: true; title: ; notranslate">
package demo;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.stereotype.Service;

@Service
public class Demo {

	@Inject
	private String text;

	private final Integer integerOne;

	private Integer integerTwo;

	@Inject
	@Named(&quot;integerOne&quot;)
	public Demo(final Integer integerOne) {
		this.integerOne = integerOne;
	}

	@Inject
	@Named(&quot;integerTwo&quot;)
	public void setintegerTwo(final Integer integerTwo) {
		this.integerTwo = integerTwo;
	}

	@Override
	public String toString() {
		return &quot;Demo [integerOne=&quot; + integerOne + &quot;, integerTwo=&quot; + integerTwo
				+ &quot;, text=&quot; + text + &quot;]&quot;;
	}
}
</pre>
<div><a name="screenshot"></a></div>
<p>A screenshot from <a href="http://www.springsource.com/products/sts">STS</a> with AspectJ nature enabled:</p>
<p><a href="http://espenberntsen.files.wordpress.com/2010/03/adviced-demo-class.png"><img class="alignnone size-full wp-image-269" title="adviced-demo-class" src="http://espenberntsen.files.wordpress.com/2010/03/adviced-demo-class.png?w=700" alt="adviced-demo-class"   /></a></p>
<p>The first two orange arrows shows the joinpoint for two afterReturn advices, while the last one show the joinpoint for an around advice.</p>
<h2>The TraceAspect class</h2>
<p>Briefly summarized, the aspect below traces all methods and constructors in the demo package annotated with @Inject and that&#8217;s inside a type annotated with @Component or a specialization of it. Further, it demonstrates how to declare a pointcut with or without @args(..). The last advice is an around advice that traces all String fields annotated with @Inject in the demo package. It also prints out the return value.</p>
<pre class="brush: java; light: true; title: ; notranslate">
package demo;

import javax.inject.Inject;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.Test;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

/**
 * An example aspect that shows how to write pointcuts for annotated fields, methods and
 * types and how to advice those aspects.
 *
 * &lt;p&gt;
 * &lt;ul&gt;
 * 	&lt;li&gt;annotation target set to method&lt;/li&gt;
 *
&lt;ul&gt;
	&lt;li&gt;{@link Inject @Inject}, {@link Test @Test}&lt;/li&gt;
&lt;/ul&gt;
 *  &lt;li&gt;annotation target set to type&lt;/li&gt;
 *
&lt;ul&gt;
	&lt;li&gt;{@link Component @Component} or a specialization of it&lt;/li&gt;
&lt;/ul&gt;
 *  	({@link Service @Service}, {@link Repository @Repository})
 * &lt;/ul&gt;
 *
 * @author Espen Berntsen
 * @see Demo
 */
@Aspect
public class TraceAspect {

	// Trace injected methods and constructors --&gt;
	@Pointcut(&quot;within(@(@org.springframework.stereotype.Component *) *)&quot;)
	public void beanAnnotatedWithComponentOrASpecializationOfIt() {}

	@Pointcut(&quot;execution(@javax.inject.Inject * demo.*.*(..))&quot;)
	public void methodAnnotatedWithInjectAndInDemoPackage() {}

	@Pointcut(&quot;execution(@javax.inject.Inject demo.*.new(Integer)) &amp;&amp; args(integer)&quot;)
	public void constructorAnnotatedWithInjectAndIndemoPackage(
			Integer integer) {}

	// With args(integer).
	@AfterReturning(&quot;beanAnnotatedWithComponentOrASpecializationOfIt() &amp;&amp;  &quot; +
			&quot;constructorAnnotatedWithInjectAndIndemoPackage(integer)&quot;)
	public void afterReturningFromConstructorInSpringBeanWithIntegerParameter(
			JoinPoint joinPoint, Integer integer) {
		System.out.println(&quot;Executed @Injected constructor: &quot;
				+ joinPoint.getSignature() + &quot; with the integer: &quot; + integer);

	}

	// Using joinPoint.getArgs() to show arguments.
	@AfterReturning(&quot;beanAnnotatedWithComponentOrASpecializationOfIt() &amp;&amp;  &quot; +
			&quot;methodAnnotatedWithInjectAndInDemoPackage()&quot;)
	public void afterReturningFromMethodInSpringBean(JoinPoint joinPoint) {
		System.out.print(&quot;Executed the @Injected method: &quot;
				+ joinPoint.getSignature() + &quot; with value(s): &quot;);

		for (Object object : joinPoint.getArgs()) {
			System.out.print(object);
		}
		System.out.println();
	}
	// Trace injected methods and constructors &lt;--

	// Trace get on String fields annotated with @Inject --&gt;
	@Pointcut(&quot;get(@javax.inject.Inject java.lang.String demo..*.*)&quot;)
	public void getStringFieldAnnotatedWithInjectInTheDemoPackage() {}

	@Pointcut(&quot;!withincode(@org.junit.Test * demo..*(..))&quot;)
	public void notInTestMethod() {}

	@Pointcut(&quot;getStringFieldAnnotatedWithInjectInTheDemoPackage() &amp;&amp; notInTestMethod()&quot;)
	public void getStringFieldAnnotatedWithInjectInTheDemoPackageAndNotInTestMethod() {}

	@Around(&quot;getStringFieldAnnotatedWithInjectInTheDemoPackageAndNotInTestMethod()&quot;)
	public String aroundGetStringFieldAnnotatedWithInjectInTheDemoPackageAndNotInTestMethod(
			ProceedingJoinPoint joinPoint) throws Throwable {

		String fieldValue = (String) joinPoint.proceed();
		System.out.println(&quot;Get on @Inject String field: &quot;
				+ joinPoint.getSignature() + &quot; with value: &quot; + fieldValue);
		return fieldValue;
	}
	// Trace get on String fields annotated with @Inject &lt;--
}
</pre>
<h2>The Spring configuration file</h2>
<p>The configuration file below contains a component-scan element that finds the Demo class because it&#8217;s annotated with @Service. The three other beans are injected into the demo bean&#8217;s field, constructor and method marked with @Inject. This is enabled with the component-scan or annotation-config element in the context namespace. Since it&#8217;s two integers, the method and constructor in the Demo class also have an @Named(..) annotation with a value equal to the bean id that&#8217;s injected.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd&quot;&gt;

	&lt;context:component-scan base-package=&quot;demo&quot; /&gt;

	&lt;bean id=&quot;a&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;test&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;integerOne&quot; class=&quot;java.lang.Integer&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;1&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;integerTwo&quot; class=&quot;java.lang.Integer&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;2&quot; /&gt;
	&lt;/bean&gt;
&lt;/beans&gt;
</pre>
<h2>The test class</h2>
<p>Finally, the test class that instantiates the Spring container executes the toString() method on the demo object. If you&#8217;re not familiar with Spring, you can replace the Spring configuration with a factory method in the test class instead as long as you&#8217;re setting the @Inject field, constructor and method.</p>
<pre class="brush: java; light: true; title: ; notranslate">
package demo;

import javax.inject.Inject;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Should have been a main method, but I use the
 * {@link Test} annotation to demonstrate withincode designator
 * {@link TraceAspect#beanAnnotatedWithComponentOrASpecializationOfIt()}
 *
 * @author Espen Berntsen
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(&amp;quot;config.xml&amp;quot;)
public class DemoTest {

	@Inject
	private Demo demo;

	@Test
	public void testToString() {
		System.out.println(&amp;quot;demo.toString(): &amp;quot; + demo.toString());
	}
}
</pre>
<p>The console output after executing the test class:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
Executed @Injected constructor: demo.Demo(Integer) with the integer: 1
Executed the @Injected method: void demo.Demo.setintegerTwo(Integer) with value(s): 2
Get on @Inject String field: String demo.Demo.text with value: test
demo.toString(): Demo [integerOne=1, integerTwo=2, text=test]
</pre>
<h2>Summary</h2>
<p>Annotations are very good pointcuts and are frequently used by application containers to add enterprise features. See also this <a href="http://blog.espenberntsen.net/2010/03/20/aspectj-cheat-sheet/">cheat sheet</a> for more information about how to write aspects with @AspectJ style.</p>
<p>The code used in this article was developed in my work time at Redpill Linpro.</p>
<p><a title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." href="http://www.redpill-linpro.com" target="_blank"><br />
<img class="size-full wp-image-212 aligncenter" style="border:0 none;" title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." src="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png?w=700" alt="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region."   /></a></p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/aspects/'>Aspects</a> Tagged: <a href='http://blog.espenberntsen.net/tag/advice/'>Advice</a>, <a href='http://blog.espenberntsen.net/tag/annotation/'>Annotation</a>, <a href='http://blog.espenberntsen.net/tag/aspectj/'>AspectJ</a>, <a href='http://blog.espenberntsen.net/tag/pointcut/'>Pointcut</a>, <a href='http://blog.espenberntsen.net/tag/spring/'>Spring</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=251&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/03/18/aspectj-examples-with-pointcuts-based-on-annotations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/adviced-demo-class.png" medium="image">
			<media:title type="html">adviced-demo-class</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png" medium="image">
			<media:title type="html">Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.</media:title>
		</media:content>
	</item>
		<item>
		<title>Monitoring a web application with tcServer developer edition</title>
		<link>http://blog.espenberntsen.net/2010/03/09/monitoring-a-web-application-with-tcserver-developer-edition/</link>
		<comments>http://blog.espenberntsen.net/2010/03/09/monitoring-a-web-application-with-tcserver-developer-edition/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 18:52:52 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Web Container]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[monitoring]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring insight]]></category>
		<category><![CDATA[tcServer]]></category>
		<category><![CDATA[Tomcat]]></category>

		<guid isPermaLink="false">http://blog.espenberntsen.net/?p=177</guid>
		<description><![CDATA[The tcServer developer edition is a Tomcat server with monitor support. The monitor support is provided through a tcServer template called Spring insight. The template is a web application. The monitor data from your application are gathered with AspectJ load-time weaving, stored in memory and presented on the Spring insight web site deployed on the [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=177&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The <a href="http://www.springsource.com/products/tcserver/devedition">tcServer developer edition</a> is a Tomcat server with monitor support. The monitor support is provided through a tcServer template called Spring insight. The template is a web application. The monitor data from your application are gathered with AspectJ load-time weaving, stored in memory and presented on the Spring insight web site deployed on the tcServer developer edition server. For local monitoring, you can find the insight application here: <a href="http://localhost:8080/insight" rel="nofollow">http://localhost:8080/insight</a>.</p>
<p>The screenshot shows all the recent traffic to the demo application&#8217;s servlets. A click on one of the bars gives you access to detailed information about the requests processed in that time period.</p>
<p><a rel="attachment wp-att-181" href="http://blog.espenberntsen.net/2010/03/09/monitoring-a-web-application-with-tcserver-developer-edition/recentactivityunstablefiveclients/"><img class="alignnone size-full wp-image-181" title="recentActivityUnstableFiveClients" src="http://espenberntsen.files.wordpress.com/2010/03/recentactivityunstablefiveclients.png?w=700" alt=""   /></a></p>
<p>The other view is application health. The screenshot below shows the application health for the &#8220;findBalance&#8221; web service.</p>
<p><a rel="attachment wp-att-183" href="http://blog.espenberntsen.net/2010/03/09/monitoring-a-web-application-with-tcserver-developer-edition/unstablenetworkwithfiveclients/"><img class="alignnone size-full wp-image-183" title="unstableNetworkWithFiveClients" src="http://espenberntsen.files.wordpress.com/2010/03/unstablenetworkwithfiveclients.png?w=700&#038;h=422" alt="" width="700" height="422" /></a></p>
<p>The service monitored above behave quite well and Spring insight claims its health is excellent.</p>
<p>If you click on one of the bars, you can drill down to each response and see details for that response:</p>
<p><a rel="attachment wp-att-179" href="http://blog.espenberntsen.net/2010/03/09/monitoring-a-web-application-with-tcserver-developer-edition/tracedetailwithexception/"><img class="alignnone size-full wp-image-179" title="traceDetailWithException" src="http://espenberntsen.files.wordpress.com/2010/03/tracedetailwithexception.png?w=700&#038;h=281" alt="" width="700" height="281" /></a></p>
<p>The example is from a web service and shows which parameters and return types my monitored beans are invoked with. Almost all the execution time for this request was used in the repository and you can see that the repository throwed an exception back. You can even read the exception message. If you&#8217;re using the WEB browser inside <a href="http://www.springsource.com/products/sts">Spring Tool Suite</a> (STS), you can also jump directly into the source code through the &#8220;Go to STS&#8221; link.</p>
<p>For a full introduction into monitoring with tcServer and Spring insight, you should see this <a href="http://s3.springsource.com/MRKT/spring-metrics/Spring_Insight_Preview-final2.mov">presentation</a>. It shows that you can see all the SQLs sent to the database and all the HTTP request and response messages handled by your application&#8217;s servlets.</p>
<div><a name="how-it-works"></a></div>
<h2>How it works</h2>
<p>The Spring insight application uses load-time weaving to monitor your application. Out of the box, Spring insight monitors the SQLs and HTTP request/response messages. To monitor your own classes, you have to add an @Component annotation above your class or preferably a specification like @Controller, @Service or @Repository. For Spring insight, these annotations are just marker annotations that tells AspectJ which classes to weave.</p>
<p>These annotations can also be used to define your Spring beans with component scanning. But it&#8217;s not related to the way Spring insight uses them since Spring insight uses them at load-time, which is before the Spring container is started (runtime).</p>
<p>A class that will be monitored because of the @Service annotation:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Service
public class AccountServiceImpl implements AccountService {
</pre>
<h2>Some examples</h2>
<p>The screenshot below shows a server that increases the load with ten clients every fifth second. In the beginning, the throughput increases with a low increase in response time. With more clients the throughput still improves, but the average response time increases much more.</p>
<p><a rel="attachment wp-att-196" href="http://blog.espenberntsen.net/2010/03/09/monitoring-a-web-application-with-tcserver-developer-edition/increasingwithtenclientseveryfifthsecond/"><img class="alignnone size-full wp-image-196" title="increasingWithTenClientsEveryFifthSecond" src="http://espenberntsen.files.wordpress.com/2010/03/increasingwithtenclientseveryfifthsecond.png?w=700&#038;h=345" alt="" width="700" height="345" /></a></p>
<p>The last image shows the same application with the number of clients doubled every fifth second. After a while it results in bad and unstable response time. The graph isn&#8217;t 100% correct since I run the clients on the same machine as the server. But the tests indicates quite clear that this application shouldn&#8217;t have unlimited number of server threads.</p>
<p><a rel="attachment wp-att-178" href="http://blog.espenberntsen.net/2010/03/09/monitoring-a-web-application-with-tcserver-developer-edition/increasingnumberofclients/"><img class="alignnone size-full wp-image-178" title="increasingNumberOfClients" src="http://espenberntsen.files.wordpress.com/2010/03/increasingnumberofclients.png?w=700" alt=""   /></a></p>
<p>You can see the response time is very unstable and Spring insight claims the application has bad health. With less server threads the application health improves.</p>
<h2>Summary</h2>
<p>The tcServer developer edition is an excellent choice for monitoring web applications that can run on Tomcat. With an annotation over all the classes you&#8217;re interested in monitoring, you get access to detailed information like execution time, parameters, exceptions and return types. And you&#8217;re only a click away from inspecting the code you find something interesting.</p>
<p>The code used in this article was developed in my work time at Redpill Linpro.</p>
<p><a title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." href="http://www.redpill-linpro.com" target="_blank"><br />
<img class="size-full wp-image-212 aligncenter" style="border:0 none;" title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." src="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png?w=700" alt="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region."   /></a></p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/web-container/'>Web Container</a> Tagged: <a href='http://blog.espenberntsen.net/tag/aspectj/'>AspectJ</a>, <a href='http://blog.espenberntsen.net/tag/monitoring/'>monitoring</a>, <a href='http://blog.espenberntsen.net/tag/spring/'>Spring</a>, <a href='http://blog.espenberntsen.net/tag/spring-insight/'>Spring insight</a>, <a href='http://blog.espenberntsen.net/tag/tcserver/'>tcServer</a>, <a href='http://blog.espenberntsen.net/tag/tomcat/'>Tomcat</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=177&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/03/09/monitoring-a-web-application-with-tcserver-developer-edition/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
<enclosure url="http://s3.springsource.com/MRKT/spring-metrics/Spring_Insight_Preview-final2.mov" length="155989307" type="video/quicktime" />
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/recentactivityunstablefiveclients.png" medium="image">
			<media:title type="html">recentActivityUnstableFiveClients</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/unstablenetworkwithfiveclients.png" medium="image">
			<media:title type="html">unstableNetworkWithFiveClients</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/tracedetailwithexception.png" medium="image">
			<media:title type="html">traceDetailWithException</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/increasingwithtenclientseveryfifthsecond.png" medium="image">
			<media:title type="html">increasingWithTenClientsEveryFifthSecond</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/increasingnumberofclients.png" medium="image">
			<media:title type="html">increasingNumberOfClients</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png" medium="image">
			<media:title type="html">Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.</media:title>
		</media:content>
	</item>
		<item>
		<title>Spring asynchronous support</title>
		<link>http://blog.espenberntsen.net/2010/03/08/spring-asynchronous-support/</link>
		<comments>http://blog.espenberntsen.net/2010/03/08/spring-asynchronous-support/#comments</comments>
		<pubDate>Sun, 07 Mar 2010 23:44:00 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[concurrent]]></category>
		<category><![CDATA[JEE 6]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blog.espenberntsen.net/?p=168</guid>
		<description><![CDATA[Spring 3 supports declarative concurrency support. At its simplest, you only need to specify in the Spring configuration file and add an @Async annotation above the method that you want to execute in an asynchronous process. See also this blog for step by step guide on how to execute a void method asynchronously. In many [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=168&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Spring 3 supports declarative concurrency support. At its simplest, you only need to specify  in the Spring configuration file and add an @Async annotation above the method that you want to execute in an asynchronous process.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Async
public void findBalanceAsync(final Account account) {
	accountRepository.findBalance(account);
}
</pre>
<p>See also this <a href="http://blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/">blog</a> for step by step guide on how to execute a void method asynchronously.</p>
<p>In many cases you also want the response message from a method executed asynchronously. To achieve this, Spring returns a java.util.concurrent.Future object. All that&#8217;s required from the implementation is to create and return a new AsyncResult object like this:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Async
public Future&lt;Balance&gt; findBalanceAsync(final Account account) {
	Balance balance = accountRepository.findBalance(account);
	return new AsyncResult&lt;Balance&gt;(balance);
}
</pre>
<p>Further, to retrieve the balance from this future object:</p>
<pre class="brush: java; light: true; title: ; notranslate">
Balance balance = future.get();
</pre>
<p>If the method that&#8217;s executed asynchronously throws an exception, it will be wrapped inside an ExecutionException and throwed when the Future&#8217;s get method gets called.</p>
<h2></h2>
<h2></h2>
<h2>Java EE 6 specification support</h2>
<p>If you prefer to use the Java EE 6 specification, then you can replace Spring&#8217;s Async and AsyncResult classes with the corresponding classes in the javax.ejb package in the commons annotations 1.1 specification.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@javax.ejb.Asynchronous
public Future&lt;Balance&gt; findBalanceAsync(final Account account) {
	Balance balance = accountRepository.findBalance(account);
	return new javax.ejb.AsyncResult&lt;Balance&gt;(balance);
}
</pre>
<h2>Configuring the task elements</h2>
<p>The Spring container understand the javax.ejb classes without any configuration changes. You only need to add the commons annotation API on the classpath.</p>
<p>Spring&#8217;s task support can be configured with values like the thread pool and wich implementation you prefer to use. The easiest approach is to use the task namespace&#8217;s executor element. This element instantiates a ThreadPoolTaskExecutor object. This class implements the java.util.concurrent.Executor interface. Another option is declare your own bean like the ExecutorService bean below and let the annotation-driven task element reference to it. See example below:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;bean id=&quot;executorService&quot; class=&quot;java.util.concurrent.Executors&quot;
	factory-method=&quot;newFixedThreadPool&quot;&gt;
	&lt;constructor-arg value=&quot;10&quot; /&gt;
&lt;/bean&gt;

&lt;task:executor id=&quot;threadPoolTaskExecutor&quot; pool-size=&quot;10&quot; /&gt;

&lt;task:annotation-driven executor=&quot;executorService&quot; /&gt;
</pre>
<h2>Work with the underlying ExecutorService implementation</h2>
<p>If you want to configure the ExecutorService object used by the Spring container after it&#8217;s initialized, then you can to do it programmatically as long as it&#8217;s a singleton bean. The first step is to retrieve the object with dependency injection like this:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Inject
ExecutorService executorService;
</pre>
<p>Then cast it to a TreadPoolExecutor object and adjust the settings like the pool size showed below:</p>
<pre class="brush: java; light: true; title: ; notranslate">
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService;
threadPoolExecutor.setMaximumPoolSize(poolSize);
threadPoolExecutor.setCorePoolSize(poolSize);
</pre>
<p>An another example it can be useful to handle the underlying implementation is if you want to abort all work in the ExecutorService or ThreadPoolTaskExecutor&#8217;s queue. Then you can execute the shutdown method like this:</p>
<pre class="brush: java; light: true; title: ; notranslate">
executorService.shutdown();
</pre>
<h2>Conclusion</h2>
<pre><a href="http://espenberntsen.files.wordpress.com/2010/03/duke_thread.gif"><img class="alignright size-thumbnail wp-image-386" style="border:0 none;" title="Duke Thread" src="http://espenberntsen.files.wordpress.com/2010/03/duke_thread.gif?w=84&#038;h=67" alt="" width="84" height="67" /></a></pre>
<p>Spring&#8217;s asynchronous support abstracts away most of the complex threading logic for you and still provides full access to the implementation behind. It also supports the new async API in Java EE 6 without any configuration changes.</p>
<p>The code used in this article was developed in my work time at Redpill Linpro.</p>
<p><a title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." href="http://www.redpill-linpro.com" target="_blank"><br />
<img class="size-full wp-image-212 aligncenter" style="border:0 none;" title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." src="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png?w=700" alt="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region."   /></a></p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/concurrency/'>Concurrency</a> Tagged: <a href='http://blog.espenberntsen.net/tag/async/'>async</a>, <a href='http://blog.espenberntsen.net/tag/concurrent/'>concurrent</a>, <a href='http://blog.espenberntsen.net/tag/jee-6/'>JEE 6</a>, <a href='http://blog.espenberntsen.net/tag/spring/'>Spring</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=168&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/03/08/spring-asynchronous-support/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/duke_thread.gif?w=150" medium="image">
			<media:title type="html">Duke Thread</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png" medium="image">
			<media:title type="html">Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.</media:title>
		</media:content>
	</item>
		<item>
		<title>Contract first web service with Spring WS</title>
		<link>http://blog.espenberntsen.net/2010/02/28/contract-first-web-service-with-spring-ws/</link>
		<comments>http://blog.espenberntsen.net/2010/02/28/contract-first-web-service-with-spring-ws/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 22:55:56 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Web Services]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[WSDL]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[XSD]]></category>

		<guid isPermaLink="false">http://espenberntsen.wordpress.com/?p=51</guid>
		<description><![CDATA[Introduction This tutorial demonstrates how to develop a web service with Spring WS. It&#8217;s a contract first web service that uses JAXB for the binding. The focus area is how to configure and use Spring WS. Details about how to create an XSD schema and JAXB classes are explained in this tutorial. I will also [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=51&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>This tutorial demonstrates how to develop a web service with Spring WS. It&#8217;s a contract first web service that uses JAXB for the binding. The focus area is how to configure and use Spring WS. Details about how to create an XSD schema and JAXB classes are explained in this <a href="http://blog.espenberntsen.net/2010/02/26/generate-jaxb-classes-from-an-xsd-schema-and-the-schema-from-an-xml-sample-document/" target="_blank">tutorial</a>.</p>
<p>I will also briefly show exception handling and validation support in relation to SOAP faults. But first some words about the contract first part.</p>
<h2>Generate an XSD schema and JAXB classes</h2>
<p>The sample XML request document that I will create an XSD schema from:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;accountBalanceRequest number=&quot;123456789&quot; name=&quot;Bob&quot; /&gt;
</pre>
<p>And the corresponding response document:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;accountBalanceResponse balance=&quot;100.50&quot; number=&quot;1234567890&quot; time=&quot;2009-05-30T09:30:10.5&quot; /&gt;
</pre>
<p>After some tweaking, the XSD schema looks like this:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;xs:schema xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;
	elementFormDefault=&quot;qualified&quot;
	targetNamespace=&quot;http://www.redpill-linpro.com/account-balance-service&quot;
	xmlns:a=&quot;http://www.redpill-linpro.com/account-balance-service&quot;&gt;

	&lt;xs:element name=&quot;accountBalanceRequest&quot;&gt;
		&lt;xs:complexType&gt;
			&lt;xs:attribute name=&quot;name&quot; use=&quot;required&quot; type=&quot;xs:string&quot; /&gt;
			&lt;xs:attribute name=&quot;number&quot; use=&quot;required&quot;&gt;
				&lt;xs:simpleType&gt;
					&lt;xs:restriction base=&quot;xs:string&quot;&gt;
						&lt;xs:pattern value=&quot;\d{10}&quot; /&gt;
					&lt;/xs:restriction&gt;
				&lt;/xs:simpleType&gt;
			&lt;/xs:attribute&gt;
		&lt;/xs:complexType&gt;
	&lt;/xs:element&gt;

	&lt;xs:element name=&quot;accountBalanceResponse&quot;&gt;
		&lt;xs:complexType&gt;
			&lt;xs:attribute name=&quot;balance&quot; use=&quot;required&quot; type=&quot;xs:decimal&quot; /&gt;
			dateTime&quot; /&gt;
		&lt;/xs:complexType&gt;
	&lt;/xs:element&gt;

&lt;/xs:schema&gt;
</pre>
<p>After I have generated the JAXB classes, the source folder containing generated classes looks like this:</p>
<pre><a href="http://espenberntsen.files.wordpress.com/2010/02/account-balance-service-jaxb-classes.png"><img class="alignnone size-medium wp-image-105" title="account-balance-service-jaxb-classes" src="http://espenberntsen.files.wordpress.com/2010/02/account-balance-service-jaxb-classes.png?w=300&#038;h=114" alt="" width="300" height="114" /></a></pre>
<p>Now I have created the data contract part of the WSDL and generated the data binding classes used to parse the Java object to XML. Then its time to understand how Spring WS works.</p>
<h2>The basics with Spring WS</h2>
<p>You don&#8217;t need to create a WSDL file with Spring WS. The WSDL file is generated from one or more XSD schemas and some few Spring configuration beans. Spring WS solves the rest with naming patterns.</p>
<p>The request element must end with Request and the response element must end with Response. The same applies to Fault elements. The WSDL operation will be the element names except the Request/Response part. Here is the generated WSDL operation:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;wsdl:operation name=&quot;accountBalance&quot;&gt;
 &lt;wsdl:input message=&quot;tns:accountBalanceRequest&quot; name=&quot;accountBalanceRequest&quot;&gt;
 &lt;/wsdl:input&gt;
 &lt;wsdl:output message=&quot;tns:accountBalanceResponse&quot; name=&quot;accountBalanceResponse&quot;&gt;
 &lt;/wsdl:output&gt;
&lt;/wsdl:operation&gt;
</pre>
<p>The server code isn&#8217;t aware of the WSDL. This is a different approach than for example CXF that generates an interface your implementation must implement. The server implementation only has dependencies to the JAXB generated request and response classes. Spring WS finds the implementing method of a WSDL operation with annotations on the service class.</p>
<h2>Server implementation</h2>
<p>This tutorial contains one stub implementation. The implementation returns the same response every time except if the account number starts with 9. Then it throws a runtime exception. More about exception handling later. The implementation class must have the Spring @Endpoint annotation above the class name and the @PayloadRoot annotation above the method that will handle the web service request. The @PayloadRoot annotation must know the XSD schema namespace and the name of the request element specified in the XSD schema. See the highlighted lines in this stub implementation:</p>
<pre class="brush: java; highlight: [1,4,5]; light: true; title: ; notranslate">
@Endpoint
public class AccountBalanceServiceStub {

	@PayloadRoot(namespace=&quot;http://www.redpill-linpro.com/account-balance-service&quot;,
			localPart=&quot;accountBalanceRequest&quot;)
	public AccountBalanceResponse findAccountBalance(
			AccountBalanceRequest accountBalanceRequest) {
		final AccountBalanceResponse response;

		if(isRequestValid(accountBalanceRequest)) {
			response = createDummyResponse();
		} else {
			throw new AccountNumberNotFoundException(
					&quot;Account number &quot; + accountBalanceRequest.getNumber() + &quot; not valid.&quot;);
		}

		return response;
	}

	private AccountBalanceResponse createDummyResponse() {
		AccountBalanceResponse response = new ObjectFactory()
			.createAccountBalanceResponse();

		response.setBalance(BigDecimal.valueOf(100.50));
		response.setTime(XMLGregorianCalendarImpl.createDateTime(2010, 4, 4, 12, 0, 0));
		return response;
	}

	private boolean isRequestValid(final AccountBalanceRequest accountBalanceRequest) {
		final boolean valid;

		if(accountBalanceRequest.getNumber().startsWith(&quot;9&quot;)) {
			valid = false;
		} else {
			valid = true;
		}

		return valid;
	}
}
</pre>
<p>The @Endpoint annotation is a specialization of the @Component annotation. All beans marked with @Component can be found with a componet scan element in the Spring configuration.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;context:component-scan base-package=&quot;com.redpill.linpro&quot; /&gt;
</pre>
<p>Another alternative for those that prefer to define their Spring beans explicitly:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;bean class=&quot;com.redpill.linpro.transport.account.ws.AccountBalanceServiceStub&quot; /&gt;
</pre>
<p>Spring WS needs an implementation of the EndpointMapping interface like this:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;bean class=&quot;org.springframework.ws.server.endpoint.mapping
	.PayloadRootAnnotationMethodEndpointMapping&quot; /&gt;
</pre>
<p>Since the stub implementation uses JAXB classes as input parameter and return type, the Spring configuration must also include these two beans for parsing XML:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;oxm:jaxb2-marshaller id=&quot;marshaller&quot;
	contextPath=&quot;com.redpill.linpro.ws.account.balance.service&quot; /&gt;

&lt;bean class=&quot;org.springframework.ws.server.endpoint.adapter
	.GenericMarshallingMethodEndpointAdapter&quot;&gt;

	&lt;constructor-arg ref=&quot;marshaller&quot; /&gt;
&lt;/bean&gt;
</pre>
<h2>Exception handling and SoapFault</h2>
<p>If something unexpected occurs on the server, it&#8217;s best practice with modern programming languages to throw exceptions. The SOAP specification supports SOAP faults and with a framework like Spring WS, these SOAP faults are converted into runtime exceptions of type SoapFaultException. An example of an SOAP fault captured with an TCP/IP monitor:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;SOAP-ENV:Body&gt;
	&lt;SOAP-ENV:Fault&gt;
		&lt;faultcode&gt;SOAP-ENV:Client&lt;/faultcode&gt;
		&lt;faultstring xml:lang=&quot;en&quot;&gt;Account number 9998765432 not valid.
	&lt;/SOAP-ENV:Fault&gt;
&lt;/SOAP-ENV:Body&gt;
</pre>
<p>The SOAP fault above is the result of throwing an AccountNotFoundException.</p>
<p>It&#8217;s several ways to configure Spring WS to convert an exception into a SOAP fault element, but I will only demonstrate how to do it with annotations. If you&#8217;re interested, see the <a href="http://static.springsource.org/spring-ws/sites/1.5/reference/html/server.html#server-endpoint-exception-resolver">reference documentation</a> for more information about the mapping alternative.</p>
<p>The @SoapFault annotation below helps the exception resolver to convert the exception to a SoapFault. Ant the FaultCode enum will be mapped to a fault-code element.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@SoapFault(faultCode = FaultCode.CLIENT)
public class AccountNumberNotFoundException extends RuntimeException {

	public AccountNumberNotFoundException(String message) {
		super(message);
	}
}
</pre>
<p>The exception resolver bean that converts all the exceptions marked with @SoapFault annotation:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;bean class=&quot;org.springframework.ws.soap.server.endpoint
	.SoapFaultAnnotationExceptionResolver&quot; /&gt;
</pre>
<p>A good web service client framework should convert a SOAP fault element to an exception and throw it to the client as a runtime exception. Below is a stacktrace printed from a caught SoapFaultClientException on the client-side:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
org.springframework.ws.soap.client.SoapFaultClientException: Account number 9998765432 not valid.
	at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37)
	at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:738)
	at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:564)
	at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:502)
	at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:351)
       ....
</pre>
<p>The SOAP specification supports five fault-codes and it&#8217;s easy to configure in the @SoapFault annotation.</p>
<pre><a rel="attachment wp-att-149" href="http://blog.espenberntsen.net/2010/02/28/contract-first-web-service-with-spring-ws/soap-faults/"><img class="alignnone size-medium wp-image-149" title="soap-faults" src="http://espenberntsen.files.wordpress.com/2010/02/soap-faults.png?w=300&#038;h=86" alt="" width="300" height="86" /></a></pre>
<p><div><a name="validating"></a></div>
<h2>Validating</h2>
<p>To enable validating, you have to add a PayloadValidatingInterceptor and reference to that interceptor from the interceptor list in the PayloadRootAnnotationMethodEndpointMapping.</p>
<pre class="brush: xml; highlight: [5]; light: true; title: ; notranslate">
&lt;bean
	class=&quot;org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping&quot;&gt;
	&lt;property name=&quot;interceptors&quot;&gt;
		&lt;list&gt;
			&lt;ref local=&quot;validatingInterceptor&quot; /&gt;
		&lt;/list&gt;
	&lt;/property&gt;
&lt;/bean&gt;

&lt;bean
	class=&quot;org.springframework.ws.soap.server.endpoint.SoapFaultAnnotationExceptionResolver&quot; /&gt;

&lt;bean id=&quot;validatingInterceptor&quot;
	class=&quot;org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor&quot;&gt;
	&lt;property name=&quot;schema&quot; value=&quot;/WEB-INF/schemas/account-balance-service.xsd&quot; /&gt;
	&lt;property name=&quot;validateRequest&quot; value=&quot;true&quot; /&gt;
	&lt;property name=&quot;validateResponse&quot; value=&quot;true&quot; /&gt;
&lt;/bean&gt;
</pre>
<p>If you&#8217;re not specifying the validate parameters above, only the request will be validated by default.</p>
<p>An example of a SOAP fault returned from the server with a request containing an account number with more than ten digits:</p>
<pre class="brush: xml; highlight: [8]; light: true; title: ; notranslate">
&lt;SOAP-ENV:Fault&gt;
	&lt;faultcode&gt;SOAP-ENV:Client&lt;/faultcode&gt;
	&lt;faultstring xml:lang=&quot;en&quot;&gt;Validation error&lt;/faultstring&gt;
	&lt;detail&gt;
		ValidationError xmlns:spring-ws=&quot;http://springframework.org/spring-ws&quot;&gt;
                        cvc-pattern-valid:
			Value '0987654321000000000000000000000000000' is not facet-valid with
			respect to pattern '\d{10}' for type
			'#AnonType_numberaccountBalanceRequest'.
			&lt;/spring-ws:ValidationError&gt;
		&lt;spring-ws:ValidationError xmlns:spring-ws=&quot;http://springframework.org/spring-ws&quot;&gt;
                        cvc-attribute.3:
			The value '0987654321000000000000000000000000000' of attribute 'number' on
			element 'ns2:accountBalanceRequest' is not valid with respect to
			its type, 'null'.&lt;/spring-ws:ValidationError&gt;
	&lt;/detail&gt;
&lt;/SOAP-ENV:Fault&gt;
</pre>
<p>As you can see, validating doesn&#8217;t require any code changes. It&#8217;s just to add an interceptor in the configuration. The same can be done in other areas like security.</p>
<h2>WSDL specific configuration</h2>
<p>Spring WS generates the WSDL document on runtime. Since the generating is based on naming patterns as described in the basic chapter earlier in this tutorial, all you need to specify is the schema, the name of the port type and the URI. You can specify a full URI, but since the dispatcher servlet already knows the application&#8217;s URI, it&#8217;s sufficient to only add the relative URI.</p>
<p>The WSDL definition Spring bean used in this tutorial:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;bean name=&quot;accountBalanceServiceDefinition&quot;
	class=&quot;org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition&quot;&gt;
	&lt;property name=&quot;schema&quot;&gt;
		&lt;bean class=&quot;org.springframework.xml.xsd.SimpleXsdSchema&quot;&gt;
			&lt;property name=&quot;xsd&quot;
				value=&quot;/WEB-INF/schemas/account-balance-service.xsd&quot; /&gt;
		&lt;/bean&gt;
	&lt;/property&gt;
	&lt;property name=&quot;portTypeName&quot; value=&quot;AccountBalanceService&quot; /&gt;
	&lt;property name=&quot;locationUri&quot; value=&quot;/account-balance-service&quot; /&gt;
&lt;/bean&gt;
</pre>
<p>The WSDL file this bean generates is available if you click on the link below:</p>
<pre class="brush: xml; collapse: true; light: false; title: ; toolbar: true; notranslate">
&lt;wsdl:definitions
	targetNamespace=&quot;http://www.redpill-linpro.com/account-balance-service&quot;&gt;

	&lt;wsdl:types&gt;
		&lt;xs:schema elementFormDefault=&quot;qualified&quot;
			targetNamespace=&quot;http://www.redpill-linpro.com/account-balance-service&quot;&gt;

			&lt;xs:element name=&quot;accountBalanceRequest&quot;&gt;
				&lt;xs:complexType&gt;
					&lt;xs:attribute name=&quot;name&quot; type=&quot;xs:string&quot; use=&quot;required&quot; /&gt;
					&lt;xs:attribute name=&quot;number&quot; use=&quot;required&quot;&gt;
						&lt;xs:simpleType&gt;
							&lt;xs:restriction base=&quot;xs:string&quot;&gt;
								&lt;xs:pattern value=&quot;\d{10}&quot; /&gt;
							&lt;/xs:restriction&gt;
						&lt;/xs:simpleType&gt;
					&lt;/xs:attribute&gt;
				&lt;/xs:complexType&gt;
			&lt;/xs:element&gt;

			&lt;xs:element name=&quot;accountBalanceResponse&quot;&gt;
				&lt;xs:complexType&gt;
					&lt;xs:attribute name=&quot;balance&quot; type=&quot;xs:decimal&quot; use=&quot;required&quot; /&gt;
					&lt;xs:attribute name=&quot;time&quot; type=&quot;xs:dateTime&quot; use=&quot;required&quot; /&gt;
				&lt;/xs:complexType&gt;
			&lt;/xs:element&gt;
		&lt;/xs:schema&gt;
	&lt;/wsdl:types&gt;

	&lt;wsdl:message name=&quot;accountBalanceRequest&quot;&gt;
		&lt;wsdl:part element=&quot;tns:accountBalanceRequest&quot; name=&quot;accountBalanceRequest&quot;&gt;
		&lt;/wsdl:part&gt;
	&lt;/wsdl:message&gt;

	&lt;wsdl:message name=&quot;accountBalanceResponse&quot;&gt;
		&lt;wsdl:part element=&quot;tns:accountBalanceResponse&quot; name=&quot;accountBalanceResponse&quot;&gt;
		&lt;/wsdl:part&gt;
	&lt;/wsdl:message&gt;

	portType name=&quot;AccountBalanceService&quot;&gt;
		&lt;wsdl:operation name=&quot;accountBalance&quot;&gt;
			&lt;wsdl:input message=&quot;tns:accountBalanceRequest&quot; name=&quot;accountBalanceRequest&quot;&gt;
			&lt;/wsdl:input&gt;
			&lt;wsdl:output message=&quot;tns:accountBalanceResponse&quot; name=&quot;accountBalanceResponse&quot;&gt;
			&lt;/wsdl:output&gt;
		&lt;/wsdl:operation&gt;
	&lt;/wsdl:portType&gt;

	AccountBalanceServiceSoap11&quot; type=&quot;tns:AccountBalanceService&quot;&gt;
		&lt;soap:binding style=&quot;document&quot;
			transport=&quot;http://schemas.xmlsoap.org/soap/http&quot; /&gt;

		&lt;wsdl:operation name=&quot;accountBalance&quot;&gt;
			soapAction=&quot;&quot; /&gt;
			&lt;wsdl:input name=&quot;accountBalanceRequest&quot;&gt;
				&lt;soap:body use=&quot;literal&quot; /&gt;
			&lt;/wsdl:input&gt;
			&lt;wsdl:output name=&quot;accountBalanceResponse&quot;&gt;
				&lt;soap:body use=&quot;literal&quot; /&gt;
			&lt;/wsdl:output&gt;
		&lt;/wsdl:operation&gt;
	&lt;/wsdl:binding&gt;

	&lt;wsdl:service name=&quot;AccountBalanceServiceService&quot;&gt;
		&lt;wsdl:port binding=&quot;tns:AccountBalanceServiceSoap11&quot; name=&quot;AccountBalanceServiceSoap11&quot;&gt;
			&lt;soap:address location=&quot;/account-balance-service&quot; /&gt;
		&lt;/wsdl:port&gt;
	&lt;/wsdl:service&gt;
&lt;/wsdl:definitions&gt;
</pre>
<p>The URL to the WSDL file can be found with this pattern: URL to the servlet + DefaultWsdl11Definition bean name + .wsdl. In my case it’s available here: <a href="http://localhost:8081/ws-demo/account-balance-service/accountBalanceServiceDefinition.wsdl">http://localhost:8081/ws-demo/account-balance-service/accountBalanceServiceDefinition.wsdl</a></p>
<h2>Servlet configuration</h2>
<p>The web.xml file must configure the Spring WS servlet to be of type MessageDispatcherServlet.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;servlet-name&gt;account-balance-service&lt;/servlet-name&gt;
	&lt;servlet-class&gt;org.springframework.ws.transport.http.MessageDispatcherServlet&lt;/servlet-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
		&lt;param-value&gt;/WEB-INF/spring/account-balance-service-ws-config.xml&lt;/param-value&gt;
	&lt;/init-param&gt;
&lt;/servlet&gt;
</pre>
<p>This servlet has its own Spring context with all the web service logic.</p>
<p>It&#8217;s a good practice to separate the servlet specific Spring configuration from the business and integration logic. Since this tutorial only contains a stub implementation, this application doesn&#8217;t have any business layer. With a normal application, the web.xml file should also contain these two elements:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;pre&gt;&lt;context-param&gt;
	&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
	classpath:config.xml
&lt;/context-param&gt;

&lt;listener&gt;
	&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
</pre>
<p>The config.xml file in this tutorial is just a dummy file with none Spring beans. If you have many separate Spring configuration files, then you can add them all in the param-value element separated with a comma.</p>
<p>Finally, you have to add mapping elements before the dispatcher servlet will work as expected.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;account-balance-service&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/account-balance-service/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;

&lt;mime-mapping&gt;
	&lt;extension&gt;wsdl&lt;/extension&gt;
	&lt;mime-type&gt;text/xml&lt;/mime-type&gt;
&lt;/mime-mapping&gt;

&lt;mime-mapping&gt;
	&lt;extension&gt;xsd&lt;/extension&gt;
	&lt;mime-type&gt;text/xml&lt;/mime-type&gt;
&lt;/mime-mapping&gt;
</pre>
<p>Click on the show source link below if you want to see the whole web.xml file.</p>
<pre class="brush: xml; collapse: true; light: false; title: ; toolbar: true; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
xmlns=&quot;http://java.sun.com/xml/ns/j2ee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;
	version=&quot;2.4&quot;&gt;

	&lt;context-param&gt;
		&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
		&lt;param-value&gt;classpath:config.xml&lt;/param-value&gt;
	&lt;/context-param&gt;

	&lt;listener&gt;
		&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
	&lt;/listener&gt;

	&lt;servlet&gt;
		&lt;servlet-name&gt;account-balance-service&lt;/servlet-name&gt;
		&lt;servlet-class&gt;org.springframework.ws.transport.http.MessageDispatcherServlet&lt;/servlet-class&gt;
		&lt;init-param&gt;
			&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
			&lt;param-value&gt;/WEB-INF/spring/account-balance-service-ws-config.xml&lt;/param-value&gt;
		&lt;/init-param&gt;
	&lt;/servlet&gt;

	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;account-balance-service&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/account-balance-service/*&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;

	&lt;mime-mapping&gt;
		&lt;extension&gt;wsdl&lt;/extension&gt;
		&lt;mime-type&gt;text/xml&lt;/mime-type&gt;
	&lt;/mime-mapping&gt;

	&lt;mime-mapping&gt;
		&lt;extension&gt;xsd&lt;/extension&gt;
		&lt;mime-type&gt;text/xml&lt;/mime-type&gt;
	&lt;/mime-mapping&gt;

&lt;/web-app&gt;
</pre>
<p>The important beans in the Spring servlet configuration file is already described earlier in this tutorial, but the link below shows all the beans.</p>
<pre class="brush: xml; collapse: true; light: false; title: ; toolbar: true; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:oxm=&quot;http://www.springframework.org/schema/oxm&quot;
	xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/oxm

http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd


http://www.springframework.org/schema/beans


http://www.springframework.org/schema/beans/spring-beans.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd&quot;&gt;

	&lt;oxm:jaxb2-marshaller id=&quot;marshaller&quot;
		contextPath=&quot;com.redpill.linpro.ws.account.balance.service&quot; /&gt;

	&lt;bean class=&quot;org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter&quot;&gt;
		&lt;constructor-arg ref=&quot;marshaller&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean
		class=&quot;org.springframework.ws.server.endpoint.mapping
		.PayloadRootAnnotationMethodEndpointMapping&quot;&gt;
		&lt;property name=&quot;interceptors&quot;&gt;
			&lt;list&gt;
				&lt;ref local=&quot;validatingInterceptor&quot; /&gt;
			&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

	&lt;bean class=&quot;org.springframework.ws.soap.server.endpoint.SoapFaultAnnotationExceptionResolver&quot; /&gt;

	&lt;bean id=&quot;validatingInterceptor&quot;
		class=&quot;org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor&quot;&gt;
		&lt;property name=&quot;schema&quot; value=&quot;/WEB-INF/schemas/account-balance-service.xsd&quot; /&gt;
		&lt;property name=&quot;validateRequest&quot; value=&quot;true&quot; /&gt;
		&lt;property name=&quot;validateResponse&quot; value=&quot;true&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;accountBalanceServiceDefinition&quot;
		class=&quot;org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition&quot;&gt;
		&lt;property name=&quot;schema&quot;&gt;
			&lt;bean class=&quot;org.springframework.xml.xsd.SimpleXsdSchema&quot;&gt;
				&lt;property name=&quot;xsd&quot;
					value=&quot;/WEB-INF/schemas/account-balance-service.xsd&quot; /&gt;
			&lt;/bean&gt;
		&lt;/property&gt;
		&lt;property name=&quot;portTypeName&quot; value=&quot;AccountBalanceService&quot; /&gt;
		&lt;property name=&quot;locationUri&quot; value=&quot;/account-balance-service&quot; /&gt;
	&lt;/bean&gt;

	&lt;context:component-scan base-package=&quot;com.redpill.linpro&quot; /&gt;

&lt;/beans&gt;
</pre>
<h2>Summary</h2>
<p>Spring WS is a lightweight web service alternative that takes care of the WSDL for you. It&#8217;s the easiest framework I have tried and should be a good framework in most situations. If you like to generate the service interfaces in addition to the transfer objects, you should consider CXF that&#8217;s another great alternative, else give this one a chance.</p>
<p>I have never been a huge fan of WSDL files and an alternative that handles all the plumbing for me is very nice. That enables faster development without loosing control over the data being exhanged with the client.</p>
<p>The code used in this article was developed in my work time at Redpill Linpro. It can be downloaded <a href="http://files.espenberntsen.net/blog/eclipse-projects/ws-demo.zip">here</a></p>
<p><a title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." href="http://www.redpill-linpro.com" target="_blank"><br />
<img class="size-full wp-image-212 aligncenter" style="border:0 none;" title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." src="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png?w=700" alt="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region."   /></a></p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/web-services/'>Web Services</a> Tagged: <a href='http://blog.espenberntsen.net/tag/spring/'>Spring</a>, <a href='http://blog.espenberntsen.net/tag/wsdl/'>WSDL</a>, <a href='http://blog.espenberntsen.net/tag/xml/'>XML</a>, <a href='http://blog.espenberntsen.net/tag/xsd/'>XSD</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=51&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/02/28/contract-first-web-service-with-spring-ws/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/02/account-balance-service-jaxb-classes.png?w=300" medium="image">
			<media:title type="html">account-balance-service-jaxb-classes</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/02/soap-faults.png?w=300" medium="image">
			<media:title type="html">soap-faults</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png" medium="image">
			<media:title type="html">Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.</media:title>
		</media:content>
	</item>
		<item>
		<title>Spring WS client</title>
		<link>http://blog.espenberntsen.net/2010/02/28/spring-ws-client/</link>
		<comments>http://blog.espenberntsen.net/2010/02/28/spring-ws-client/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 20:50:13 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Web Services]]></category>
		<category><![CDATA[exception handling]]></category>
		<category><![CDATA[JAXB]]></category>
		<category><![CDATA[SOAP fault]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[validating]]></category>
		<category><![CDATA[WebServiceTemplate]]></category>
		<category><![CDATA[XSD]]></category>

		<guid isPermaLink="false">http://blog.espenberntsen.net/?p=135</guid>
		<description><![CDATA[Introduction The Spring WS client is a lightweight alternative that doesn&#8217;t need a WSDL to work. You code against a template like Spring&#8217;s other templates for communicating against a database or JMS server. This blog article demonstrates how to use Spring WS as a client with JAXB for the data binding and how to add [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=135&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>The Spring WS client is a lightweight alternative that doesn&#8217;t need a WSDL to work. You code against a template like Spring&#8217;s other templates for communicating against a database or JMS server. This blog article demonstrates how to use Spring WS as a client with JAXB for the data binding and how to add pre and post processing behaviour with interceptors.</p>
<p>If you&#8217;re not familiar with generating JAXB classes, then take a look at this <a href="http://blog.espenberntsen.net/2010/02/26/generate-jaxb-classes-from-an-xsd-schema-and-the-schema-from-an-xml-sample-document/">tutorial</a>.</p>
<h2>How to use the WebServiceTemplate class</h2>
<p>Since Spring WS doesn&#8217;t use a service contract, you must know the request and response type. The test below demonstrates how to create and instantiate a request object of a JAXB generated class, call the marshallSendAndReceive method with it and how to cast the response object to an object of the JAXB generated response class. Finally, the test asserts that the service returned the expected result.</p>
<pre class="brush: java; light: true; title: ; notranslate">
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(&quot;test-config.xml&quot;)
public class AccountBalanceServiceTest {

	@Autowired
	private WebServiceTemplate webServiceTemplate;

	@Test
	public void testAccountBalanceService() {

		AccountBalanceRequest request = new ObjectFactory()
				.createAccountBalanceRequest();
		request.setName(&quot;Willy&quot;);
		request.setNumber(&quot;0987654321&quot;);
		AccountBalanceResponse response = (AccountBalanceResponse) webServiceTemplate
				.marshalSendAndReceive(request);

		assertEquals(BigDecimal.valueOf(100.5), response.getBalance());
	}
}
</pre>
<p>As you see, none web service specific information. All the web service details are hiding in the configuration.</p>
<h2>Spring configuration</h2>
<p>The test above requires a marshaller and WebServiceTemplate bean. The marshaller must specify the context path. That&#8217;s the package name for the generated JAXB classes.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;oxm:jaxb2-marshaller id=&quot;marshaller&quot;
	contextPath=&quot;com.redpill.linpro.ws.account.balance.service&quot; /&gt;
</pre>
<p>The template bean must specify the JAXB marshaller and the URI to the web service&#8217;s servlet URI.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;bean id=&quot;webServiceTemplate&quot; class=&quot;org.springframework.ws.client.core.WebServiceTemplate&quot;&gt;

	&lt;property name=&quot;marshaller&quot; ref=&quot;marshaller&quot; /&gt;
	&lt;property name=&quot;unmarshaller&quot; ref=&quot;marshaller&quot; /&gt;
	&lt;property name=&quot;defaultUri&quot;
		value=&quot;http://localhost:8081/ws-demo/account-balance-service&quot; /&gt;
&lt;/bean&gt;
</pre>
<h2>Retrieving standard SOAP faults</h2>
<p>When the SOAP response contains a SOAP fault, then Spring WS converts it into a SoapFaultClientException. This test calls a web service and expects an exception back:</p>
<pre class="brush: java; light: true; title: ; notranslate">
@Test(expected = SoapFaultClientException.class)
public void testAccountBalanceServiceWithTooLongAccountNumber() {

	AccountBalanceRequest request = new AccountBalanceRequest();
	request.setName(&quot;Willy&quot;);
	request.setNumber(&quot;0987654321000000000000000000000000000&quot;);

	webServiceTemplate.marshalSendAndReceive(request);
}
</pre>
<p>It&#8217;s caught by the JUnit test in the same way as you can catch every Java exceptions.</p>
<div><a name="validating"></a></div>
<h2>Validating</h2>
<p>The client part of Spring WS can validate the parsed XML before it sends the XML document. You only need to specify a validator interceptor in the configuration and reference to it from the WebServiceTemplate bean.</p>
<pre class="brush: xml; highlight: [8]; light: true; title: ; notranslate">
&lt;bean id=&quot;webServiceTemplate&quot; class=&quot;org.springframework.ws.client.core.WebServiceTemplate&quot;&gt;
	&lt;property name=&quot;marshaller&quot; ref=&quot;marshaller&quot; /&gt;
	&lt;property name=&quot;unmarshaller&quot; ref=&quot;marshaller&quot; /&gt;
	&lt;property name=&quot;defaultUri&quot;
		value=&quot;http://localhost:8081/ws-demo/account-balance-service&quot; /&gt;
	&lt;property name=&quot;interceptors&quot;&gt;
		&lt;list&gt;
			&lt;ref bean=&quot;payloadValidatingInterceptor&quot; /&gt;
		&lt;/list&gt;
	&lt;/property&gt;
&lt;/bean&gt;

&lt;bean id=&quot;payloadValidatingInterceptor&quot;
	class=&quot;org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor&quot;&gt;
	&lt;property name=&quot;schema&quot;
		value=&quot;file:WebContent/WEB-INF/schemas/account-balance-service.xsd&quot; /&gt;
	&lt;property name=&quot;validateRequest&quot; value=&quot;true&quot; /&gt;
	&lt;property name=&quot;validateResponse&quot; value=&quot;true&quot; /&gt;
&lt;/bean&gt;
</pre>
<p>This configuration should have worked. But it doesn&#8217;t work on my machine with Spring WS 1.5.9.A. A snippet from the odd log message:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
&lt;XML validation error on request: cvc-complex-type.3.2.2: Attribute 'name' is not allowed to appear in element 'ns2:accountBalanceRequest'.&gt;
&lt;XML validation error on request: cvc-complex-type.4: Attribute 'name' must appear on element 'ns2:accountBalanceRequest'.&gt;
</pre>
<p>You can click the link to see the whole log message.</p>
<pre class="brush: plain; collapse: true; light: false; title: ; toolbar: true; notranslate">
ERROR [org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor] - &lt;XML validation error on request: cvc-complex-type.3.2.2: Attribute 'name' is not allowed to appear in element 'ns2:accountBalanceRequest'.&gt;
ERROR [org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor] - &lt;XML validation error on request: cvc-complex-type.3.2.2: Attribute 'number' is not allowed to appear in element 'ns2:accountBalanceRequest'.&gt;
ERROR [org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor] - &lt;XML validation error on request: cvc-complex-type.4: Attribute 'name' must appear on element 'ns2:accountBalanceRequest'.&gt;
ERROR [org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor] - &lt;XML validation error on request: cvc-complex-type.4: Attribute 'number' must appear on element 'ns2:accountBalanceRequest'.&gt;
</pre>
<p>It&#8217;s an issue with the SAX validator and the DOM source element that represents the parsed XML. A quick fix to solve this problem is to transform the DOM source to a String. Create a StringReader with the String and create a StreamSource object with the StringReader. For all the details, see the source code:</p>
<pre class="brush: java; light: true; title: ; notranslate">
public class PayloadValidatingInterceptorWithSourceFix extends
		PayloadValidatingInterceptor {

	@Override
	protected Source getValidationRequestSource(WebServiceMessage request) {
		return transformSourceToStreamSourceWithStringReader(request.getPayloadSource());
	}

	@Override
	protected Source getValidationResponseSource(WebServiceMessage response) {
		return transformSourceToStreamSourceWithStringReader(response.getPayloadSource());
	}

	Source transformSourceToStreamSourceWithStringReader(Source notValidatableSource) {
		final Source source;
		try {
			Transformer transformer = TransformerFactory.newInstance().newTransformer();

			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
					&quot;yes&quot;);
			transformer.setOutputProperty(OutputKeys.INDENT, &quot;no&quot;);
			StringWriter writer = new StringWriter();
			transformer.transform(notValidatableSource, new StreamResult(
					writer));

			String transformed = writer.toString();
			StringReader reader = new StringReader(transformed);
			source = new StreamSource(reader);

		} catch (TransformerException transformerException) {
			throw new WebServiceTransformerException(
					&quot;Could not convert the source to a StreamSource with a StringReader&quot;,
					transformerException);
		}

		return source;
	}
}
</pre>
<p>And finally, replace the Spring interceptor bean with this bean:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;bean id=&quot;payloadValidatingInterceptorWithSourceFix&quot;
	class=&quot;com.redpill.linpro.transport.account.ws.PayloadValidatingInterceptorWithSourceFix&quot;&gt;
	&lt;property name=&quot;schema&quot;
		value=&quot;file:WebContent/WEB-INF/schemas/account-balance-service.xsd&quot; /&gt;
	&lt;property name=&quot;validateRequest&quot; value=&quot;true&quot; /&gt;
	&lt;property name=&quot;validateResponse&quot; value=&quot;true&quot; /&gt;
&lt;/bean&gt;
</pre>
<p>When the PayloadValidatingInterceptor work as expected, the interceptor will throw a WebServiceValidationException when you try to send a value that&#8217;s not valid according to the XSD schema.</p>
<h2>Summary</h2>
<p>It&#8217;s an elegant framework that&#8217;s easy to use.</p>
<p>The validation issues is a minus, but since it&#8217;s an open-source project, you always have the chance to replace or extend the classes you want.</p>
<p>The code used in this article was developed in my work time at Redpill Linpro. It can be downloaded <a href="http://files.espenberntsen.net/blog/eclipse-projects/ws-demo.zip">here</a></p>
<p><a title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." href="http://www.redpill-linpro.com" target="_blank"><br />
<img class="size-full wp-image-212 aligncenter" style="border:0 none;" title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." src="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png?w=700" alt="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region."   /></a></p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/web-services/'>Web Services</a> Tagged: <a href='http://blog.espenberntsen.net/tag/exception-handling/'>exception handling</a>, <a href='http://blog.espenberntsen.net/tag/jaxb/'>JAXB</a>, <a href='http://blog.espenberntsen.net/tag/soap-fault/'>SOAP fault</a>, <a href='http://blog.espenberntsen.net/tag/spring/'>Spring</a>, <a href='http://blog.espenberntsen.net/tag/validating/'>validating</a>, <a href='http://blog.espenberntsen.net/tag/webservicetemplate/'>WebServiceTemplate</a>, <a href='http://blog.espenberntsen.net/tag/xsd/'>XSD</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=135&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/02/28/spring-ws-client/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png" medium="image">
			<media:title type="html">Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.</media:title>
		</media:content>
	</item>
		<item>
		<title>Generate JAXB classes from an XSD schema and the schema from an XML sample document</title>
		<link>http://blog.espenberntsen.net/2010/02/26/generate-jaxb-classes-from-an-xsd-schema-and-the-schema-from-an-xml-sample-document/</link>
		<comments>http://blog.espenberntsen.net/2010/02/26/generate-jaxb-classes-from-an-xsd-schema-and-the-schema-from-an-xml-sample-document/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 11:36:33 +0000</pubDate>
		<dc:creator>Espen</dc:creator>
				<category><![CDATA[Web Services]]></category>
		<category><![CDATA[JAXB]]></category>
		<category><![CDATA[Trang]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[XSD]]></category>

		<guid isPermaLink="false">http://espenberntsen.wordpress.com/?p=69</guid>
		<description><![CDATA[It's much easier to write an XML document than an XSD schema. A good start is therefore to generate the first version of the schema from a sample XML document. Since XSD schemas works as the default data contracts in the XML world on cross of every programming language, you should make the contract as good as possible. To parse XML from Java, an excellent choice is to generate JAXB classes from an XSD schema and let the JAXB framework do the parsing for you.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=69&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>This tutorial demonstrates how to generate an XSD schema from a sample XML document and how to improve the schema before generating JABX classes from it.</p>
<p>The sample document used throughout this tutorial contains an order element as you can see here:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;order&gt;
	&lt;date&gt;2010-01-01&lt;/date&gt;
	&lt;id&gt;12345&lt;/id&gt;
	&lt;item name=&quot;Effective Java&quot; type=&quot;BOOK&quot; quantity=&quot;1&quot; /&gt;
	&lt;item name=&quot;Spring in Action&quot; type=&quot;BOOK&quot; quantity=&quot;1&quot; /&gt;
	&lt;item name=&quot;Gladiator&quot; type=&quot;DVD&quot; quantity=&quot;1&quot; /&gt;
&lt;/order&gt;
</pre>
<p>The motivation for creating a sample document first, is that it&#8217;s more simple and less verbose to write than an XSD schema. You can also generate an XSD schema from JAXB classes, but this tutorial generates JAXB classes from an XSD schema. This is because an XSD schema is language neutral and more feature rich for describing a data contract. For example the ability to add restrictions with regular expressions like this:</p>
<pre class="brush: xml; highlight: [4]; light: true; title: ; notranslate">
&lt;xs:attribute name=&quot;number&quot; use=&quot;required&quot;&gt;
	simpleType&gt;
		&lt;xs:restriction base=&quot;xs:string&quot;&gt;
			&lt;xs:pattern value=&quot;\d{10}&quot; /&gt;
		&lt;/xs:restriction&gt;
	&lt;/xs:simpleType&gt;
&lt;/xs:attribute&gt;
</pre>
<h2><strong>Generate XSD schema from XML sample document with Trang</strong></h2>
<p>The Trang project lives here: <a href="http://code.google.com/p/jing-trang/">http://code.google.com/p/jing-trang/</a></p>
<p>You can execute Trang&#8217;s Driver class with the XML sample document&#8217;s path and the path for the schema that will be generated to generate the schema. Another and probably more common way to generate is with Ant like this target:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;target name=&quot;generate-order-schema&quot; description=&quot;Generates schema from XML with Trang&quot;&gt;
	&lt;mkdir dir=&quot;${xsd-folder}&quot; /&gt;

	&lt;java jar=&quot;${lib-generate-folder}/trang.jar&quot; fork=&quot;true&quot;&gt;
		&lt;arg value=&quot;${xml-example-folder}/order.xml&quot; /&gt;
		&lt;arg value=&quot;${xsd-folder}/order-generated.xsd&quot; /&gt;
	&lt;/java&gt;

	&lt;echo message=&quot;${xsd-folder}/order-generated.xsd was generated&quot; /&gt;
&lt;/target&gt;
</pre>
<p>After you have executed this target, remember to update the folder with the generated file if you&#8217;re using Eclipse.</p>
<h2>Tweaking the generated XSD schema</h2>
<p>I only specified the input file and the path to the generated file when I executed Trang. This results in a very simple XSD without namespace for example. See Trang&#8217;s <a href="http://www.google.com/url?q=http%3A%2F%2Fwww.thaiopensource.com%2Frelaxng%2Ftrang-manual.html&amp;sa=D&amp;sntz=1&amp;usg=AFrqEzdOGvSeCQ4IeHBSLLSnQNa2ob1hoQ">manual</a> for more advanced use. The generated schema looks like this:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;
	elementFormDefault=&quot;qualified&quot;&gt;
	&lt;xs:element name=&quot;order&quot;&gt;
		&lt;xs:complexType&gt;
			&lt;xs:sequence&gt;
				&lt;xs:element ref=&quot;date&quot; /&gt;
				&lt;xs:element ref=&quot;id&quot; /&gt;
				&lt;xs:element maxOccurs=&quot;unbounded&quot; ref=&quot;item&quot; /&gt;
			&lt;/xs:sequence&gt;
		&lt;/xs:complexType&gt;
	&lt;/xs:element&gt;
	NMTOKEN&quot; /&gt;
	&lt;xs:element name=&quot;id&quot; type=&quot;xs:integer&quot; /&gt;
	&lt;xs:element name=&quot;item&quot;&gt;
		&lt;xs:complexType&gt;
			&lt;xs:attribute name=&quot;name&quot; use=&quot;required&quot; /&gt;
			&lt;xs:attribute name=&quot;quantity&quot; use=&quot;required&quot; type=&quot;xs:integer&quot; /&gt;
			NCName&quot; /&gt;
		&lt;/xs:complexType&gt;
	&lt;/xs:element&gt;
&lt;/xs:schema&gt;
</pre>
<p>The generated schema is an excellent start, but you often want to add namespace, restrictions and often to change the type of some of the fields Trang guessed on. After some manual modifications, my schema looks like this:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;
	elementFormDefault=&quot;qualified&quot; targetNamespace=&quot;http://www.redpill-linpro.com/order&quot;
	xmlns:o=&quot;http://www.redpill-linpro.com/order&quot;&gt;

	&lt;xs:element name=&quot;order&quot;&gt;
		&lt;xs:complexType&gt;
			&lt;xs:sequence&gt;
				&lt;xs:element name=&quot;date&quot; type=&quot;xs:date&quot; /&gt;
				&lt;xs:element name=&quot;id&quot; type=&quot;xs:int&quot; /&gt;
				&lt;xs:element name=&quot;item&quot; maxOccurs=&quot;unbounded&quot;&gt;
					&lt;xs:complexType&gt;
						&lt;xs:attribute name=&quot;name&quot; use=&quot;required&quot; type=&quot;xs:string&quot; /&gt;
						&lt;xs:attribute name=&quot;quantity&quot; use=&quot;required&quot; type=&quot;xs:int&quot; /&gt;
						itemType&quot; /&gt;
					&lt;/xs:complexType&gt;
				&lt;/xs:element&gt;
			&lt;/xs:sequence&gt;
		&lt;/xs:complexType&gt;
	&lt;/xs:element&gt;

	&lt;xs:simpleType name=&quot;itemType&quot;&gt;
		&lt;xs:restriction base=&quot;xs:string&quot;&gt;
			&lt;xs:enumeration value=&quot;BOOK&quot; /&gt;
			&lt;xs:enumeration value=&quot;DVD&quot; /&gt;
			&lt;xs:enumeration value=&quot;CD&quot; /&gt;
		&lt;/xs:restriction&gt;
	&lt;/xs:simpleType&gt;
&lt;/xs:schema&gt;
</pre>
<p>Another difference is that it&#8217;s only one xs:element in the tweaked version. This is because id or date doesn&#8217;t give any value alone, but only together as part of the order element.</p>
<p>A JAXB tips is to create an xs:element with a nested type element inside it. This enables JAXB to add an @XmlRoot annotation above the generated class. This annotation is necessary for JAXB to marshall your objects.</p>
<div>
<h2>Working with XSD schema inside a good IDE</h2>
<p>With an IDE like Eclipse, it&#8217;s quite easy to create an XML document from an XSD schema. The XML document below is created with Eclipse. The schema is relative to the document and is highlighted in the XML document. You should consider a URL instead of a relative path for other situations than simple testing.</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
xmlns:o=&quot;http://www.redpill-linpro.com/order&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://www.redpill-linpro.com/order order.xsd &quot;&gt;
	&lt;o:date&gt;2001-01-01&lt;/o:date&gt;
	&lt;o:id&gt;0&lt;/o:id&gt;
	&lt;o:item name=&quot;Effective Java&quot; quantity=&quot;3&quot; type=&quot;BOOK&quot; /&gt;
	&lt;o:item name=&quot;Spring in Action&quot; quantity=&quot;1&quot; type=&quot;BOOK&quot; /&gt;
&lt;/o:order&gt;
</pre>
<p>A good IDE that&#8217;s aware of the schema will also give you code completion and validation support. This screenshot shows code completion of enumeration values.</p>
<p><a href="http://espenberntsen.files.wordpress.com/2010/02/order-xml-ide-support.png"><img class="alignnone size-medium wp-image-41" title="order-xml-ide-support" src="http://espenberntsen.files.wordpress.com/2010/02/order-xml-ide-support.png?w=300&#038;h=122" alt="" width="300" height="122" /></a></p>
<h2>Testing the generated JAXB classes</h2>
<p>The test below is a simple test that instantiates a JAXB generated order object. Then the object is marshalled to an XML document. The test asserts that the XML document contains some of the data from the order object. After this, it unmarshall the XML document back to an Order object again. Finally, the two order objects are compared against each other.</p>
<pre class="brush: java; light: true; title: ; notranslate">
public class OrderJaxbTest {

	@Test
	public void testOrder() throws Exception {
		Order order = createJaxbOrder();

		String xmlDocument = marshallOrderToXml(order);
		assertTrue(xmlDocument.contains(&quot;type=\&quot;CD\&quot; quantity=\&quot;2\&quot; name=\&quot;Effective Java\&quot;&quot;));

		Order unmarshalledOrder = unmarshallToOrderFromXml(xmlDocument);
		assertEquals(order.getId(), unmarshalledOrder.getId());
	}

	private Order unmarshallToOrderFromXml(String xmlDocument)
			throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(Order.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		StringReader reader = new StringReader(xmlDocument);
		Order unmarshalledOrder = (Order) unmarshaller.unmarshal(reader);
		return unmarshalledOrder;
	}

	private Order createJaxbOrder() throws DatatypeConfigurationException {
		Order order = new ObjectFactory().createOrder();
		order.setDate(DatatypeFactory.newInstance()
				.newXMLGregorianCalendar(2010, 5, 5, 12, 0, 0, 0, 1));
		order.setId(1);

		Item item = new Item();
		item.setName(&quot;Effective Java&quot;);
		item.setQuantity(2);
		item.setType(ItemType.CD);
		order.getItem().add(item);

		return order;
	}

	public String marshallOrderToXml(Order order) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(Order.class);
		Marshaller marshaller =context.createMarshaller();
		StringWriter writer = new StringWriter();
		marshaller.marshal(order, writer);

		return writer.toString();
	}
}
</pre>
<p>For simplicity, I send an StringWriter to the JAXB marshaller and an StringReader to the JAXB unmarshaller. It&#8217;s just to replace the reader and writer if you want to work against the file system.</p>
<h2>Summary</h2>
<p>To generate a basic version of the schema and then incrementally improve that schema works really well. It exists several frameworks and tools that can generate the schema. I have only evaluated Trang, but it does the job well and it&#8217;s an open source project that&#8217;s very easy to use. Also, to generate the JAXB classes from an XSD schema ensures that you&#8217;re 100% language neutral. JAXB is just one of many frameworks that can parse XML. It&#8217;s the Java standard parsing framework and some of its benefits are that it provides type safety and abstracts away the XML parsing behind a Java API.</p>
<p>To generate JAXB classes from an XSD schema is also an excellent start for writing contract-first web services with frameworks like Spring WS and CXF. These frameworks can be configured to use JAXB for the parsing. I will write more about Spring WS in a later article.</p>
<p>The code used in this article was developed in my work time at Redpill Linpro. It can be downloaded from <a href="http://files.espenberntsen.net/blog/eclipse-projects/jaxb-demo.zip" target="_blank">here</a>.</p>
</div>
<p><a title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." href="http://www.redpill-linpro.com" target="_blank"><br />
<img class="size-full wp-image-212 aligncenter" style="border:0 none;" title="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region." src="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png?w=700" alt="Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region."   /></a></p>
<br />Filed under: <a href='http://blog.espenberntsen.net/category/web-services/'>Web Services</a> Tagged: <a href='http://blog.espenberntsen.net/tag/jaxb/'>JAXB</a>, <a href='http://blog.espenberntsen.net/tag/trang/'>Trang</a>, <a href='http://blog.espenberntsen.net/tag/xml/'>XML</a>, <a href='http://blog.espenberntsen.net/tag/xsd/'>XSD</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.espenberntsen.net&#038;blog=12198574&#038;post=69&#038;subd=espenberntsen&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.espenberntsen.net/2010/02/26/generate-jaxb-classes-from-an-xsd-schema-and-the-schema-from-an-xml-sample-document/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0ab8e53a09aa9b99a7f32d927c80b4bc?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Espen</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/02/order-xml-ide-support.png?w=300" medium="image">
			<media:title type="html">order-xml-ide-support</media:title>
		</media:content>

		<media:content url="http://espenberntsen.files.wordpress.com/2010/03/redpill-linpro-logo-gif-190x90.png" medium="image">
			<media:title type="html">Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.</media:title>
		</media:content>
	</item>
	</channel>
</rss>
