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

<channel>
	<title>blog.smart-java.nl</title>
	<atom:link href="http://blog.smart-java.nl/blog/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smart-java.nl/blog</link>
	<description>Ordina J-Technologies - Java Blog</description>
	<lastBuildDate>Wed, 05 May 2010 20:06:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Running JPA (Hibernate3) and JTA on IBM Websphere 6.1 &amp; 7</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/05/05/jpa-hibernate3-jta-was7/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/05/05/jpa-hibernate3-jta-was7/#comments</comments>
		<pubDate>Wed, 05 May 2010 07:34:07 +0000</pubDate>
		<dc:creator>Vincent Lussenburg</dc:creator>
				<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Object Relational Mapping]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1100</guid>
		<description><![CDATA[Background
At my current project, we&#8217;re currently working on the second release of a webapp that integrates with a couple of webservices. It features a N+1 architecture (pretty much like the J-Technologies reference architecture) integrated by Spring 2.5.x. In this release, we have to persist into a single-consumer Oracle database. Since we have a tight deadline [...]]]></description>
			<content:encoded><![CDATA[<h2>Background</h2>
<p>At my current project, we&#8217;re currently working on the second release of a webapp that integrates with a couple of webservices. It features a N+1 architecture (pretty much like the J-Technologies reference architecture) integrated by Spring 2.5.x. In this release, we have to persist into a single-consumer Oracle database. Since we have a tight deadline but do want to experiment with various ORM implementations in the future, we ended up deciding to use JPA1.0 with Hibernate3 as persistence provider.</p>
<h2>Purpose of this post</h2>
<p>The combination Websphere / Hibernate / JPA did provide some &#8211; shall we say.. <em>challenges</em>? :&#41; You have some different approach routes to wire these technologies together and having a lot of choices can be confusing. The purpose of this post therefore is not only to show <em>how</em> we integrated it all but also <em>why</em> we did it this way. That hopefully helps others who are starting up a project with these technologies.</p>
<p>And of course, some of the choices we made may be flawed. That&#8217;s the reason you can write comments below :&#41; </p>
<p>I created an example project with our setup, see the bottom of this post ([1]). Remember that nowadays you can download a development version of Websphere 7 at no charge at IBM.com. But you can also run this project in jetty ofcourse.</p>
<h2>Configuring JPA</h2>
<h3>Setting up the PersistenceContext</h3>
<p>We decided to use Spring to bootstrap the JPA context. This is not the pure JEE way, I&#8217;ll get back to that in a later section. Spring&#8217;s <a href="http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html">LocalContainerEntityManagerFactoryBean</a> does pretty much what the JEE container should do: bootstrap the JPA persistence context, but with the usual extra Spring flexibility.</p>
<h5>persistence-spring.xml</h5>
<pre class="brush:[xml]">
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
	version="1.0">
	<!-- Kept as light as possible in order to work with Spring in both J2SE and JEE. -->
<persistence-unit name="example-db">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<jta-data-source>java:comp/env/jdbc/testDb</jta-data-source>
	</persistence-unit>
</persistence>
</pre>
<h5>Spring application context</h5>
<pre class="brush:[xml]">&lt;util:properties id="jpaProviderProperties" location="classpath:jpaVendor.properties" /&gt;
&lt;bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt;
&lt;!--
Non-standard filename so Websphere doesn't try to create the EM (and
throw errors due to Hibernate not being on the AS classpath)
--&gt;
&lt;property name="persistenceXmlLocation" value="classpath:META-INF/persistence-spring.xml" /&gt;
&lt;property name="jpaProperties" ref="jpaProviderProperties" /&gt;

&lt;/bean&gt;
</pre>
<p>The location of the persistence-spring.xml is important as it is used to find the Entities you want to persist (more info, see <a href="http://javahowto.blogspot.com/2007/06/where-to-put-persistencexml-in-web-app.html">here</a>). Ignore the jpaVendor.properties for now, I&#8217;ll get to that in the section on integration tests.</p>
<h3>Transaction management</h3>
<h4>Choosing a transaction manager</h4>
<p>In the end, we chose the most future-proof option: a JTA Transaction manager (TM). But we started out with these options:</p>
<ol>
<li>A (in JPA-speak) RESOURCE_LOCAL transaction manager. Spring provides the <a href="http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/orm/jpa/JpaTransactionManager.html">JpaTransactionManager</a>. Cannot handle transactions for more than one XA resource (db, web service call, etc).</li>
<li>A container-provided JTA transaction manager. Websphere provides the <a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=/com.ibm.websphere.javadoc.doc/public_html/spi/com/ibm/wsspi/uow/UOWManager.html">UOWManager</a> and Spring providers a wrapper around it, offering full JTA support &#8211; transaction suspending, distributed transactions, the works. It can be created through the container-independent &lt;tx:jta-transaction-manager /&gt; in the spring context.</li>
<li>What is all this transaction manager dogma? Do we need it? What&#8217;s wrong with using plain old autocommit?</li>
</ol>
<p>First: do we need a TM at all? Recent experiences at a different project showed that without a TM the use of connection pools is less efficient resulting in sizeable performance penalties, although it&#8217;s not completely clear why. So configuring a transaction manager seems the sensible thing to do. Since JTA is the default choice when running JPA in a JEE container and we had no good reason to reject this option, we went ahead with the default approach. Also, I have the feeling we might have to support <a href="https://www.ibm.com/developerworks/webservices/library/ws-transjta/">WS-Transaction</a> somewhere in the future (yes, YAGNI ;&#41;).</p>
<h4>Transaction boundaries</h4>
<p>Next: how to configure the transaction boundaries. That&#8217;s pretty standard Spring-tx stuff (since we&#8217;re not using EJB3). We use Spring&#8217;s @Transactional annotations on the service layer (the transaction boundary in our application) and the rest is taken care of by Spring&#8217;s &lt;tx:annotation-driven /&gt;. Works like a charm.</p>
<h4>Hibernate configuration</h4>
<p>Hibernate did give some problems with this setup. Since Spring is managing transactions, the only thing Hibernate should do is join the transaction. In order to do this Hibernate needs to look up the transaction manager. Sadly, neither the IBM UOWManager nor the Spring wrapper implements the TransactionManager interface. In the end, this configuration in jpaVendor.properties did the trick:</p>
<blockquote><p>
hibernate.transaction.manager_lookup_class=org.hibernate.transaction.WebSphereExtendedJTATransactionLookup</p></blockquote>
<p>Bottom line: Hibernate is synchronizing to the transaction using a pre-WAS6.1 mechanism, and Spring is using the >=WAS6.1 way. Also, the Hibernate implementation has it&#8217;s problems: setRollbackOnly may be called in application code according to the spec, but this causes a nasty stacktrace in the log. But: it <em>does</em> work correctly. The whole story is explained in detail in <a href="https://forum.hibernate.org/viewtopic.php?f=1&amp;t=992310">this thread</a>.</p>
<p>On a sidenote: something confused me for a while: Hibernate3 configures itself based on the persistence.xml configuration. I noticed that it switched its transaction factory implementation automatically to &#8216;JoinableCMTTransactionFactory&#8217;. CMT is Container managed persistence, and we don&#8217;t use EJB2, since this seemed incorrect. After some time I read the javadoc <a href="http://docs.jboss.org/hibernate/stable/annotations/api/org/hibernate/transaction/CMTTransaction.html">here</a>, and it turns out that this is in fact correct behaviour:</p>
<blockquote><p>The term &#8216;CMT&#8217; is potentially misleading here; the pertinent point simply being that the transactions are being managed by something other than the Hibernate transaction mechanism.</p></blockquote>
<h4>Opening the entity manager on each request</h4>
<p>We also added a filter (<a href="http://static.springsource.org/spring/docs/3.0.0.RC1/javadoc-api/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.html">OpenEntityManagerInViewFilter</a>) in the web.xml that sets up a EntityManager that the request starts en destroys it when the request ends (comparable with the OpenSessionInViewFilter for Hibernate).</p>
<h3>Running integration tests / Jetty</h3>
<p>Our data layer is isn&#8217;t unittested, it&#8217;s integration tested (as explained by yet another Vincent <a href="http://blog.xebia.com/2009/07/11/jpa-implementation-patterns-testing/">here</a>). As a rule of thumb, we always try to keep the configuration as identical to the deployment configuration as possible. In this case, the JPA context is set up using the exact same application context file and persistence.xml. The only thing that&#8217;s different are the jpaVendor.properties (in tests, I want Hibernate to use the H2 dialect and to automatically create the DB schema). They are read from the classpath (see sping XML snipplet at the beginning of this post): so you can have separate jpaVendor.properties for your test (src/test/resources) and production (src/main/resources) environment [2].</p>
<p>The resources normally provided by the JEE container (through JNDI) need to be mocked in test mode. This is a nice way to accomplish that:</p>
<pre class="brush:[java]">
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-config-domain.xml" })
@TransactionConfiguration(defaultRollback = true)
public class UserDaoTest {
[...]
	@BeforeClass
	public static void beforeClass() throws Exception {

		// Suppress the 'close', since we use a single connection in unittest
		// anyways. The connection is terminated upon destruction in afterClass
		singleConnectionDataSource = new SingleConnectionDataSource(
				"jdbc:h2:mem:", true);
		singleConnectionDataSource.setDriverClassName("org.h2.Driver");
		final TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy(
				singleConnectionDataSource);

		contextBuilder = new SimpleNamingContextBuilder();
		contextBuilder.bind("java:comp/TransactionManager",
				new JotmFactoryBean().getObject());
		contextBuilder.bind("java:comp/env/jdbc/testDb",
				transactionAwareDataSourceProxy);
		contextBuilder.activate();
	}

	@AfterClass
	public static void afterClass() throws Exception {
		contextBuilder.deactivate();
		singleConnectionDataSource.destroy();
	}
[...]
}
</pre>
<p>So, a datasource is registered in JNDI that keeps one connection open at all times (which is pretty handy when using a single threaded H2 DB) and a JOTM (jottum!) TM is used instead of the Websphere TM. The nice thing is the Spring configuration is identical, the &lt;tx:jta-transaction-manager /&gt; finds the JOTM TM now instead. Hibernate does need some manual configuration:</p>
<blockquote><p>hibernate.transaction.manager_lookup_class=org.hibernate.transaction.JOTMTransactionManagerLookup</p></blockquote>
<p>Another bonus: if you want to run your app in a lite JEE container like Jetty for quick deployment, you can use pretty much the same config for that!</p>
<h2>Discussion &#8211; what about JPA by the JEE book?</h2>
<p>According to the EJB3 spec, the container should be in control of the PersistenceContext, roughly as follows:</p>
<ul>
<li>Container detects META-INF/persistence.xml on webapp startup.</li>
<li>Container boots the JPA context based on the provided configuration.</li>
<li>Container sets the PersistenceContext on objects requiring it.</li>
<li>Container exposes the PersistenceContext via JNDI (as defined in the web.xml).</li>
</ul>
<p>Now try this on Websphere 7 (and 6.1 with the EJB3 feature pack, for that matter). As expected (remember: don&#8217;t feed the trolls), Websphere fails if you want to use your own persistence provider (in our case: Hibernate3). According to <a title="IBM" href="http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/tejb_jpa3rdparty.html" target="_blank">IBM</a> this should be possible by setting the classloader to PARENT_LAST, but alas, that didn&#8217;t seem to work as documented. Messing with heavy weight containers like Websphere is tiresome: you have stop/start redeploy until you&#8217;ve gone cross-eyed. So, the pure JEE configuration for JPA in Websphere wasn&#8217;t convenient for us (which doesn&#8217;t say it&#8217;s impossible) and I personally don&#8217;t see that as a problem &#8211; because it&#8217;s just easier to do it the Spring way &#8211; which can be easily tested in an integration test, instead of deploy-time. </p>
<h2>Final words</h2>
<p>So, is this the best solution? THE way of configuring JPA/JTA/Hibernate/WAS? Of course not. The is no right answer here I think, it all depends on the environment you&#8217;re in. But by explaining why this seems to be a nice fit for our situation, I hope to help those we need to use these technologies but can&#8217;t seem to see the forest for the trees. </p>
<p>Thanks for reading!</p>
<h2>Links</h2>
<p>[1] <a href="http://lussenburg.net/svn/dev/sandbox/jpa-spring-hibernate-example/trunk/">example jpa-spring-hibernate-was project</a><br />
[2] You could also accomplish this by setting a hibernate.properties on your classpath as Hibernate picks this up automatically, but this a more explicit way (but who cares about explicitness anymore in these times of @Autowired magic? :-&#41;).<br />
Keywords: Websphere 6.1 7, JPA, EJB3 , JTA, Transaction management, Spring, Hibernate, Hibernate3</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/05/05/jpa-hibernate3-jta-was7/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Reflection slow? Class vs. Constructor newInstance</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/05/01/reflection-slow-class-vs-constructor-newinstance/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/05/01/reflection-slow-class-vs-constructor-newinstance/#comments</comments>
		<pubDate>Sat, 01 May 2010 18:53:46 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[hotspot]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1083</guid>
		<description><![CDATA[My last article triggered a lot of responses of people, which I, of course, try to answer.
One question, by Tofarr, was: 

You are not caching the contructor! class.newInstance() internally looks for the no arg constructor each time – I would be curious to see how doing a Constructor c = class.getConstructor() would affect the timing…

This [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/">My last article</a> triggered a lot of responses of people, which I, of course, try to answer.</p>
<p><a href="http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/#comment-594">One question, by Tofarr</a>, was: </p>
<blockquote><p>
You are not caching the contructor! class.newInstance() internally looks for the no arg constructor each time – I would be curious to see how doing a Constructor c = class.getConstructor() would affect the timing…
</p></blockquote>
<p>This is not for 100% true, since (at least in my Java version) <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29">Class.newInstance()</a> caches the no-arg constructor after it&#8217;s first lookup. But, the suggestion is worth trying.</p>
<p>So, let&#8217;s go!</p>
<h3>Caching and instantiating the Class</h3>
<p>In the <a href="http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/">original article</a>, this was the task with the cached Class object.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CLASS_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache;
        {
            try {
                classCache = (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Cannot initialize JavaBean", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                JavaBean bean = classCache.newInstance();
                classCache.getMethod("setValue", Integer.TYPE).invoke(bean, i);
                final int value = (Integer) classCache.getMethod("getValue").invoke(bean);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<h3>Caching and invoking the Constructor</h3>
<p>So I added a simple implementation which caches the <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html">Constructor</a> object, like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CONSTRUCTOR_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache = JavaBean.class;
        private final Constructor<JavaBean> constructorCache;
        {
            try {
                constructorCache = classCache.getDeclaredConstructor();
            } catch (Exception e) {
                throw new RuntimeException("Cannot initialize JavaBean class and constructor", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                JavaBean bean = constructorCache.newInstance();
                classCache.getMethod("setValue", Integer.TYPE).invoke(bean, i);
                final int value = (Integer) classCache.getMethod("getValue").invoke(bean);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>The code should speak for itself. We don't just cache the Class object, but also the Constructor object. Caching only the Constructor in not enough, since we still need the Class to reflectively lookup methods. This wouldn't be necessary if we cache the <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html">Method</a>s. But, for the sake of a fair comparison, both implementations don't cache the methods.</p>
<h3>Running the benchmark</h3>
<p>Let's run it, using the following command:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
java -jar -server \
    -XX:+TraceClassLoading -XX:+PrintCompilation -XX:+PrintGCDetails \
    -Xms512m -Xmx512m -XX:PermSize=256m -XX:MaxPermSize=256m \
    ReflectionSlow.jar
</script></pre>
<p>In the previous article, I didn't show you the run command, so let's catch up.</p>
<ul>
<li><strong>-jar</strong><br />
Nothing special, I just packaged the benchmark in a JAR to easily transfer it across machines</li>
<li><strong>-server</strong><br />
This option is used to enable the high performance "server" VM. Since Java SE 5, <a href="http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html#ergonomics">Ergonomics</a> are used to automatically pick an appropriate VM, based on the characteristics of the hardware, OS, etc. We explicitly choose server to make the test more reliable.</li>
<li><strong>-XX:+TraceClassLoading</strong><br />
Output each loaded class to the console. Used to make sure that the test isn't disrupted by class loading, which would skew the results.</li>
<li><strong>-XX:+PrintCompilation</strong><br />
Output a line to the console when a method is compiled by the VM. Used to make sure that the test isn't disrupted by dynamic compilation, which would skew the results.</li>
<li><strong>-XX:+PrintGCDetails</strong><br />
Output a detailled message to the console with each garbage collection run. Used to check that no <a href="http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html#available_collectors.selecting">major collections</a> occur during a test, which would skew the results.</li>
<li><strong>-Xms512m -Xmx512m -XX:PermSize=256m -XX:MaxPermSize=256m</strong><br />
I purposely set high values to delay any garbage collection, because that could decrease performance on the later runs.</li>
</ul>
<h3>The results</h3>
<p><strong>NOTE: I've changed the benchmark since the previous article and the results presented here aren't comparable with the old ones!</strong></p>
<pre><script type="syntaxhighlighter" class="brush: plain">
Total times:
Total Class = 11282ms
Total Constructor = 12107ms
</script></pre>
<p>Hey, that's odd. <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance%28java.lang.Object...%29">Constructor.newInstance()</a> is more expensive than <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29">Class.newInstance()</a>. Strange... (ps. the result is the same on many runs on multiple machines)</p>
<h3>Fixing the problem</h3>
<p>But... Constructor.newInstance() is a <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html">varargs</a> method. This means a new array is created when it is invoked. Let's fix this line:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
                JavaBean bean = constructorCache.newInstance();
</script></pre>
<p>into this:</p>
<pre><script type="syntaxhighlighter" class="brush: java; first-line: 16">
                JavaBean bean = constructorCache.newInstance(NULL_ARRAY);
</script></pre>
<p>We also need to put this thingie somewhere:</p>
<pre><script type="syntaxhighlighter" class="brush: java; first-line: 16">
    private static final Object[] NULL_ARRAY = (Object[]) null;
</script></pre>
<p>This way, we pass in our own array, which is null, but this is enough to disable the creation of a new array.</p>
<p><strong>Note that I didn't just pass in a null literal. This would lead to <a href="http://weblogs.java.net/blog/2006/08/10/varargs-puzzler">a compiler warning and makes the code less obvious</a>.</strong></p>
<p>The results:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
Total times:
Total Class = 11263ms
Total Constructor = 11078ms
</script></pre>
<p>Yeah, now we're faster, but just a little bit.</p>
<h3>Wrapping up</h3>
<p>So, let's combine this with the other optimizations (method caching) and see where we end up:<br />
<em>"Java HotSpot(TM) Server VM (build 10.0-b23, mixed mode)"</em></p>
<pre><script type="syntaxhighlighter" class="brush: plain">
Total times:
Total Normal = 708ms
Total Reflection = 26492ms
Total Class = 11770ms
Total Constructor = 11682ms
Total Constructor And Methods = 1825ms
</script></pre>
<p>(these are the totals of a *lot* of runs)</p>
<p>And, for the fun of it, some OpenJDK results from my little Atom 330 Ubuntu machine: <em>"OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode)"</em>:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
Total Normal = 3713ms
Total Reflection = 136662ms
Total Class = 61733ms
Total Constructor = 62293ms
Total Constructor And Methods = 8246ms
</script></pre>
<p>So, invoking Constructor.newInstance(args...) is slightly cheaper than invoking Class.newInstance().</p>
<p>And, Reflection has gotten pretty damn fast if you ask me. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Don't forget to pass in a null array to prevent the JVM from automagically creating one for you.</strong></p>
<p><strong>Note: Class.newInstance() and Constructor.newInstance() behave differently with regards to Exceptions. See the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29">Class</a> and <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance%28java.lang.Object...%29">Constructor</a> documentation for details. The only thing I'm gonna say here, is that Constructor is the preferred way.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/05/01/reflection-slow-class-vs-constructor-newinstance/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Reflection slow? Well, it depends&#8230;</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 15:29:30 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1065</guid>
		<description><![CDATA[In this article, I&#8217;ll show you some ways to turn slow reflective code into faster code.
Reasons to use reflection
As some of you may know, many frameworks and libraries use reflection to do their thing. Reflection can be a solution for many sorts of issues, like:

Configuration. Many frameworks use text-based configuration, like XML. Classes are often [...]]]></description>
			<content:encoded><![CDATA[<p>In this article, I&#8217;ll show you some ways to turn slow reflective code into faster code.</p>
<h3>Reasons to use reflection</h3>
<p>As some of you may know, many frameworks and libraries use reflection to do their thing. Reflection can be a solution for many sorts of issues, like:</p>
<ul>
<li>Configuration. Many frameworks use text-based configuration, like XML. Classes are often configured in text files and need to be instantiated at some point. Also, method names (like event handlers or callbacks) might be configured in text files.</li>
<li>Frameworks in general. Whether you configure your classes in an external text file, annotations or some kind of <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/new-in-3.html#new-java-configuration">Java config</a>, the framework can never know the classes it invokes. This framework therefore almost always needs to invoke <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29">Class.newInstance()</a> or something similar (<a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance%28java.lang.Object...%29">Constructor.newInstance() is actually better</a>) to invoke the application classes. And, if you don&#8217;t want to put any restrictions on the application code, like requiring application classes to implement a predefined interface, you definitely need to use reflection to invoke methods and access fields.</li>
<li>Backwards compatibility. For example, the <a href="http://svn.apache.org/repos/asf/myfaces/core/trunk/api/src/main/java/javax/faces/validator/BeanValidator.java">BeanValidator in MyFaces</a> needs to behave in two different ways, depending on the available libraries. It uses the method <a href="http://java.sun.com/javaee/6/docs/api/javax/el/ValueExpression.html#getValueReference%28javax.el.ELContext%29">ValueExpression.getValueReference()</a>, but only if it is available (available since Unified EL 2.2). Otherwise, it uses a home-brewn mechanism. Reflection is needed, both for compile and at runtime. Otherwise, the code will throw a NoSuchMethodError when ValueExpression.getValueReference() is not available. Reflection is the way to determine method-existence on classes.</li>
<li>Tooling, or other kinds of code that need to inspect classes at runtime.</li>
<li>Simple class modifications, like making private methods accessible. OR-Mappers like Hibernate do this <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-property">for field access</a>, since fields are usually private.</li>
<li>Non-Java templating engines, like <a href="http://freemarker.sourceforge.net/">FreeMarker</a> or <a href="http://andyschwartz.wordpress.com/2009/07/31/whats-new-in-jsf-2/#facelets">Facelets</a>. Since templates are not Java bytecode, they rely on reflection to access Java stuff.</li>
</ul>
<h3>Reflection in JSF</h3>
<p>As you may know, JSF also uses reflection a lot. <a href="http://www.oracle.com/technology/tech/java/newsletter/articles/jsf_pojo/index.html">Managed Beans</a>, unlike i.e. <a href="http://struts.apache.org/1.x/struts-core/apidocs/org/apache/struts/action/Action.html">Struts Actions</a>, don&#8217;t have a specific interface, but (mostly) follow the JavaBean convention. This requires the framework to use reflection a lot, for example while resolving EL expressions to method calls.</p>
<p>Unfortunately, <a href="http://www.google.nl/search?q=java+reflection+is+slow">reflection is slow</a>. Note that I&#8217;m talking about nanoseconds per invocation here. Few reflective invocations in a single web request is nothing to be afraid about, especially compared to database and network latency. But, resolving expressions is a heavily used operation in any JSF request.</p>
<p>Profiling also shows that a significant portion of a JSF application is spent on reflection.</p>
<p>I say, time to improve this. But first, we need measurements to see what the problem is.</p>
<h3>Reflection performance, the test setup</h3>
<p>So, reflection is slow, right? What does slow really mean and how slow is it?</p>
<p>Let&#8217;s start with a simple, but typical, example of how reflection is used in most frameworks.</p>
<p>Consider a simple JavaBean:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class JavaBean {
    private int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}
</script></pre>
<p>A simple JavaBean with a String property. This JavaBean&#8217;s methods are to be invoked by the framework.</p>
<p>Now, let&#8217;s first write a simple program to access it without reflection. Not a single framework invokes application code directly, since it&#8217;s not compiled against it, but this will be our baseline for comparison.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class Runner {
    private static final int THREADS = 1000;
    private static final int ITERATIONS = 1000;

    private static final Random random = new Random();

    public static void main(String[] args) throws Exception {
        testConcurrent(NORMAL_ACCESS_TASK, "normal access WARMUP");
        testConcurrent(NORMAL_ACCESS_TASK, "normal access");
    }

    private static void testConcurrent(final Callable<Integer> task, final String name) throws InterruptedException {
        // Omitted for brevity, but this method starts <THREADS> threads
        // which concurrently access the object during <ITERATIONS> iterations.
    }

    private static Callable<Integer> NORMAL_ACCESS_TASK = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int j = 0; j < ITERATIONS; j++) {

// ################# Instantiate and invoke the bean START #################

                final JavaBean bean = new JavaBean();
                bean.setValue(j);
                final int value = bean.getValue();

// ################## Instantiate and invoke the bean END ##################

                counter = 37 * counter + value;
            }

            return counter;
        }
    };
}
</script></pre>
<p>A reliable concurrent test harness requires a lot of boilerplate code, but the essence is between the two comments. It invokes the bean methods in a plain Java way.</p>
<p>On my laptop, with 1000 threads and 1000 iterations, it takes 68ms to complete.</p>
<h3>Measuring reflection performance</h3>
<p>Now, let's try it out using reflection. After all, not a single framework is compiled against the application code, so the method above is the ideal, but impossible.</p>
<p>We add the following task to the test harness:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                final Class<JavaBean> clazz = (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
                JavaBean bean = clazz.newInstance();
                clazz.getMethod("setValue", Integer.TYPE).invoke(bean, i);
                final int value = (Integer) clazz.getMethod("getValue").invoke(bean);
                counter = 31 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>This code should look pretty familiar. It loads a class, given its name, instantiates it and invokes its methods, all using the standard Reflection API.</p>
<p>Don't mind the arithmetic stuff. It's used to prevent the JIT from removing too much (dead) code, which would render the test case useless.</p>
<p>Let's include it in the test, so the main method looks like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    public static void main(String[] args) throws Exception {
        testConcurrent(NORMAL_ACCESS_TASK, "normal access WARMUP");
        testConcurrent(NORMAL_ACCESS_TASK, "normal access");

        testConcurrent(REFLECTION_ACCESS_TASK, "reflection access WARMUP");
        testConcurrent(REFLECTION_ACCESS_TASK, "reflection access");
    }
</script></pre>
<p>The results are obvious:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
  - normal access WARMUP: time = 72ms, counter = 218579914 
  - normal access: time = 68ms, counter = 218579458 
  - reflection access WARMUP: time = 4602ms, counter = 218579743 
  - reflection access: time = 3307ms, counter = 218579280 
</script></pre>
<p>So, full blown reflection is about 50 times slower. Not good, right? Let's try to improve this.</p>
<h3>Optimizing reflective code: Caching classes</h3>
<p>But, of course we can do better. Let's tune the reflective approach a bit.</p>
<p>The first optimization is caching the Class object. Classes are thread safe and can be cached and reused safely.</p>
<p>Caching a Class object saves a <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#forName%28java.lang.String%29">lot of repeated overhead</a>, like contacting the SecurityManager, ClassLoader, etc. So this should be a significant improvement.</p>
<p>The code looks like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CLASS_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache = loadClass();

        private Class<JavaBean> loadClass() {
            try {
                return (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Cannot initialize JavaBean", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                JavaBean bean = classCache.newInstance();
                classCache.getMethod("setValue", Integer.TYPE).invoke(bean, i);
                final int value = (Integer) classCache.getMethod("getValue").invoke(bean);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>And we of course add the task to the test.<br />
Performance got better with about 40%</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
  - normal access WARMUP: time = 72ms, counter = 218579914 
  - normal access: time = 68ms, counter = 218579458 
  - reflection access WARMUP: time = 4602ms, counter = 218579743 
  - reflection access: time = 3307ms, counter = 218579280 
  - reflection access (cached class) WARMUP: time = 1956ms, counter = 218579659 
  - reflection access (cached class): time = 1917ms, counter = 218579628 
</script></pre>
<p>So, we can safely conclude that in general, it's a good idea to cache Class instances if you plan to instantiate them a lot. Don't cache too much, because such loitering objects are the number one reason of Java memory leaks. But, a "Map&lt;String, Class&gt;" with a fixed amount of classes (like all your controllers) should do no harm here.</p>
<h3>Optimizing reflective code: Caching method handles</h3>
<p>There is more reflective code that can be optimized. The Method instances are also good candidates for caching. After all, you obtain the same <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke%28java.lang.Object,%20java.lang.Object...%29">Method</a> handle every time and invoke it with an instance parameter. So, let's cache the getter and setter methods, like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CLASS_AND_METHODS_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache = loadClass();
        private final Method getterCache = loadGetter();
        private final Method setterCache = loadSetter();

        private Method loadGetter() {
            try {
                return classCache.getMethod("getValue");
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot get getter method handle", e);
            }
        }

        private Method loadSetter() {
            try {
                return classCache.getMethod("setValue", Integer.TYPE);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot get setter method handle", e);
            }
        }

        private Class<JavaBean> loadClass() {
            try {
                return (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Cannot initialize JavaBean", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                JavaBean bean = classCache.newInstance();
                setterCache.invoke(bean, i);
                final int value = (Integer) getterCache.invoke(bean);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>The code is getting a lot messier with every tweak, but don't worry. There are other, more concise ways to do this. I chose this approach because of testability (<a href="http://www.ibm.com/developerworks/java/library/j-jtp02225.html">writing a correct concurrent test is hard</a>).</p>
<p>The results, however, don't lie:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
  - normal access WARMUP: time = 123ms, counter = 218578998 
  - normal access: time = 63ms, counter = 218579569 
  - reflection access WARMUP: time = 4711ms, counter = 218579400 
  - reflection access: time = 3001ms, counter = 218579313 
  - reflection access (cached class) WARMUP: time = 2214ms, counter = 218579055 
  - reflection access (cached class): time = 2067ms, counter = 218579560 
  - reflection access (cached class+methods) WARMUP: time = 466ms, counter = 218579101 
  - reflection access (cached class+methods): time = 537ms, counter = 218579916 
</script></pre>
<p>Caching the two methods improves performance with about 400%. But we have two methods, so let's conclude a 200% improvement per method.</p>
<p>At this point, we've performance has improved about ten times, compared to the original reflection implementation. But, even this optimized version is still about 6 to 10 times slower than the original one.</p>
<p>Unfortunately, using standard reflection, we can't make much more improvements. The JIT simply has less ways to optimize reflective invocations than it has with normal bytecode (<a href="http://openjdk.java.net/projects/mlvm/subprojects.html#InvokeDynamic">invokedynamic in JDK 7 improves this</a>).</p>
<h3>Optimizing reflective code: Caching instances</h3>
<p><b>This optimization is only applicable to stateless objects! Using it on objects with state leads to correctness problems!</b></p>
<p>Let's assume that correctness is irrelevant so we can cache instances of the bean. The code would look like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CLASS_AND_METHODS_AND_INSTANCE_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache = loadClass();
        private final Method getterCache = loadGetter();
        private final Method setterCache = loadSetter();
        private final JavaBean instanceCache = loadInstance();

        private JavaBean loadInstance() {
            try {
                return classCache.newInstance();
            } catch (Exception e) {
                throw new RuntimeException("Cannot get instance", e);
            }
        }

        private Method loadGetter() {
            try {
                return classCache.getMethod("getValue");
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot get getter method handle", e);
            }
        }

        private Method loadSetter() {
            try {
                return classCache.getMethod("setValue", Integer.TYPE);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot get setter method handle", e);
            }
        }

        private Class<JavaBean> loadClass() {
            try {
                return (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Cannot initialize JavaBean", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                setterCache.invoke(instanceCache, i);
                final int value = (Integer) getterCache.invoke(instanceCache);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>And the results:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
  - normal access WARMUP: time = 120ms, counter = 218579735 
  - normal access: time = 70ms, counter = 218579495 
  - reflection access WARMUP: time = 3902ms, counter = 218579662 
  - reflection access: time = 3001ms, counter = 218579761 
  - reflection access (cached class) WARMUP: time = 1897ms, counter = 218579863 
  - reflection access (cached class): time = 1910ms, counter = 218579251 
  - reflection access (cached class+methods) WARMUP: time = 440ms, counter = 218579665 
  - reflection access (cached class+methods): time = 426ms, counter = 218578955 
  - reflection access (cached class+methods+instance) WARMUP: time = 370ms, counter = 1124350138 
  - reflection access (cached class+methods+instance): time = 247ms, counter = 1268925652 
</script></pre>
<p>So, we've won about 100-200ms by not invoking the newInstance method. But, since creating objects also affects garbage collection (in this test we create one million beans per test) and we've refactored the local variable to a static final variable the performance implications of the newInstance call itself are not obvious. But, it's a fact that we've improved performance by caching the instance.</p>
<p>But note, this approach only applies to stateless or immutable objects. Wherever there's state, you need new instances.</p>
<h3>Optimizing reflective code: Conclusion</h3>
<p>In this article, we've seen how the performance of reflection differs from 'normal' Java bytecode performance.</p>
<p>We've also seen how some simple tweaks like caching Class and Method objects make reflective code a lot faster.</p>
<p>But still, even when caching instances, the performance of reflection doesn't even come close to the performance of plain Java bytecode (where the instances weren't cached).</p>
<p>There are examples of high performance reflection, for example in the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.html">java.util.concurrent.atomic.AtomicReferenceFieldUpdater class</a>, but this kind of code should not be written by anyone except <a href="http://g.oswego.edu/">Doug Lea</a>. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (and b.t.w., it hurts portability)</p>
<p>So, should you use reflection in your application? It depends. If you're writing high performance stuff that's invoked very, very often, I would say no. If you're writing a simple method dispatcher that gets invoked once per web request in a normal web application, I wouldn't care about the performance of the reflective invocation. After all, we're still talking about nano-/milliseconds here.</p>
<p>In the next entry, I'll show you how you can use <a href="http://asm.ow2.org/">bytecode enhancement</a> to get the same functionality as with reflection, but without a huge performance penalty.</p>
<p><b>Edit</b><br />
Note: I just heard that in some cases, HotSpot is able to inline through reflection calls, enabling it to apply all it's JIT tricks on it, effectively reducing the invocation cost to zero! But it only works if it can prove if the invoked method is always the same, which is not always true unfortunately.<br />
<a href="http://java.sun.com/products/hotspot/whitepaper.html#performance">http://java.sun.com/products/hotspot/whitepaper.html#performance</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Immutable lists</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/26/immutable-lists/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/26/immutable-lists/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 15:03:51 +0000</pubDate>
		<dc:creator>Pieter van der Meer</dc:creator>
				<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Java language]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1048</guid>
		<description><![CDATA[The last couple of years there is more and more talk about concurrency. One of the main issues is the access data from the various threads that you have running.
Brian Goetz has a simple statement on how to solve this:  Use immutable objects where ever possible. Although true it is not always as simple to [...]]]></description>
			<content:encoded><![CDATA[<p>The last couple of years there is more and more talk about concurrency. One of the main issues is the access data from the various threads that you have running.</p>
<p>Brian Goetz has a simple statement on how to solve this:  <em>Use immutable objects where ever possible. </em>Although true it is not always as simple to implement your data structures immutable. especially when you are working with Collections (List/Set/Map).</p>
<p>Making the collection variable immutable is easy,<br />
<span id="more-1048"></span></p>
<pre class="brush: java">class finalSet {
  private final Set theSet;
  public finalSet(Set theSet) {
    this.theSet = theSet;
  }

  public Set getSet() {
    return this.theSet;
  }
}</pre>
<p>With this it is not possible the change the value of the Set parameter. But when retrieving the Set with <em>getSet </em>you are still able to modify the content of the set.  This effectively means that the set you attempted to make immutable is still mutable.</p>
<p>The documentation of the <a href="http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html">Collections Framework</a> does not provide an answer on how to make the collection immutable. they speak just a little about the class <span style="font-family: Consolas, Monaco, 'Courier New', Courier, monospace; line-height: 18px; font-size: 12px; white-space: pre;">Collections<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">. </span></span></p>
<p><span style="font-family: Consolas, Monaco, 'Courier New', Courier, monospace; line-height: 18px; font-size: 12px; white-space: pre;"><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">Taken from the documentation page:</span></span></p>
<blockquote><p>The general-purpose implementations support all of the <em>optional operations</em> in the collection interfaces, and have no restrictions on the elements they may contain. They are unsynchronized, but the <code>Collections</code> class contains static factories called <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedCollection(java.util.Collection)"><em>synchronization wrappers</em></a> that may be used to add synchronization to many unsynchronized collections. All of the new implementations have <em>fail-fast iterators</em>, which detect illegal concurrent modification, and fail quickly and cleanly (rather than behaving erratically).</p></blockquote>
<p>What they say there is a Collections class that does all kind of things for you, mainly synchronization, but do not really say what else it can do for you. As you might guess it provides with methods to make you list immutable!</p>
<p>Take a look at the <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html">Collections javadoc</a> (without explicitly searching for this class its hard to find).<br />
It gets interesting when you scroll down to the methods that start with</p>
<pre>unmodifiable</pre>
<p>. For all the base interface from the <a href="http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html">Collections Framework</a> there is a method to make it unmodifiable. hey wait a second: unmodifiable aint that the same as immutable? To my humble opinion it does. So Java does provide a out of the box solution to make a collection immutable!</p>
<p>this code snippet proves that it works:</p>
<pre class="brush: java">import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

/**
 * Simple Unit test for immutability
 */
public class ListTest {

    /**
     * The actual testing for a List
     */
    @Test (expected = UnsupportedOperationException.class)
    public void immutableList() {
        //Create a simple mutable list
        List mutableList = new ArrayList();
        mutableList.add("A");
        mutableList.add("B");
        //Make this immutable
        List immutableList = Collections.unmodifiableList(mutableList);

        //Try and set the value of an element in the list
        immutableList.set(1, "X");
    }

    /**
     * The actual testing for a Set
     */
    @Test (expected = UnsupportedOperationException.class)
    public void immutableSet() {
        //Create a mutable set
        Set mutableSet = new HashSet();
        mutableSet.add("A");
        mutableSet.add("B");
        //Change it to immutable
        Set immutableSet = Collections.unmodifiableSet(mutableSet);

        //Try and add an element to it.
        immutableSet.add("X");
    }
}</pre>
<p>When you run the unit tests both the tests will succeed.</p>
<p><strong>Conclusion</strong>:<br />
making a list immutable ain&#8217;t that hard <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  Just be aware i say nothing about the elements in the list, they must be immutable as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/26/immutable-lists/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>JSF 2.0 ClientBehavior: First impressions</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/19/jsf-2-0-clientbehavior-first-impressions/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/19/jsf-2-0-clientbehavior-first-impressions/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 18:05:57 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[ClientBehavior]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JSF 2.0]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1024</guid>
		<description><![CDATA[In my previous article, I wrote about my first real JSF 2.0 ClientBehavior, called ValidateBeanBehavior.
While programming, I&#8217;ve experienced some issues that, in my opinion, make the ClientBehavior less usable in many cases.
Events
A ClientBehavior is attached to a component, both on the server side and on the client side. On the client side, this simply means [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.smart-java.nl/blog/index.php/2010/03/17/jsf-2-0-clientbehavior-bean-validation-in-javascript/">my previous article</a>, I wrote about my first real JSF 2.0 ClientBehavior, called ValidateBeanBehavior.</p>
<p>While programming, I&#8217;ve experienced some issues that, in my opinion, make the ClientBehavior less usable in many cases.</p>
<p><b>Events</b><br />
A ClientBehavior is attached to a component, both on the server side and on the client side. On the client side, this simply means that an event listener is attached to an HTML element. The event listener then contains the scripts generated by the ClientBehavior.</p>
<p>For example, the generated JavaScript of ValidateBeanBehavior looks like this in the browser.</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head&gt;
    &lt;title&gt;test&lt;/title&gt;
    &lt;script type="text/javascript" src="/jsf2test/javax.faces.resource/validationBehavior.js.xhtml"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;form id="j_idt8" name="j_idt8" method="post"
          action="/jsf2test/index.xhtml" enctype="application/x-www-form-urlencoded"&gt;
      &lt;input type="hidden" name="j_idt8" value="j_idt8" /&gt;
      text: &lt;input type="text" name="j_idt8:j_idt10" /&gt;&lt;br /&gt;
      number: &lt;input type="text" name="j_idt8:j_idt12" /&gt;&lt;br /&gt;
      date: &lt;input type="text" name="j_idt8:j_idt14" /&gt;&lt;br /&gt;

      &lt;input id="j_idt8:j_idt16" type="submit" name="j_idt8:j_idt16" value="Click"
          onclick="return org.jkva.validateBean.validateForm([...])" /&gt;

      &lt;input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState"
          value="..." autocomplete="off" /&gt;
    &lt;/form&gt;
  &lt;/body&gt;
&lt;/html&gt;
</script></pre>
<p>Do you see the onclick handler on my submit button? This is the ClientBehavior at work. I&#8217;ve attached the ClientBehavior to my submit button and you can see what it looks like in the snippet above.</p>
<p>Looks nice, not? No, it doesn&#8217;t. You shouldn&#8217;t use onclick for validations. Why not? Because the behavior of onclick differs between browsers with regards to form submits. For example, many users use ENTER to &#8216;implicitly submit&#8217; the form. Different browsers behave differently on such implicit submits, either triggering the onclick of the default submit button (where default is also undefined) or nothing at all.</p>
<p>The current HTML specs are also <a href="http://www.w3.org/TR/html401/interact/forms.html#successful-controls">quite vague about implicit submits</a>. It says the following:</p>
<blockquote><p>If a form contains more than one submit button, only the activated submit button is successful.</p></blockquote>
<p>Sounds nice, but what does &#8220;activated&#8221; mean? When clicking a button, it&#8217;s obviously the clicked button, but what to do when pressing ENTER?</p>
<p>Different things may happen in different browsers. For example, in my current Firefox (3.5.8), IE8 and Chrome 4.1 browsers, the default button is the first button (first is determined as the first one in the source).</p>
<p>But in other, mainly older browsers, no click event may be raised. Or, it may raise a click event on the wrong button (the first one after the active input or the first one, based on tab order). This makes it a very unpredictable (and thus not very useful) mechanism.</p>
<p>The <a href="http://www.w3.org/TR/html5/forms.html#implicit-submission">HTML5 spec</a> is much clearer about implicit submission and it&#8217;s behavior. But, since many users won&#8217;t use a HTML5 browser for a while, we simply need a more reliable mechanism, like form.onsubmit. We&#8217;ve written our JavaScript validations on onsubmit for years and it simply works. But the standard JSF2 components don&#8217;t support it.</p>
<p><b>Initialization</b><br />
Another issue with onclick is that it doesn&#8217;t provide any window.onload/document.ready support. It simply executes some JavaScript when the button is pressed and there is no way to initialize your JavaScript using a ClientBehavior.</p>
<p>For example, I would have liked to initialize my validateBean JS using the ClientBehavior. This would enable me to provide input masking support.<br />
The mechanism for this needs to be initialized though. Some keyup/-down handlers need to be attached to the form fields and this needs to be done when the page is loaded.</p>
<p>ClientBehavior doesn&#8217;t support this. In the ValidateBeanBehavior, I added a @ResourceDependency for my scripts. I can put my initialization logic there, but why should I use a ClientBehavior when all I want to do is loading a JS file? I don&#8217;t know.</p>
<p><b>Default RenderKit</b><br />
The default RenderKit, HTML_BASIC, attaches the event handlers inline using the &#8220;on[eventName]&#8221; attribute on the HTML tag. While this is easier for JSF implementers, I generally consider inline event handlers a bad practice. I prefer attaching them in the DOM L2 style: addEventListener (or attachEvent in IE). This allows multiple event handlers and if I really don&#8217;t care about this, I still dynamically add them using element.on[eventName]. I think this gives much better markup, because of the separation of markup and scripts.</p>
<p>But, 3th party components may do better here&#8230;</p>
<p><b>Supported components</b><br />
All components that implement ClientBehaviorHolder may have one or more ClientBehaviors attached to them. Unfortunately, on UIForm, no event named &#8220;submit&#8221; is supported. And since submit is the most widely used event on forms, this is quite annoying, making behaviors not very useful for standard forms. After all, who wants to handle the dblclick event on a form?</p>
<p>Third party components may of course also implement ClientBehaviorHolder and take advantage of it.</p>
<p><b>So where is ClientBehavior useful?</b><br />
Simply put, all client side event handlers you&#8217;d like to attach to EditableValueHolder or UICommand components that are triggered explicitly, for example by onchange or onclick events. I can imagine something like effects can be implemented nicely with ClientBehaviors. But OTOH, most effects in real world applications aren&#8217;t used standalone, but as a part of an Ajax transaction, so I don&#8217;t see much use there either.</p>
<p>The concept of ClientBehaviorHolder is generic and can be applied by any component, so I hope the ICEFaces, RichFaces and Trinidad folks take advantage of this mechanism. I think interoperability between libraries will increase with this.</p>
<p>But maybe I&#8217;m just negative because I&#8217;d like to completely control my JavaScript.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/19/jsf-2-0-clientbehavior-first-impressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSF 2.0 ClientBehavior: Bean Validation in JavaScript</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/17/jsf-2-0-clientbehavior-bean-validation-in-javascript/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/17/jsf-2-0-clientbehavior-bean-validation-in-javascript/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 21:02:29 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[ClientBehavior]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JSF 2.0]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1008</guid>
		<description><![CDATA[In the following article I&#8217;m going to show you my first &#8220;real world&#8221; ClientBehavior and my first impressions from a user&#8217;s perspective.
First, some theory. JSF has support for something called &#8220;attached objects&#8221;. This has been since the very beginning, with Converters and Validators.
Since JSF 2.0, Behaviors have been added to this list. A Behavior, when [...]]]></description>
			<content:encoded><![CDATA[<p>In the following article I&#8217;m going to show you my first &#8220;real world&#8221; <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/javax/faces/component/behavior/ClientBehavior.html">ClientBehavior</a> and my first impressions from a user&#8217;s perspective.</p>
<p>First, some theory. JSF has support for something called &#8220;attached objects&#8221;. This has been since the very beginning, with <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/convert/Converter.html">Converters</a> and <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/validator/Validator.html">Validators</a>.<br />
Since <a href="http://www.javaserverfaces.org/">JSF 2.0</a>, Behaviors have been added to this list. A Behavior, when attached to a component, adds client side scripts to an object. For example, one can imagine a Behavior to do an Ajax request, load some data and show it on the page. This will be a common use case for behaviors. The Expert Group understood this and came up with a specialized <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/component/behavior/AjaxBehavior.html">AjaxBehavior</a>, which is quite similar to the <a href="http://www.jboss.org/richfaces">Ajax4jsf</a> <a href="http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html_single/#a4j_support">&lt;:a4jsupport /&gt; tag</a>. it adds Ajax functionality to the existing component, without modifying it.</p>
<p>This is ClientBehavior in a nutshell. There are more subtile things to know, see this <a href="http://java.dzone.com/articles/jsf-2-client-behaviors">article by Andy Schwartz</a> for a more thorough explanation of the subject.</p>
<p><strong><em>From now on, I assume at least basic ClientBehavior knowledge and of course JSF knowledge.</em></strong></p>
<p><b>The ValidateBean Behavior</b><br />
With Java EE 6 we got <a href="http://jcp.org/en/jsr/detail?id=303">Bean Validation</a>. And I must admit, I like it a lot. It has a nice declarative language and one ubiquitous model for defining validations for your entire system, from database (generating Bean Validation-aware DDL with JPA 2.0) to UI (the JSF 2.0 BeanValidator, which I implemented for <a href="http://myfaces.apache.org/">Apache MyFaces</a>. That&#8217;s where my enthusiasm started).</p>
<p>But, one validation is missing in the spec (with good reasons of course), namely client side JavaScript validations, to improve usability and decrease server load.</p>
<p>Especially since JavaScript validations are often skipped because of maintenance reasons (validations implemented twice) and we now have a robust platform to implement generic validations, I tried to combine the two new technologies (ClientBehavior and Bean Validation) into one generic JavaScript validator.</p>
<p><b>The ClientBehavior implementation</b></p>
<pre><script type="syntaxhighlighter" class="brush: java">
@FacesBehavior("org.jkva.ValidateBeanBehavior")
@ResourceDependency(name = "validateBeanBehavior.js")
public class ValidateBeanBehavior extends ClientBehaviorBase {
    @Override
    public String getScript(ClientBehaviorContext ctx) {
        UIComponent component = ctx.getComponent();
        if (component instanceof UICommand) {
            UIForm form = findParentForm(component);
            if (form == null) {
                throw new FacesException("No parent form found");
            }
            List&lt;UIInput&gt; inputsInForm = findInputs(form);
            UIMessages messages = findMessages(ctx.getFacesContext().getViewRoot());
            return getSubmitHandler(form, inputsInForm, messages);
        } else {
            throw new FacesException("Unsupported component: " + component + " Only UICommand components are supported");
        }
    }
}
</script></pre>
<p>This class has some interesting things. First, of course the annotations. <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/component/behavior/FacesBehavior.html">@FacesBehavior</a> simply registers the class as a ClientBehavior under the given name, just like how Managed Beans or Converters work. The second annotation defines a <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/application/ResourceDependency.html">@ResourceDependency</a>. A ResourceDependency simply says: &#8220;Hey JSF, I generate markup which depends on this file. Make sure it&#8217;s available&#8221;. And JSF 2.0 responds with: &#8220;Okay, I will&#8221;.</p>
<p>Also, you probably noticed my ClientBehavior to only understand buttons. That&#8217;s right, you need to attach it to a button and it takes care of wiring all field validations in the form.</p>
<p>It also looks for a messages component. This is used later to make sure the JS error messages are positioned the same as the by JSF generated messages. <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/component/UIMessages.html">UIMessages</a> applies to the entire view, so I don&#8217;t just look in the form. A high performance implementation may choose to start searching near the form, since most messages are positioned there, but that&#8217;s way out of scope of this article.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
private String getSubmitHandler(UIForm form, List&lt;UIInput&gt; inputsInForm, UIMessages messages) {
    FacesContext fc = FacesContext.getCurrentInstance();
    StringBuilder sb = new StringBuilder();
    sb.append("return org.jkva.validateBean.validateForm(");
    sb.append("'" + form.getClientId(fc) + "', ");
    if (messages != null) {
        sb.append("'" + messages.getClientId(fc) + "'");
    } else {
        sb.append("null");
    }
    sb.append(", [");
    String sep = "";
    for (UIInput input : inputsInForm) {
        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(fc, input);
        Set&lt;ConstraintDescriptor&lt;?&gt;&gt; constraints = propertyDescriptor.getConstraintDescriptors();
        ValidationPropertyModel model = createValidationModel(input, propertyDescriptor, constraints);

        String fieldValidation = getFieldMetadata(input, model, fc);
        sb.append(sep);
        sb.append(fieldValidation);
        sep = ",";
    }
    sb.append("])");
    return sb.toString();
}
</script></pre>
<p>I know, I know, this is not the most elegant piece of code, but it nicely illustrates the point. I simply aggregates as much validation metadata as possible and writes it into one big JavaScript statement. Not that optimal, but high performance implementations may choose to dynamically generate a JS file with all metadata which only needs to be referenced from the inline JS code.</p>
<p>If you&#8217;d like to know how to obtain the ConstraintDescriptors (the four method calls in the above snippet), just look for the <a href="http://svn.apache.org/repos/asf/myfaces/core/trunk/api/src/main/java/javax/faces/validator/BeanValidator.java">BeanValidator in the Apache MyFaces SVN</a>. I reused the same code here.</p>
<p><b>The JavaScript</b><br />
The JavaScript shown below is part of the static scripts that belong to the ValidateBeanBehavior. It contains the JavaScript code to execute the rules, as passed from the server and, if needed, show the validation errors.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
var org;
if ("undefined" == typeof org) org = {};
if ("undefined" == typeof (org.jkva)) org.jkva = {};
if ("undefined" == typeof (org.jkva.validateBean)) {

    org.jkva.validateBean = {

        validateForm: function(formId, messagesId, validations) {
            var errors = [];
            var form = document.getElementById(formId);
            var elems = form.elements;
            for (var i = 0; i &lt; validations.length; i++) {
                var val = validations[i];
                var field = elems[val.fieldId];
                var error = org.jkva.validateBean.validateField(field, val);
                if (error) {
                    if (val.fieldId) {
                        var label = org.jkva.validateBean.findLabelForField(field);
                        if (!label) {
                            label = val.fieldId;
                        }
                    } else {
                        var label = val.fieldId;
                    }
                    errors.push(label + ":" + error);
                }
            }

            if (errors.length) {
                var messages = document.getElementById(messagesId);
                if (!messages) {
                    messages = document.createElement("span");
                    messages.id = messagesId;
                    form.insertBefore(messages, form.firstChild);
                }

                messages.innerHTML = org.jkva.validateBean.arrayToUnorderedList(errors);

                return false;
            } else {
                return true;
            }
        },

        ...
    }
}
</script></pre>
<p>It&#8217;s a lot of code, which, in essence, validates all input fields in the given form, according to the given validation rules and shows the user an error if needed. This error is positioned at the same spot as where the UIMessages would have been rendered in case of a server side error. This is a best guess though, because when the messages are not rendered (i.e. on the initial request), there is no marker in the page that I can use for positioning. A more sophisticated implementation could enrich all UIMessages in the page to always write some marker &#8220;div&#8221; with an ID to the client.</p>
<p>I&#8217;m going to skip the rest of the JavaScript. It&#8217;s just a bunch of validations and utilities, like utilities to convert Strings to and from Date Objects, based on a <a href="http://java.sun.com/javase/6/docs/api/index.html?java/text/SimpleDateFormat.html">SimpleDateFormat</a> pattern. This pattern is part of the generated JavaScript and is obtained by looking at the attached Converters.</p>
<p><b>Usage in a Facelet</b><br />
To make the ClientBehavior a bit easier to use, here&#8217;s a Facelets taglib which defines a tag for the ClientBehavior (don&#8217;t forget to configure the taglib in web.xml or put it in the /META-INF of a JAR).</p>
<pre><script type="syntaxhighlighter" class="brush: java">
&lt;?xml version='1.0' encoding='UTF-8'?&gt;
&lt;facelet-taglib version="2.0"
                xmlns="http://java.sun.com/xml/ns/javaee"&gt;
    &lt;namespace&gt;http://www.jkva.org/validateBeanBehavior&lt;/namespace&gt;
    &lt;tag&gt;
        &lt;tag-name&gt;validateBean&lt;/tag-name&gt;
        &lt;behavior&gt;
            &lt;behavior-id&gt;org.jkva.ValidateBeanBehavior&lt;/behavior-id&gt;
        &lt;/behavior&gt;
    &lt;/tag&gt;
&lt;/facelet-taglib&gt;
</script></pre>
<p>With the taglib in place, we can use the ClientBehavior, like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:jkva="http://www.jkva.org/validateBeanBehavior"&gt;
&lt;h:head&gt;
    &lt;title&gt;test&lt;/title&gt;
&lt;/h:head&gt;
&lt;h:body&gt;
    &lt;h:messages/&gt;
    &lt;h:form&gt;
        &lt;h:outputLabel value="text" for="text" /&gt;
        &lt;h:inputText value="#{myBean.text}" id="text"/&gt;&lt;br/&gt;

        &lt;h:outputLabel value="number" for="number" /&gt;
        &lt;h:inputText value="#{myBean.number}" id="number" /&gt;&lt;br/&gt;

        &lt;h:outputLabel value="date" for="date" /&gt;
        &lt;h:inputText value="#{myBean.date}" id="date"&gt;
            &lt;f:convertDateTime pattern="dd-MM-yyyy"/&gt;
        &lt;/h:inputText&gt;&lt;br/&gt;
        &lt;h:commandButton value="Hello" action="/hello" immediate="true"/&gt;
        &lt;h:commandButton value="Click" action="#{myBean.click}"&gt;
            &lt;jkva:validateBean /&gt;
        &lt;/h:commandButton&gt;
    &lt;/h:form&gt;
&lt;/h:body&gt;
&lt;/html&gt;
</script></pre>
<p>That&#8217;s not too much effort for a client side form validation right? And, these validations are always in-sync with the server side validations.</p>
<p>After a bit of cleanup, I&#8217;ll commit the code into the <strong><a href="http://myfaces.apache.org/sandbox/index.html">Apache MyFaces Sandbox</a></strong>, so you can download it from there when I&#8217;m done. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/17/jsf-2-0-clientbehavior-bean-validation-in-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to de-frameset a Web App with Apache Tiles 2</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 15:45:12 +0000</pubDate>
		<dc:creator>Assen Kolov</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tiles]]></category>

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

&lt;tiles-definitions&gt;

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

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

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

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

&lt;/tiles-definitions&gt;

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

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

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

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

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

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

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

   container.render(templateName, request, response);
   container.endContext(request, response);
  }
}
</script></pre>
<p>This servlet always renders the same tiles definition, providing an appropriate body. For example, a request to /showOrder.tiled?orderId=100 would render the output of /showOrder?orderId=100 as the body tile in the tiles definition. No separate tiles definition and JSP for each view are needed.</p>
<h3>
What&#8217;s next?</h3>
<p>All the code above only provides an easy template-decorated view for each servlet output. There is sill a lot of work that has to be done manually:<br />
- move all separate styles, scripts etc. from the separate pages to the template<br />
- requestDispacher.forward in a servlet closes the output stream while it is still needed for the tiles template; all forwards must become includes;<br />
- all navigation javascript referring to top.menu ot top.body has to be refatored manually.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing a Bean Validation ConstraintValidator</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 15:27:16 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Java language]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[ConstraintValidator]]></category>
		<category><![CDATA[Dynamic Proxies]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=976</guid>
		<description><![CDATA[I&#8217;ve been playing a bit with Bean Validation and thought I found an issue: Unit testing a ConstraintValidator. Specifically, parametrized ConstraintValidators.
First, what&#8217;s a parametrized ConstraintValidator? Simple, a Validator that takes a parameter to do its job. A simple example is a length validator that takes the minimum and maximum length as parameters and validates if [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing a bit with Bean Validation and thought I found an issue: Unit testing a ConstraintValidator. Specifically, parametrized ConstraintValidators.</p>
<p>First, what&#8217;s a parametrized ConstraintValidator? Simple, a Validator that takes a parameter to do its job. A simple example is a length validator that takes the minimum and maximum length as parameters and validates if the value is between those two.</p>
<p>Parametrized ConstraintValidators are everywhere, even Bean Validation itself contains them. For example: @Min(length) and @Max(length), but also normal ConstraintValidators, like @NotNull where you can customize the error message. However, this error message parameter is not very interesting with regards to unit testing individual ConstraintValidators, because the message is generated by the Bean Validation framework.</p>
<p>For example, consider this ConstraintValidator, incl. corresponding annotation:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = CreditCardExpiryYearValidator.class)
public @interface CreditCardExpiryYear {
    int expirationInYears() default 10;
    String message() default "{validation.CreditCardExpiryYear.message}";
}

public class CreditCardExpiryYearValidator implements ConstraintValidator&lt;CreditCardExpiryYear, Integer&gt; {
    private volatile int expirationInYears;
    public void initialize(CreditCardExpiryYear constraint) {
        this.expirationInYears = constraint.expirationInYears();
    }

    public boolean isValid(Integer year, ConstraintValidatorContext context) {
        final int nowYear = Calendar.getInstance().get(Calendar.YEAR);
        return year != null
            &amp;&amp; year &lt; nowYear + expirationInYears;
    }
}
</script></pre>
<p>In the future, Bean Validation may become the core mechanism for ensuring correctness in your system. For example, JPA 2.0 leverages Bean Validation annotations to generate additional DDL statements and JSF 2.0 automatically uses Bean Validation when it&#8217;s available. Note: JSF 2.0 uses a new concept, called &#8220;default validators&#8221; to implement this. A default validator is invoked on every input component on a postback.</p>
<p>But, how do we test this stuff? After all, you can&#8217;t instantiate an annotation.</p>
<p>I currently have 4 options:</p>
<ul>
<li><a href="#reflection">Using reflection to use a declared annotation</a></li>
<li><a href="#implementation">Custom annotation implementation</a></li>
<li><a href="#dynamic_proxies">Dynamic proxies</a></li>
<li><a href="#mockito">Mocking, for example using Mockito</a></li>
</ul>
<p><b><a name="reflection">Using a declared annotation</a></b><br />
The first attempt is shown below. Here, I simply declare the annotation in my test case on a dummy instance field (an annotation doesn&#8217;t live on its own) and look it up using reflection. This way, Java takes care of instantiating and initializing the annotation.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class CreditCardExpiryYearValidatorTest {

    @CreditCardExpiryYear(expirationInYears = 5)
    int expiryAfter5Years;

    @CreditCardExpiryYear
    int expiryAfter10Years;

    private int currentYear;

    @Before
    public void setUp() throws Exception {
        currentYear = Calendar.getInstance().get(Calendar.YEAR);
    }

    @Test
    public void testIsValid_DefaultExpiration() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(getFieldAnnotation(this, "expiryAfter10Years", CreditCardExpiryYear.class));

        boolean b = val.isValid(currentYear + 5, null);

        assertTrue(b);
    }

    @Test
    public void testIsValid_Configure5Years() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(getFieldAnnotation(this, "expiryAfter5Years", CreditCardExpiryYear.class));

        boolean b = val.isValid(currentYear + 6, null);

        assertFalse(b);
    }
}
</script></pre>
<p>I personally quite like this approach. The test data is inside the test case. Unfortunately not in the test method, that would be better, but since you can&#8217;t put annotations everywhere in your code, it&#8217;s not easy to implement this decently.</p>
<p>So let&#8217;s look at the next one&#8230;</p>
<p><b><a name="implementation">Custom annotation implementation</a></b><br />
Since Java annotations are just a special case of interfaces, they should be fairly straightforward to implement. However, for some reason, I didn&#8217;t know this until recently. But it&#8217;s actually not different from any other interface implementation. See for yourself.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class CreditCardExpiryYearValidatorTest {

    private int currentYear;

    @Before
    public void setUp() throws Exception {
        currentYear = Calendar.getInstance().get(Calendar.YEAR);
    }

    @Test
    public void testIsValid_CustomAnnotationImpl() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(new CreditCardExpiryYearImpl());

        boolean b = val.isValid(currentYear + 6, null);

        assertFalse(b);
    }
}
class CreditCardExpiryYearImpl implements CreditCardExpiryYear {
    public int expirationInYears() { return 5; }
    public String message() { return "hello"; }
    public Class&lt;? extends Annotation&gt; annotationType() { return CreditCardExpiryYear.class; }
}
</script></pre>
<p>Nothing special, right? But I don&#8217;t really like it. I could have also written it inline, but I don&#8217;t like that either:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_CustomAnnotationImplInline() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    val.initialize(new CreditCardExpiryYear() {
        public Class&lt;? extends Annotation&gt; annotationType() { return CreditCardExpiryYear.class; }
        public String message() { return ""; }
        public int expirationInYears() { return 5; }
    });

    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>I think the above one looks like garbage. So this is also a no-go.</p>
<p><b><a name="dynamic_proxies">Dynamic proxies</a></b><br />
Java itself uses dynamic proxies at runtime to instantiate annotations. So why not also use a Proxy to mock the annotation? See for yourself. </p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_DynamicProxy() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    CreditCardExpiryYear annotation = (CreditCardExpiryYear)
            Proxy.newProxyInstance(
                    this.getClass().getClassLoader(),
                    new Class&lt;?&gt;[] { CreditCardExpiryYear.class },
                    new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return 5;
        }
    });
    val.initialize(new CreditCardExpiryYearImpl());
    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>However inline, the implementation looks very clumsy. Unfortunately this is probably as simple as it can get, since you DO need to define the inner class.</p>
<p>And it will become even worse when there are multiple parameters on the bean, since you need to check which method is invoked. This will make the implementation even worse.</p>
<p><b><a name="mockito">Mocking using Mockito</a></b><br />
But, creating and configuring proxies, isn&#8217;t this what mocking libraries do? Exactly, let&#8217;s try.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_Mockito() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    CreditCardExpiryYear annotation = mock(CreditCardExpiryYear.class);
    when(annotation.expirationInYears()).thenReturn(5);

    val.initialize(annotation);
    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>This looks pretty nice. And it scales well with multiple attributes.</p>
<p>I only doubt it will be the nicest solution when the annotations become more complex. I really don&#8217;t like annotations that contain annotation parameters. Or even worse, arrays of annotation parameters. But reality is, they exist. And if they exist, they also need to be tested. But, OTOH, people who nest annotations probably don&#8217;t mind unreadable unit tests. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate, lazy loading and inheritance</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 12:35:15 +0000</pubDate>
		<dc:creator>gnoij</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Java API]]></category>
		<category><![CDATA[Object Relational Mapping]]></category>
		<category><![CDATA[ClassCastException]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[lazy loading]]></category>

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

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

    private Long id;

    private String name;

    public String getName() { return name; }

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

    public Long getId() { return id; }
}

public class B extends A {

    private String somethingElse;

    public String getSomethingElse() { return somethingElse; }

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

}

public class C {

    private Long id;

    private A a;

    public A getA() { return a; }

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

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

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

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

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

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

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

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

    <modelVersion>4.0.0</modelVersion>

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

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

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

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

    <modelVersion>4.0.0</modelVersion>

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

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

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

    <build>
        <finalName>test</finalName>
<plugins>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
<plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.14</version>
                <configuration>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                    <stopKey>foo</stopKey>
                    <stopPort>9999</stopPort>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>javax.servlet.jsp</groupId>
                        <artifactId>jsp-api</artifactId>
                        <version>2.2</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>javax.el</groupId>
                        <artifactId>el-api</artifactId>
                        <version>2.2.1-b01</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.glassfish.web</groupId>
                        <artifactId>el-impl</artifactId>
                        <version>2.2.1-b01</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.mortbay.jetty</groupId>
                        <artifactId>jsp-2.1</artifactId>
                        <version>6.1.14</version>
                        <scope>provided</scope>
                        <exclusions>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>jsp-api-2.1</artifactId>
                            </exclusion>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>start</artifactId>
                            </exclusion>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>jetty-annotations</artifactId>
                            </exclusion>
                        </exclusions>
                    </dependency>
                </dependencies>
</plugin>
        </plugins>
    </build>
</project>
</script></pre>
<p>As you can see, Maven takes care of the heavy lifting. You only need to specify your dependencies and they will override any dependencies with the same groupId, artifactId and type.</p>
<p>So, now I don&#8217;t have any reason not to use mvn-jetty-run to test my code!</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/02/27/using-unified-expression-language-in-maven-jetty-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
