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

<channel>
	<title>blog.smart-java.nl &#187; Java EE</title>
	<atom:link href="http://blog.smart-java.nl/blog/index.php/category/java-ee/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>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>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>REST made easy with Java EE 6 and JAX-RS 1.1</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 06:34:25 +0000</pubDate>
		<dc:creator>Stephan Oudmaijer</dc:creator>
				<category><![CDATA[Java EE]]></category>

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

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

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

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

    @Inject
    private ProductService productService;

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

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

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Product {
...
}

package com.oudmaijer.webshop.domain;

import javax.xml.bind.annotation.XmlRootElement;

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

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

</web-app>
</script></pre>
<p><b>Conclusion</b></p>
<p>When building RESTfull services on an JEE6 enabled application server, JAX-RS really makes things easy. You will have to decide for your specific case if you want to use Spring or JAX-RS.</p>
<p><em><a href="http://www.oudmaijer.com/blog/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/">Orginal article posted here.</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JSF 2.0: The most simple CDI integration use cases</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/31/jsf-2-0-the-most-simple-cdi-integration-use-cases/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/31/jsf-2-0-the-most-simple-cdi-integration-use-cases/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 19:45:47 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[JSF 2.0]]></category>
		<category><![CDATA[Producer methods]]></category>

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

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

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

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

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

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

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

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