<?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; Spring</title>
	<atom:link href="http://blog.smart-java.nl/blog/index.php/category/toolsframeworks/spring-toolsframeworks/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>Getting on the cloud!</title>
		<link>http://blog.smart-java.nl/blog/index.php/2009/06/05/getting-on-the-cloud/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2009/06/05/getting-on-the-cloud/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 19:35:51 +0000</pubDate>
		<dc:creator>Roy van Rijn</dc:creator>
				<category><![CDATA[Middleware]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[app engine]]></category>
		<category><![CDATA[cloud computing]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[wicket]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=417</guid>
		<description><![CDATA[You&#8217;ve probably heard people talking before about &#8216;cloud computing&#8217;.
But what exacly is this cloud computing you might ask? 
To figure this out I decided to create my own Google App Engine project and find out about cloud computing along the way. 
Wikipedia states that cloud computing is:
&#8220;Cloud computing is a style of computing in which [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.smart-java.nl/blog/wp-content/uploads/2009/06/appengine.gif" alt="Google App Engine" title="appengine_logo" width="142" height="109" class="size-medium wp-image-432" /></p>
<p>You&#8217;ve probably heard people talking before about &#8216;cloud computing&#8217;.<br />
But what exacly is this cloud computing you might ask? </p>
<p>To figure this out I decided to create my own Google App Engine project and find out about cloud computing along the way. </p>
<p>Wikipedia states that cloud computing is:</p>
<p><em>&#8220;<strong>Cloud computing</strong> is a style of computing in which dynamically <strong>scalable</strong> and often <strong>virtualized</strong> resources are provided <strong>as a service</strong> over the Internet. Users need not have knowledge of, expertise in, or control over the technology infrastructure in the &#8220;cloud&#8221; that supports them&#8221;</em></p>
<p>So, cloud computing doesn&#8217;t only have a vague name, the description isn&#8217;t very helpful either. But the key ingredients are &#8220;scalable&#8221; and &#8220;virtualized&#8221; and &#8220;as a service&#8221;. And you don&#8217;t have control over the infrastructure&#8230;</p>
<p>Lets take a look at Google App Engine. It was released in April 2008 as a platform for developing (Python)cloud applications. App Engine hosts these applications virtually on many machines, the programs are distributed and scaled across a vast amount of servers. And now, since the beginning of this year Google App Engine also supports Java!</p>
<p>The concept is simple, you get to build an application, preferably using Google&#8217;s App Engine-eclipse-plugin. And the JRE you build on is a slightly stripped-down version to make it usable on a cloud, like a sandbox.</p>
<p>Because you don&#8217;t know on what kind of servers your application will run on, or on how many servers, Google has decided you can&#8217;t do the following:</p>
<ul>
<li>Start threads</li>
<li>Go to the Filesystem, no I/O</li>
<li>Open sockets directly, but you can open connections through HTTP/HTTPS</li>
<li>Make calls to System (like exit();, gc(); etc)</li>
</ul>
<p>And there is more. Because of these restrictions you can&#8217;t access a database! So you can&#8217;t use something like Hibernate and some Oracle/MySQL/Postgress machine. To still be able to save/persist objects Google has teamed up with Datanucleus. Using JDO or (a stripped down version of) JPA you can persist and retrieve objects on the cloud.</p>
<p>With this in mind I started making my own application. And the frameworks I wanted to use are:</p>
<ul>
<li>Wicket (Web Framework)</li>
<li>Spring IOC</li>
<li>Spring ORM (for transaction management, using annotations)</li>
<li>JPA (instead of the default JDO)</li>
</ul>
<p>The first problems I encountered was getting Wicket to load. Because of the sandbox-restrictions there are a couple of things you can&#8217;t do. For example, Wicket can&#8217;t save temporary data to disk (what it normally does). And there are problems with Wicket being in &#8216;development-mode&#8217; where is wants to start Threads to poll for changed resources.</p>
<p>A good overview on what it takes to get Wicket working is explained here:<br />
<a href="http://www.danwalmsley.com/2009/04/08/apache-wicket-on-google-app-engine-for-java/">http://www.danwalmsley.com/2009/04/08/apache-wicket-on-google-app-engine-for-java/</a></p>
<p>Next up was installing and running Spring. This was relatively easy at first. The core Spring code ran pretty much as expected. I added the JARs to my project and added this to the web.xml:</p>
<pre>
	&lt;!-- Spring --&gt;
	&lt;context-param&gt;
		&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
		&lt;param-value&gt;classpath:applicationcontext-*.xml&lt;/param-value&gt;
	&lt;/context-param&gt;
	&lt;listener&gt;
		&lt;listener-class&gt;
			org.springframework.web.context.ContextLoaderListener
		&lt;/listener-class&gt;
	&lt;/listener&gt;
	&lt;listener&gt;
		&lt;listener-class&gt;
			org.springframework.web.context.request.RequestContextListener
		&lt;/listener-class&gt;
	&lt;/listener&gt;
</pre>
<p>As you can see, I load up multiple XML files. I decided to go with the all-out-annotations method using Spring ORM. This proved to be pretty challenging&#8230;</p>
<p>With these annotations you are able to do the following in the code:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@<span style="color: #003399;">Repository</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;loginDao&quot;</span><span style="color: #009900;">&#41;</span>
@Transactional
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> LoginDaoImpl <span style="color: #000000; font-weight: bold;">implements</span> LoginDao <span style="color: #009900;">&#123;</span>
&nbsp;
	@PersistenceContext
	<span style="color: #000000; font-weight: bold;">private</span> EntityManager entityManager<span style="color: #339933;">;</span>
	... <span style="color: #009900;">&#40;</span>and more<span style="color: #009900;">&#41;</span></pre></div></div>

<p>As you can see I&#8217;m using Spring to inject my EntityManager into the DAO. But you can&#8217;t just load the entity manager in Google App Engine, you need a specific piece of configuration. I used the following XML:</p>
<pre>
	&lt;bean id=&quot;data.emf&quot;
		class=&quot;org.springframework.orm.jpa.LocalEntityManagerFactoryBean&quot;&gt;
		&lt;property name=&quot;persistenceUnitName&quot; value=&quot;transactions-optional&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean class=&quot;org.springframework.orm.jpa.JpaTemplate&quot;&gt;
		&lt;property name=&quot;entityManagerFactory&quot; ref=&quot;data.emf&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;transactionManager&quot;
		class=&quot;org.springframework.orm.jpa.JpaTransactionManager&quot;&gt;
		&lt;property name=&quot;entityManagerFactory&quot; ref=&quot;data.emf&quot; /&gt;
	&lt;/bean&gt;
</pre>
<p>To tell Spring to scan for these annotations you need to add the following lines in your applicationcontext:</p>
<pre>
	&lt;context:annotation-config /&gt;
	&lt;context:component-scan base-package=&quot;nl.redcode.*&quot; /&gt;
</pre>
<p>And now the problems start&#8230; The first problem is that Google App Engine doesn&#8217;t support all core classes. When loading these annotations Spring will load its PersistenceAnnotationBeanPostProcessor. But it contains the following piece of code:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>EntityManagerFactory<span style="color: #009900;">&#41;</span> lookup<span style="color: #009900;">&#40;</span>jndiName, EntityManagerFactory.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">NamingException</span> ex<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalStateException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Could not obtain 
		EntityManagerFactory [&quot;</span> <span style="color: #339933;">+</span> jndiName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;]from JNDI&quot;</span>, ex<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And the Exception we get is:</p>
<pre>org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.context.annotation.internalPersistenceAnnotationProcessor':
Initialization of bean failed; nested exception is
java.lang.NoClassDefFoundError: javax/naming/NamingException
	at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
	at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
	at java.security.AccessController.doPrivileged(Native Method)
	at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
	at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
	at
...etc</pre>
<p>And when I looked at the white-list it was clear, NamingException isn&#8217;t part of the sandbox Google App Engine uses. So I started to google how to solve this. The first thing I encoutered was somebody who added the following lines to his/her applicationContext:</p>
<pre>
	&lt;bean id=&quot;org.springframework.context.annotation.internalPersistenceAnnotationProcessor&quot;
		class=&quot;java.lang.String&quot; /&gt;
</pre>
<p>This piece of code, when executed before the annotation-scan, loads a String in the Spring Container under the name &#8220;internalPersistenceAnnotationProcessor&#8221;. This causes Spring to ignore its own instantiation of the PersistenceAnnotationBeanPostProcessor and we don&#8217;t get the Exception anymore. </p>
<p>But this causes some more damage we don&#8217;t want in the application. Before my Dao&#8217;s received a valid EntityManager, but they are Null now&#8230;! </p>
<p>So I took the code of the original Spring PersistenceAnnotationBeanPostProcessor and replaced all the instances of NamingException with just Exception. This removed the dependency to NamingException. I called this new bean &#8220;AppEngineJPAPostProcessor&#8221;. This is how I configured it in the applicationContext:</p>
<pre>
	&lt;bean id=&quot;org.springframework.context.annotation.internalPersistenceAnnotationProcessor&quot;
		class=&quot;nl.redcode.springhack.AppEngineJPAPostProcessor&quot; /&gt;
</pre>
<p>The EntityManager(Factory) is now created, it gets injected into the DAO&#8217;s, they have transactions using annotations and everybody is happy!</p>
<p>When I got a little further in my project I decided to deploy my application to the cloud and test it online. Deploying your application to App Engine is very simple, just push the &#8220;Deploy&#8221; button in the Eclipse plugin and you only need to enter your credentials and a version-number of your release!</p>
<p>But then the old BeanPostProcessor bit me in the back again. On the server I got the following Exception when deploying:</p>
<pre>java.lang.SecurityException: Unable to get members for class org.springframework.jndi.JndiLocatorSupport
	at com.google.apphosting.runtime.security.shared.intercept.java.lang.Class_$10.run(Class_.java:357)
	at com.google.apphosting.runtime.security.shared.intercept.java.lang.Class_$10.run(Class_.java:347)
	at java.security.AccessController.doPrivileged(Native Method)
	at com.google.apphosting.runtime.security.shared.intercept.java.lang.Class_.getMembers(Class_.java:347)
	at com.google.apphosting.runtime.security.shared.intercept.java.lang.Class_.getDeclaredMethods(Class_.java:174)
	at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:460)
	at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:443)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata(AutowiredAnnotationBeanPostProcessor.java:299)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(AutowiredAnnotationBeanPostProcessor.java:179)</pre>
<p>It seems the runtime is a bit more strict then the development server Google App Engine uses. For some reason it doesn&#8217;t like the JndiLocatorSupport. This is excepted because Google App Engine, due to the nature of the cloud, prohibits the use of JNDI.</p>
<p>Soon I found the problem, the only reference to JndiLocatorSupport is my own BeanPostProcessor:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Rewritten for use in Google AppEngine
 *
 * @author Roy van Rijn
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AppEngineJPAPostProcessor <span style="color: #000000; font-weight: bold;">extends</span> JndiLocatorSupport <span style="color: #000000; font-weight: bold;">implements</span>
		InstantiationAwareBeanPostProcessor, BeanFactoryAware <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Map</span> persistenceUnits<span style="color: #339933;">;</span>
	...</pre></div></div>

<p>When I removed the &#8216;extends&#8217; part there were two pieces of code that stopped working, they both look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">	<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>EntityManagerFactory<span style="color: #009900;">&#41;</span> lookup<span style="color: #009900;">&#40;</span>jndiName, EntityManagerFactory.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It seems this PostProcessor always does a JNDI lookup to find the correct EntityManager! But we can&#8217;t do this if we don&#8217;t have access to the JndiLocatorSupport methods anymore. So I decided to hack a little bit in this code, my solution was to load the EntityManagerFactory and EntityManager from the Spring container:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>JpaTransactionManager<span style="color: #009900;">&#41;</span>beanFactory
		.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;transactionManager&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		.<span style="color: #006633;">getEntityManagerFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">/*	return (EntityManagerFactory) lookup(jndiName,
		EntityManagerFactory.class);*/</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> ex<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
...</pre></div></div>

<p>This solved all the problems and with the changes to the BeanPostProcessor I&#8217;m now able to use all the Spring annotations, for persistency and transactions, in Google AppEngine.</p>
<p>I&#8217;m now still in the middle of developing my application on Google App Engine, but it seems that Google App Engine works like a charm. The problem is, most frameworks can&#8217;t really cope with the sandbox out-of-the-box. But with (some) minor patches and tweaking most frameworks will run using Google App Engine. The only major problem I&#8217;m having (which can&#8217;t be solved) is Datanucleus. I chose to use JPA because it is much richer and has more features then JDO, but Datanucleus hasn&#8217;t implemented much of these features yet.</p>
<p>For example, I had the following annotation on a field: <em>@Column(unique=true)</em><br />
Datanucleus threw &#8220;<em>java.lang.UnsupportedOperationException: No support for uniqueness<br />
constraints</em>&#8220;.</p>
<p>Also, I created a query with this: &#8220;<em>username = :username OR emailAddress = :emailAddress</em>&#8221;<br />
But Datanucleus doesn&#8217;t support the operator &#8220;OR&#8221;.</p>
<p>Other things DataNucleus can&#8217;t currently do:</p>
<ul>
<li>Many-to-many relationships</li>
<li>Joins in a query (WHAT??)</li>
<li>Aggregation queries (group by, having, sum, avg, max, min)</li>
<li>Polymorphic queries. You cannot perform a query of a class to get instances of a subclass. Each class is represented by a separate entity kind in the datastore.</li>
</ul>
<p>So, we&#8217;ve seen what a cloud is, what Google App Engine is, and I explained some tweaks/patches needed to get Wicket and Spring working.</p>
<p>Why use Google App Engine? It is free (up to some CPU/mail/data limits) and your project runs on a cloud, and thus is very scalable. You don&#8217;t have to worry about the environment or server. Your application will scale when its needed and everything is pre-installed and ready to run.<br />
But be prepared for difficult classloading issues and missing classes. You just can&#8217;t expect all frameworks to be working out-of-the-box with the sandbox-limitations. Also don&#8217;t expect much support with persisting, the JPA-support is very minimal and won&#8217;t let you do much more then persisting and retrieving single objects. </p>
<p>Enough blogging, now its time for me again to tinker on my application, maybe I&#8217;ll tell about it here in the future!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2009/06/05/getting-on-the-cloud/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Cyclische dependencies @ runtime</title>
		<link>http://blog.smart-java.nl/blog/index.php/2009/04/16/cyclische-dependencies-runtime/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2009/04/16/cyclische-dependencies-runtime/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 11:01:40 +0000</pubDate>
		<dc:creator>Frank Verbruggen</dc:creator>
				<category><![CDATA[Architectuur]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=353</guid>
		<description><![CDATA[In een gelaagd project zijn er meestal aparte lagen gedefinieerd voor services, domein logica en data access. Stel nu dat er een noodzaak is om vanuit een lager gelegen laag gebruik te maken van functionaliteit die thuis hoort in een hoger gelegen laag. Bijvoorbeeld omdat er in de domein objecten een noodzaak is om gebruik [...]]]></description>
			<content:encoded><![CDATA[<p>In een gelaagd project zijn er meestal aparte lagen gedefinieerd voor services, domein logica en data access. Stel nu dat er een noodzaak is om vanuit een lager gelegen laag gebruik te maken van functionaliteit die thuis hoort in een hoger gelegen laag. Bijvoorbeeld omdat er in de domein objecten een noodzaak is om gebruik te maken van een service. Hoe zorg je er dan voor dat je nette object georienteerde code houdt, zonder dat je compile time dependencies krijgt tussen je projecten / lagen? Het hier gepresenteerde design pattern is een elegante object georienteerde oplossing voor het bovenstaande probleem.</p>
<p>Gegeven een DomeinObject als object uit de lagere laag, en een ServiceImplementation als object uit de hogere laag. De serviceImplementation heeft een een interface methode &#8217;someMethod()&#8217; uit de ServiceInterface die benodigd is om de methode &#8216;businessMethod()&#8217; uit het DomeinObject te implementeren (zie figuur 1, originele klasse diagram).</p>
<p>N.B. Het design pattern is uitgewerkt met domein objecten en service implementaties, maar dat is slechts een invulling.</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
<img src="http://blog.smart-java.nl/blog/wp-content/uploads/2009/04/originele-situatie.jpg" alt="" /><br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Figuur 1, originele klasse diagram<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>Los dit als volgt op. Trek de ServiceInterface uit de hogere laag, en zet deze in de lagere laag. Maak een RequiredInterfaceFactory die een instantie van de ServiceInterface kan bevatten. Initialiseer bij het opstarten van je applicatie vanuit de bovenste laag de RequiredInterfaceFactory met de ServiceImplementation (dit kan bijvoorbeeld goed met de Spring configuratie uit Listing 1, Spring configuratie). En implementeer de businessMethod door de aanroep naar de ServiceImplementation als volgt te abstraheren:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">RequiredInterfaceFactory.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getServiceInterface</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">someMethod</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Het klasse diagram ziet er dan uit zoals weergegeven in Figuur 2, klasse diagram.</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">&nbsp;</pre></div></div>

<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Listing 1, Spring configuratie<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
<img src="http://blog.smart-java.nl/blog/wp-content/uploads/2009/04/design-pattern.jpg" alt="" /><br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Figuur 2, klasse diagram<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p><strong>Voordelen en nadelen</strong></p>
<p>Het gebruik van dit design pattern biedt de volgende voordelen:</p>
<ul>
<li>Compile time dependencies zijn niet nodig</li>
<li>At runtime kunnen interface methoden van bovenliggende klassen toch gebruikt worden</li>
<li>Ieder object kan gebruik maken van de interface, ongeacht in welk package het zit, dus het ophalen van de interface kan in de code altijd op dezelfde manier gebeuren</li>
</ul>
<p>Het gebruik van dit design pattern biedt de volgende nadelen:</p>
<ul>
<li>Je moet de RequiredInterfaceFactory injecteren met de ServiceImplementation voordat de rest van de applicatie aangesproken wordt</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2009/04/16/cyclische-dependencies-runtime/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Flat file parsing met Spring Batch</title>
		<link>http://blog.smart-java.nl/blog/index.php/2008/11/07/flat-file-parsing-met-spring-batch/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2008/11/07/flat-file-parsing-met-spring-batch/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 23:17:05 +0000</pubDate>
		<dc:creator>Richard Kettelerij</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Architectuur]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Tools/Frameworks]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=240</guid>
		<description><![CDATA[Legacy systemen gebruiken vaak flat files voor gegevens uitwisseling. Bij integratie met dergelijk systemen moeten deze files worden geparst. In zo’n geval kan je natuurlijk zelf met de Java Scanner of StingTokenizer aan de slag gaan maar het is waarschijnlijk verstandiger om een bestaand framework te gebruiken. Spring Batch biedt hiervoor een elegante oplossing.
Mocht je [...]]]></description>
			<content:encoded><![CDATA[<p>Legacy systemen gebruiken vaak flat files voor gegevens uitwisseling. Bij integratie met dergelijk systemen moeten deze files worden geparst. In zo’n geval kan je natuurlijk zelf met de Java <tt>Scanner</tt> of <tt>StingTokenizer</tt> aan de slag gaan maar het is waarschijnlijk verstandiger om een bestaand framework te gebruiken. Spring Batch biedt hiervoor een elegante oplossing.</p>
<p>Mocht je overigens meer willen weten over Spring Batch en batch processing in het algemeen? Schrijf je dan in voor <a href="http://joost.ordina.nl/Default.asp/id,410/cursusid,828/index.html">Special Meeting op 18 november</a> a.s.</p>
<p><strong>Bestandsdefinitie</strong><br />
Als voorbeeld gebruiken we een fixed-width file afkomstig uit een legacy systeem van een fictieve online videotheek. Zoals gebruikelijk bij deze vorm van gegevensuitwisseling bestaat het bestand uit verschillende soorten records: Een header record met metadata als een bedrijfsnaam en batchnummer, een footer record met een controlegetal en uiteraard een aantal records met de daadwerkelijke informatie; in dit geval film titels.<br />
<code><br />
H   OrdinaVideoStore.nl    12<br />
M   Shrek II<br />
M   Lord of War<br />
M   Godfather, The<br />
M   Kungfu Panda<br />
F   0000000000000000006<br />
</code><br />
<strong>Tokenizing</strong><br />
Om bovenstaand bestand te kunnen parsen dient allereerst onderscheid te worden gemaakt tussen de verschillende soorten records. Aangezien dit uit het eerste karakter van elk record kan worden afgeleid gebruiken we de  <tt>PrefixMatchingCompositeLineTokenizer</tt>.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;movieFileLayout&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.batch.item.file.transform.PrefixMatchingCompositeLineTokenizer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;tokenizers&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;map<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;entry</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;H&quot;</span> <span style="color: #000066;">value-ref</span>=<span style="color: #ff0000;">&quot;movieHeaderRecordLayout&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;entry</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;M&quot;</span> <span style="color: #000066;">value-ref</span>=<span style="color: #ff0000;">&quot;movieRecordLayout&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;entry</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;F&quot;</span> <span style="color: #000066;">value-ref</span>=<span style="color: #ff0000;">&quot;movieFooterRecordLayout&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/map<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;movieHeaderRecordLayout&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.batch.item.file.transform.FixedLengthTokenizer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;names&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;recordtype, videostore, batchid&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;columns&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;1,5-25,28-30&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Deze tokenizer geeft records op basis van het type door aan een nieuwe <tt>LineTokenizer</tt>. Zoals je in bovenstande configuratie kunt zien mapped deze tokenizer elke fixed-width kolom naar een bijbehorende kolomnaam. Hier zie je duidelijk de kracht van de configuratie mogelijkheden in Spring. Je geeft gewoon in de application context de ranges van gerelateerde kolommen op en Spring Batch doet de rest. Om deze magic mogelijk te maken heeft Spring wel wat hulp nodig in de vorm van een <tt>CustomEditorConfigurer</tt>. Deze vertaald de range definities (5-3, etc) naar betekenisvolle <tt>Range</tt> objecten.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;customEditorConfigurer&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.beans.factory.config.CustomEditorConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;customEditors&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;map<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;entry</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;org.springframework.batch.item.file.transform.Range[]&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.batch.item.file.transform.RangeArrayPropertyEditor&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/entry<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/map<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><strong>Mapping naar domein objecten</strong><br />
Vervolgens is het de bedoeling om de kolom/veld definities naar domein objecten te vertalen. Hiervoor heeft Spring Batch de <tt>FieldSetMapper</tt> interface geïntroduceerd. Hoewel we hiermee zelf de mapping van velden naar domein objecten kunnen verzorgen is het mogelijk om dit aan Spring Batch over te laten middels een <tt>FieldSetMapper</tt> gebaseerd op Spring’s <tt>BeanWrapper</tt>. Er moet echter ook onderscheid worden gemaakt tussen de verschillende record soorten. Hiervoor is &#8211; in tegenstelling tot de prefix-enabled tokenizer &#8211; geen standaard fieldset mapper aanwezig. Daarom schijven we zelf een eenvoudige mapper:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PrefixAwareMovieFieldSetMapper <span style="color: #000000; font-weight: bold;">implements</span> FieldSetMapper <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">private</span> FieldSetMapper headerFieldSetMapper<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> FieldSetMapper movieFieldSetMapper<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> FieldSetMapper footerFieldSetMapper<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> mapLine<span style="color: #009900;">&#40;</span>FieldSet fieldSet<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> recordType <span style="color: #339933;">=</span> fieldSet.<span style="color: #006633;">readString</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;recordtype&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>recordType.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;H&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> headerFieldSetMapper.<span style="color: #006633;">mapLine</span><span style="color: #009900;">&#40;</span>fieldSet<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>recordType.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;M&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> movieFieldSetMapper.<span style="color: #006633;">mapLine</span><span style="color: #009900;">&#40;</span>fieldSet<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>recordType.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;F&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> footerFieldSetMapper.<span style="color: #006633;">mapLine</span><span style="color: #009900;">&#40;</span>fieldSet<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalStateException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;onbekend record type&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">// setters</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Wanneer we deze <tt>FieldSetMapper</tt> configureren is de mapping van tokens naar domein objecten compleet.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;movieFileFieldSetMapper&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;nl.ordina.batch.PrefixAwareMovieFieldSetMapper&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;headerFieldSetMapper&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;movieHeaderFieldSetMapper&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;movieFieldSetMapper&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;movieFieldSetMapper&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;footerFieldSetMapper&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;movieFooterFieldSetMapper&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;movieHeaderFieldSetMapper&quot;</span> </span>
<span style="color: #009900;">   <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;prototypeBeanName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;headerRecord&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;headerRecord&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;nl.ordina.batch.model.MovieHeaderRecord&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">scope</span>=<span style="color: #ff0000;">&quot;prototype&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p><strong>Parsen</strong><br />
Nu we hebben gedefinieerd welke karakters naar welke velden mappen, en welke velden naar welk domein object mapped wordt het tijd om bestanden te parsen. Hiervoor gebruiken we een <tt>FlatFileItemReader</tt> die we injecteren met de eerder gecreërde tokenizer en fieldset mapper. Geconfigureerd binnen een batch job ziet dit er als volgt uit. Wanneer deze job wordt uitgevoerd ontvangt de &#8220;DummyWriter&#8221; voor elke record in het bronbestand een overeenkomstig domein object.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;videotheekJob&quot;</span> <span style="color: #000066;">parent</span>=<span style="color: #ff0000;">&quot;simpleJob&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;steps&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;printRecordStep&quot;</span> <span style="color: #000066;">parent</span>=<span style="color: #ff0000;">&quot;simpleStep&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;itemReader&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.batch.item.file.FlatFileItemReader&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;resource&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;file:///videotheek/films.txt&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;lineTokenizer&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;movieFileLayout&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;fieldSetMapper&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;movieFileFieldSetMapper&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;itemWriter&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;dummyWriter&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Zoals je wellicht opvalt wijst de <tt>FlatFileItemReader</tt> naar een hardcoded filepath. Momenteel biedt Spring Batch nog geen mogelijkheid om dit voor meerdere bestanden configurabel te maken. Dit heb ik inmiddels gemeld via een <a href="http://jira.springframework.org/browse/BATCH-905">JIRA ticket</a> en een oplossing bijgevoegd in de vorm van een <tt>DynamicMultiResourceItemReader</tt>. </p>
<p>Tot slot, Spring Batch biedt m.i. behoorlijke ondersteuning om diverse soorten bestanden te parsen. Dit is met name handig in applicaties die reeds gebruik maken van het Spring Framework. Maar Spring Batch bevat méér en is zeker het overwegen waard buiten pure Spring applicaties.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2008/11/07/flat-file-parsing-met-spring-batch/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Spring MVC 2.5: BindingResult probleempje</title>
		<link>http://blog.smart-java.nl/blog/index.php/2008/10/09/spring-mvc-25-bindingresult-probleempje/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2008/10/09/spring-mvc-25-bindingresult-probleempje/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 09:28:52 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[BindingResult]]></category>
		<category><![CDATA[ModelAttribute]]></category>
		<category><![CDATA[Request attribute]]></category>
		<category><![CDATA[Spring MVC 2.5]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=210</guid>
		<description><![CDATA[Zojuist liep ik tegen een vervelend probleempje aan. Ik was bezig met het bouwen van een weblog met Spring 2.5 en alles ging goed, tot het laatste schermpje. Namelijk een klein schermpje om je password te wijzigen.
Dit is de controller:

@Controller
@SessionAttributes&#40;&#34;changePassword&#34;&#41;
public class ProfileController extends AbstractAdminController &#123;
&#160;
    public static final class ChangePasswordBean &#123;
  [...]]]></description>
			<content:encoded><![CDATA[<p>Zojuist liep ik tegen een vervelend probleempje aan. Ik was bezig met het bouwen van een weblog met Spring 2.5 en alles ging goed, tot het laatste schermpje. Namelijk een klein schermpje om je password te wijzigen.</p>
<p>Dit is de controller:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@Controller
@SessionAttributes<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;changePassword&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ProfileController <span style="color: #000000; font-weight: bold;">extends</span> AbstractAdminController <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">class</span> ChangePasswordBean <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">String</span> password1<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">String</span> password2<span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// Getters and setters</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
    @Autowired <span style="color: #000000; font-weight: bold;">private</span> BlogService blogService<span style="color: #339933;">;</span>
&nbsp;
    @RequestMapping<span style="color: #009900;">&#40;</span>value=<span style="color: #0000ff;">&quot;/admin/users/profile&quot;</span>, method=RequestMethod.<span style="color: #006633;">GET</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> ModelAndView setupForm<span style="color: #009900;">&#40;</span>ModelMap model, HttpSession session<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        model.<span style="color: #006633;">addAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;changePassword&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> ChangePasswordBean<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> ModelAndView<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;admin/users/profile&quot;</span>, model<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @RequestMapping<span style="color: #009900;">&#40;</span>value=<span style="color: #0000ff;">&quot;/admin/users/profile&quot;</span>, method=RequestMethod.<span style="color: #006633;">POST</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">String</span> processSubmit<span style="color: #009900;">&#40;</span>
            @ModelAttribute ChangePasswordBean changePassword,
            BindingResult result, HttpSession session, SessionStatus status<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">new</span> PasswordValidator<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">validate</span><span style="color: #009900;">&#40;</span>changePassword, result<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000;  font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>result.<span style="color: #006633;">hasErrors</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;admin/users/profile&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000;  font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">// Call to service layer</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;redirect:/admin/home.html&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Dit is de JSP met het form:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">  ...
  <span style="color: #339933;">&lt;</span>form:form modelAttribute=<span style="color: #0000ff;">&quot;changePassword&quot;</span><span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>form:errors /<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>table <span style="color: #000000; font-weight: bold;">class</span>=<span style="color: #0000ff;">&quot;form&quot;</span><span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>tr<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;&lt;</span>form:label <span style="color: #000000;  font-weight: bold;">for</span>=<span style="color: #0000ff;">&quot;password1&quot;</span> path=<span style="color: #0000ff;">&quot;password1&quot;</span><span style="color: #339933;">&gt;</span>Password<span style="color: #339933;">&lt;</span>/form:label<span style="color: #339933;">&gt;&lt;</span>/td<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;&lt;</span>form:password id=<span style="color: #0000ff;">&quot;password1&quot;</span> maxlength=<span style="color: #0000ff;">&quot;20&quot;</span> path=<span style="color: #0000ff;">&quot;password1&quot;</span> /<span style="color: #339933;">&gt;&lt;</span>/td<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;&lt;</span>form:errors path=<span style="color: #0000ff;">&quot;password1&quot;</span> /<span style="color: #339933;">&gt;&lt;</span>/td<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>/tr<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>tr<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;&lt;</span>form:label <span style="color: #000000;  font-weight: bold;">for</span>=<span style="color: #0000ff;">&quot;password2&quot;</span> path=<span style="color: #0000ff;">&quot;password2&quot;</span><span style="color: #339933;">&gt;</span>Retype password<span style="color: #339933;">&lt;</span>/form:label<span style="color: #339933;">&gt;&lt;</span>/td<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;&lt;</span>form:password id=<span style="color: #0000ff;">&quot;password2&quot;</span> maxlength=<span style="color: #0000ff;">&quot;20&quot;</span> path=<span style="color: #0000ff;">&quot;password2&quot;</span> /<span style="color: #339933;">&gt;&lt;</span>/td<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;&lt;</span>form:errors path=<span style="color: #0000ff;">&quot;password2&quot;</span> /<span style="color: #339933;">&gt;&lt;</span>/td<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>/tr<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>tr<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>td colspan=<span style="color: #0000ff;">&quot;3&quot;</span><span style="color: #339933;">&gt;</span>
          <span style="color: #339933;">&lt;</span>input type=<span style="color: #0000ff;">&quot;reset&quot;</span> value=<span style="color: #0000ff;">&quot;Cancel&quot;</span> /<span style="color: #339933;">&gt;</span> |
          <span style="color: #339933;">&lt;</span>input type=<span style="color: #0000ff;">&quot;submit&quot;</span> value=<span style="color: #0000ff;">&quot;Save&quot;</span> /<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>/td<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>/tr<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>/table<span style="color: #339933;">&gt;</span>
  <span style="color: #339933;">&lt;</span>/form:form<span style="color: #339933;">&gt;</span>
  ...</pre></div></div>

<p>Deze opzet werkte bij alle schermen, maar om de een of andere reden niet voor dit &#8220;simpele&#8221; schermpje. Het form openen ging goed, submitten ging ook goed, zolang er geen validatiefouten waren, maar bij validatiefouten kreeg ik de volgende melding:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">java.<span style="color: #006633;">lang</span>.<span style="color: #003399;">IllegalStateException</span><span style="color: #339933;">:</span> Neither BindingResult nor plain target object <span style="color: #000000; font-weight: bold;">for</span> bean name <span style="color: #0000ff;">'changePassword'</span> available as request attribute
    at org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">web</span>.<span style="color: #006633;">servlet</span>.<span style="color: #006633;">support</span>.<span style="color: #006633;">BindStatus</span>.<span style="color: #339933;">&lt;</span>init<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>BindStatus.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">141</span><span style="color: #009900;">&#41;</span>
    at org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">web</span>.<span style="color: #006633;">servlet</span>.<span style="color: #006633;">tags</span>.<span style="color: #006633;">form</span>.<span style="color: #006633;">AbstractDataBoundFormElementTag</span>.<span style="color: #006633;">getBindStatus</span><span style="color: #009900;">&#40;</span>AbstractDataBoundFormElementTag.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">172</span><span style="color: #009900;">&#41;</span>
    at org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">web</span>.<span style="color: #006633;">servlet</span>.<span style="color: #006633;">tags</span>.<span style="color: #006633;">form</span>.<span style="color: #006633;">AbstractHtmlElementTag</span>.<span style="color: #006633;">resolveCssClass</span><span style="color: #009900;">&#40;</span>AbstractHtmlElementTag.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">412</span><span style="color: #009900;">&#41;</span>
    at org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">web</span>.<span style="color: #006633;">servlet</span>.<span style="color: #006633;">tags</span>.<span style="color: #006633;">form</span>.<span style="color: #006633;">AbstractHtmlElementTag</span>.<span style="color: #006633;">writeOptionalAttributes</span><span style="color: #009900;">&#40;</span>AbstractHtmlElementTag.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">388</span><span style="color: #009900;">&#41;</span>
    ...</pre></div></div>

<p>Toch creemd. Ik had de JSP en de controller gewoon gekopieerd van een <strong>wel</strong> werkend scherm, maar om de een of andere reden werkte het toch niet. Ligt het aan de inner class? Nee, vast niet. Hoewel, het is wel een final class. Misschien wil Spring wel een proxy aanmaken en mag de class niet final zijn ofzo. Hup, final eraf. Scheisse, nog steeds hetzelfde probleem. Wat kan het dan zijn?</p>
<h3>Oplossing</h3>
<p>Toen viel mijn oog op de processSubmit methode in de controller. Daar week de naam van de parameter af van de klassenaam. Class name: ChangePasswordBean, argument name: changePassword.</p>
<p>Hmm, dat zal wel het probleem zijn, want bij alle andere schermen waren deze gelijk. Toevallig wist ik dat in de bytecode van de klasse geen parameternamen staan en dus ook niet @runtime uit te lezen zijn. De mannen van Spring zijn waarschijnlijk tegen dezelfde beperking aan gelopen en hebben hier omheen gewerkt door standaard de type name als request attribute name te gebruiken, in plaats van de parameter naam (wat logischer is, maar dus niet kan in Java).</p>
<p>Dit was de oplossing:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">    <span style="color: #666666; font-style: italic;">// Before fix (this didn't work)</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">String</span> processSubmit<span style="color: #009900;">&#40;</span>
			@ModelAttribute ChangePasswordBean changePassword,
			...<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// After fix (working solution)</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">String</span> processSubmit<span style="color: #009900;">&#40;</span>
			@ModelAttribute<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;changePassword&quot;</span><span style="color: #009900;">&#41;</span> ChangePasswordBean changePassword,
			...<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span></pre></div></div>

<p>Dusss, gebruik in je JSP&#8217;s de klassenaam of geef expliciet de naam op in de @ModelAttribute annotation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2008/10/09/spring-mvc-25-bindingresult-probleempje/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
