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

<channel>
	<title>Struberg&#039;s Blog</title>
	<atom:link href="http://struberg.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://struberg.wordpress.com</link>
	<description>Yet another blog site?</description>
	<lastBuildDate>Sun, 08 Jan 2012 15:51:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='struberg.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Struberg&#039;s Blog</title>
		<link>http://struberg.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://struberg.wordpress.com/osd.xml" title="Struberg&#039;s Blog" />
	<atom:link rel='hub' href='http://struberg.wordpress.com/?pushpress=hub'/>
		<item>
		<title>JPA Enhancement done right</title>
		<link>http://struberg.wordpress.com/2012/01/08/jpa-enhancement-done-right/</link>
		<comments>http://struberg.wordpress.com/2012/01/08/jpa-enhancement-done-right/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 02:17:41 +0000</pubDate>
		<dc:creator>struberg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://struberg.wordpress.com/?p=37</guid>
		<description><![CDATA[JPA Enhancement done right When it comes to handling databases in a highlevel language there are basically 2 different approaches: a.) Systems which give you access to all the gory details and therefor have a pretty high entry barrier. b.) Systems which are perfectly easy to use for samples and simple apps &#8211; but you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=37&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>JPA Enhancement done right</h1>
<p>When it comes to handling databases in a highlevel language there are basically 2 different approaches:</p>
<p>a.) Systems which give you access to all the gory details and therefor have a pretty high entry barrier.<br />
b.) Systems which are perfectly easy to use for samples and simple apps &#8211; but you need all the (well hidden) gory details if you use that stuff in real world projects.</p>
<p>Without a doubt JPA is more the category b.) type of project.</p>
<h2>Using JPA</h2>
<p>If you look at a classical JPA entity, you will find something similar to our following example:</p>
<pre>
import javax.persistence.*;

@Entity
public class Customer {
  @Id
  @GeneratedValue
  private Long id;

  @Column(length = 50)
  private String firstName;

  public Long getId() {
    return id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
}
</pre>
<p>Usually the entities get created with the &#8216;new&#8217; keyword and then stored by calling EntityManager#persist()</p>
<pre>
Customer c = new Customer();
c.setFirstName("John");
entityManager.persist(c);
</pre>
<p>Looks easy, isn&#8217;t?</p>
<h2>Enhancement</h2>
<p>A lot of the &#8216;easyness&#8217; of JPA actually comes by the feature of &#8216;enhancing&#8217; classes which are annotated with @Entity. And this enhancement step is usually well hidden deep inside the code.</p>
<p>So let&#8217;s first look what this &#8216;enhancement&#8217; does for you!</p>
<p>Whenever you touch a JPA entity, it will track the following information for each and every non-transient attribute of the entity:</p>
<p>* <b>_dirty</b>: if you change firstName from &#8216;John&#8217; to &#8216;Barry&#8217;, this field becomes &#8216;dirty&#8217;. JPA uses this information to decide which fields/entities needs to get written to the database.</p>
<p>* <b>_loaded</b>: JPA entities might contain fields which have FetchType.LAZY. They will only get loaded from the database once they are accessed the first time. This is pretty neat if you have a fat @ElementCollection which takes some time to load. Some older JPA impls did rely on if(field == null) but what about c.setFirstName(null); to clear out this info in the database? How to distinguish between a field which didn&#8217;t yet get laoded (and is null) from a field which got loaded and afterwards set to null?<br />
_loaded will be used to track this info.</p>
<p>But where is this _dirty and _loaded info in my entities? Well, this is exactly what the &#8216;enhancement&#8217; step is doing. It adds this information to the entity class file for you!</p>
<p>Basically the setFirstName in the &#8216;enhanced&#8217; class will finally look somehow like the following (completely transparent for the user!):</p>
<pre>
public void setFirstName(String firstName) {
  if (safeEquals(this.firstName, firstName) {
    return;
  }

  //EntityManager must not get accessed in different threads
  assertEntityManagerLocking();

  setDirty(FIRSTNAME_FIELD);
  this.firstName = firstName;
}
</pre>
<p>Technically there are 3 different ways to achieve this</p>
<h3>1.) Using Proxies/Subclassing at runtime</h3>
<p>A Proxy is basically a dynamically created Subclass. This is the default mode for Hibernate and has quite a few drawbacks.</p>
<p><strong>1.a.)</strong> you can only proxy methods. It&#8217;s not possible to intercept the field access inside the class level. This makes it much harder to correctly write EntityListeners and other methods which juggle around with fields.</p>
<p><strong>1.b.)</strong> Only property access for classes loaded via a query or EntityManager#find() can get tracked. It&#8217;s not possible to do the same for Entities just created via &#8216;new&#8217; because there is no proxy in this case.</p>
<p><strong>1.c.)</strong> Lazy loading is not possible in this case. All fields (including expensive @ElementCollection reads) will be performed eagerly.</p>
<h3>2.) Using Compilation Enhancement</h3>
<p>You can use either ant or maven to &#8216;enhance&#8217; the class files of your entities to contain all the additional code which is needed to work properly. This is the prefered way as it provides the full set of features and also the best performance at runtime. Actually this option comes in 2 different flavours:</p>
<p><strong>2.a.)</strong> Build Time Enhancement: The class file get&#8217;s modified even before it will get packaged into the JAR. I will come back to this again a bit later and explain it in detail.</p>
<p><strong>2.b.)</strong> Deploy Time Enhancement: The class file get&#8217;s enhanced by the &#8216;deployer&#8217; in a JavaEE container. If you upload your WAR/EAR to your server, it will get unpackaged, all classes with an @Entity will automatically get enhanced immediately afterwards by the container.</p>
<h3>3.) Runtime Enhancement (via ClassTransformer)</h3>
<p>At the first glance the JavaAgent [1] looked like a smart way to perform the enhancement at runtime, but it turned out that there are fundamental problems with this approach. Again there are 2 different flavours for this way of enhancement:<br />
<strong>3.a.)</strong> using the Java5 -javaagent option.<br />
<strong>3.b.)</strong> using the Java6 Instrumentation#retransformClasses. This allows to drop out loaded classes and replace them with their &#8216;transformed&#8217; version.</p>
<p>The major problem with both of the aforementioned mechanism is that they use the SystemClassLoader to register the ClassTransformer and subsequently also to load the classes needed to perform the transformation!</p>
<p>This has the bad side effect that the SystemClassloader gets polluted with some impl classes of your persistence provider. But not all, and if the transformation is finished, the jar containing the Transformer will get detached from the JVM again. This will leave you with 30% of Hibernate/OpenJPA/EclipseLink lying around in your SystemClassPath and the rest is not available.</p>
<p>Not that worse, one might say, because all those classes are still available in your web application. Too bad that a nice little security mechanism kicks in and destroys all our dreams. The Servlet specification defines that any container must prevent redefining &#8216;system classes&#8217; &#8211; that is all classes which get loaded via the SystemClassLoader. Thus in any spec conform servlet container (e.g. tomcat [2]) you are now bound to the few classes of your jpa provider which are available in your SystemClassLoader. This will result in tons of NoClassDefFound errors and many tears&#8230;</p>
<h2>The Winner: Build Time Enhancement</h2>
<p>Technically only Built Time Enhancement and Deploy Time Enhancement do work sufficiently at all. The reason I don&#8217;t use Deploy Time Enhancement is that you are not able to test and debug locally what you have running in your server. All the unit tests are not worth much if you don&#8217;t run the code which gets executed in production. Thus Build Time Enhancement is the clear winner to me.</p>
<h3>The openjpa-maven-plugin</h3>
<p>Quite some time ago we wrote the openjpa-maven-plugin [3] which allows to do all the enhancement steps while building your project with maven. This plugin got moved over to the OpenJPA project itself and will first be available with the upcoming OpenJPA-2.2.0 version (expect this to be out this month). A similar tool is available as ant-task. There is also a maven plugin for doing the same with hibernate [4].</p>
<h3>IDE pitfalls</h3>
<p>Most IDEs nowadays compile the classes on the fly. If you don&#8217;t have a special IDE plugin installed which &#8216;fixes&#8217; the entity classes afterwards, you might get errors reporting that you &#8216;try to run unenhanced classes&#8217;. Usually this happens only the first time or if you change an Entity class.</p>
<p>In this case simply enhance them again on the commandline.<br />
$&gt; mvn clean process-classes</p>
<p>Afterwards you can work in your IDE without any further problems.</p>
<p>Glossar:</p>
<p>[1] javaagent: http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html</p>
<p>[2] tomcat WebAppClassLoader: http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/loader/WebappClassLoader.java<br />
see public synchronized Class loadClass(String name, boolean resolve)</p>
<pre>
// (0.2) Try loading the class with the system class loader, to prevent
// the webapp from overriding J2SE classes
</pre>
<p>[3] http://mojo.codehaus.org/openjpa-maven-plugin/usage.html</p>
<p>[4] http://mojo.codehaus.org/maven-hibernate3/hibernate3-maven-plugin/</p>
<p>OpenJPA: http://openjpa.apache.org/builds/latest/docs/manual/manual.html#ref_guide_pc_enhance</p>
<p>Hibernate: http://docs.jboss.org/hibernate/core/3.3/reference/en/htm/performance.html#performance-fetching-lazyproperties</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/struberg.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/struberg.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/struberg.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/struberg.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/struberg.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/struberg.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/struberg.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/struberg.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/struberg.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/struberg.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/struberg.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/struberg.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/struberg.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/struberg.wordpress.com/37/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=37&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://struberg.wordpress.com/2012/01/08/jpa-enhancement-done-right/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/30fae5bce90608fb3df5c018c586aea6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">struberg</media:title>
		</media:content>
	</item>
		<item>
		<title>solving the browser Tab problem</title>
		<link>http://struberg.wordpress.com/2011/11/13/solving-the-browser-tab-problem/</link>
		<comments>http://struberg.wordpress.com/2011/11/13/solving-the-browser-tab-problem/#comments</comments>
		<pubDate>Sat, 12 Nov 2011 23:53:27 +0000</pubDate>
		<dc:creator>struberg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://struberg.wordpress.com/?p=30</guid>
		<description><![CDATA[Web Browser tabs and windows have been an issue for a long time now. They cause broken ViewMaps (used in @ViewScoped), FlashScope and lots other issues [1]. There is also a very ugly negative effect with using multiple browser tabs when using server side state saving in JSF: the last viewStates of a client is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=30&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Web Browser tabs and windows have been an issue for a long time now. They cause broken ViewMaps (used in @ViewScoped), FlashScope and lots other issues [1].</p>
<p>There is also a very ugly negative effect with using multiple browser tabs when using server side state saving in JSF: the last viewStates of a client is only stored per session and not per browser tab. Thus if a person clicks long enough in 1 browser tab (the default value is 20 for both Mojarra and MyFaces) then all your other open tabs will loose the view state. And this will cause a ViewExpiredException once you click around in one of those other browser tabs. This can only be solved if JSF natively supports multiple browser tabs and stores the view states per browser tab.</p>
<p>The problem is that providing a really working windowId handling is not exactly easy (as outlined in [1]).</p>
<h3>Apache MyFaces CODI ClientSideWindowHandler</h3>
<p>A solution which works perfectly fine on a technical level has been implemented by Jakob, Gerhard and me in Apache MyFaces CODI [2]. But it had the bad user effect that rendering the intermediate page (which checks for a valid site) and only then requests the real page did cause some &#8216;flickering&#8217;. It seems we have solved this problem now!</p>
<p>While I explained Dan Allen how we do the windowId handling in CODI currently, he came up with the idea of &#8216;taking a screenshot somehow and show it on the intermediate page&#8217;. One idea hit the other and today I tried to use html5 localStorage to store the head and body elements and dynamically apply them on the indermediate windowhandler.html page. Voila, works perfect so far. Of course, we need to test this with complex pages and pages which heavily uses javascript, but so far it works fine.</p>
<h3>How it works</h3>
<p>The site which contains a GET link needs to use some JavaScript which changes all &lt;a href../&gt; and add/delegate a<br />
<code>onclick="storeWindowTree(); return true;"</code></p>
<p>The storeWindowTree is pretty easy:<br />
<code><br />
&lt;script type="text/javascript"&gt;<br />
// store the current body in the html5 localstorage<br />
function storeWindowTree() {<br />
localStorage.setItem(window.name, document.body.innerHTML);<br />
}<br />
&lt;/script&gt;<br />
</code></p>
<p>So after we click on a link, we have the body of the current page in the html5 localStorage. (We should store the head too in the future).</p>
<p>On the windowhandler.html intermediate page we just do the following:</p>
<p><code><br />
&lt;script type="text/javascript" &gt;<br />
function getOldBody() {<br />
var oldBody = null;<br />
if (window.name.length != null) {<br />
oldBody = localStorage.getItem(window.name);<br />
}<br />
return oldBody;<br />
}</code></p>
<p>window.onload = function() {<br />
var oldBody = getOldBody();</p>
<p>if (oldBody != null) {<br />
document.body.innerHTML = oldBody;<br />
localStorage.removeItem(window.name);<br />
}&#8230;<br />
do all the windowId stuff (works fine anyway)<br />
window.location.reload();<br />
}</p>
<p>easy, isn&#8217;t?</p>
<p>[1] http://myfaces.apache.org/orchestra/myfaces-orchestra-core/multiwindow.html<br />
[2] https://cwiki.apache.org/confluence/display/EXTCDI/JSF+WindowHandler<br />
// ]]&gt;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/struberg.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/struberg.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/struberg.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/struberg.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/struberg.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/struberg.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/struberg.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/struberg.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/struberg.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/struberg.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/struberg.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/struberg.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/struberg.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/struberg.wordpress.com/30/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=30&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://struberg.wordpress.com/2011/11/13/solving-the-browser-tab-problem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/30fae5bce90608fb3df5c018c586aea6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">struberg</media:title>
		</media:content>
	</item>
		<item>
		<title>Flexible Configuration for Modular Systems</title>
		<link>http://struberg.wordpress.com/2010/09/21/flexible-configuration-for-modular-systems/</link>
		<comments>http://struberg.wordpress.com/2010/09/21/flexible-configuration-for-modular-systems/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 09:05:25 +0000</pubDate>
		<dc:creator>struberg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://struberg.wordpress.com/?p=16</guid>
		<description><![CDATA[Properties are cool, but you can only pickup the configuration of one property at a time. If you have a base configuration in your framework jar and need to allow further tweaking of that configuration in a higher level, then a well defined chain of responsibilities often helps.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=16&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>The Problem</h2>
<p>Properties are cool, but you can only pickup the configuration of one property file at a time. If you have a base configuration in your framework jar and need to allow further tweaking of that configuration in a higher level, then a well defined chain of responsibilities often helps.<br />
Usually this is done by</p>
<ul>
<li> having the base configuration in yourframework.jar</li>
<li>overriding the configuration if the same config.properties file exists in WEB-INF/classes</li>
</ul>
<p>But this solution is pretty restrictive and wont help you if you have a plugin architecture utilising the java.util.ServiceLoader mechanism. Speaking of OpenWebBeans, we have most of our functionality provided as SPI (Service Provider Interface) and the implementation which should get used is being picked via a config.properties. The problem we face is that we have lots of droppable plugins which need a different configuration. If you use the openwebbeans-resource.jar alone, then you&#8217;ll get a basic support for JPA via a SPI-implementation. If you additionally use openwebbeans-openejb, then we need to use another SPI implementation to get EntityManagers from OpenEJB instead.<br />
But the config.properties are all contained in JARs which have the same layer (all in WEB-INF/lib, your EAR lib or in the EE-Server classpath) &#8211; which means the algorithm mentioned above isn&#8217;t enough anymore. This is even more true in OSGi environments where you don&#8217;t have any control over the classloader hierarchy anymore.</p>
<h2>The Solution</h2>
<p>Instead of maintaining the importance of an application implicitly via it&#8217;s location, we just explicitely give each config file a configuration.ordinal property. Higher values mean higher importance. And here is how it works:</p>
<ul>
<li>First we scan for all config.properties files with ClassLoader.getResources()</li>
<li>Scan all found properties files for it&#8217;s configuration.ordinal value. If no such property is found, we assume a default value of 100</li>
<li>Sort all found config files by their configuration.ordinal values in ascending order</li>
<li>Start overlaying all properties by applying them in ascending configuration.ordinal order. All properties defined with a higher ordinal will just override the values from any less important config file.</li>
</ul>
<h2>The Usage</h2>
<p>Just type your properties files as usual. </p>
<p>myconfig.properties has a <em>configuration.ordinal</em> of 15<br />
<code><br />
configuration.ordinal=15<br />
my.value = hello user<br />
my.othervalue = not overwritten<br />
</code></p>
<p>Another jar contains a myconfig.properties with a <em>configuration.ordinal</em> of 20<br />
<code><br />
configuration.ordinal=20<br />
my.value = and now something completely different<br />
</code></p>
<p>The resulting property values are:<br />
<code><br />
my.value = and now something completely different<br />
my.othervalue = not overwritten<br />
</code></p>
<h2>The Source</h2>
<p>The whole source can be found in our Apache OpenWebBeans SVN repository:<br />
<a title="PropertyLoader.java" href="http://svn.apache.org/repos/asf/openwebbeans/trunk/webbeans-impl/src/main/java/org/apache/webbeans/config/PropertyLoader.java" target="_blank">PropertyLoader.java</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/struberg.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/struberg.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/struberg.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/struberg.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/struberg.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/struberg.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/struberg.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/struberg.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/struberg.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/struberg.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/struberg.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/struberg.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/struberg.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/struberg.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=16&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://struberg.wordpress.com/2010/09/21/flexible-configuration-for-modular-systems/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/30fae5bce90608fb3df5c018c586aea6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">struberg</media:title>
		</media:content>
	</item>
		<item>
		<title>HowTo ChangeLog with JPA</title>
		<link>http://struberg.wordpress.com/2010/07/31/howto-changelog-with-jpa/</link>
		<comments>http://struberg.wordpress.com/2010/07/31/howto-changelog-with-jpa/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 09:44:45 +0000</pubDate>
		<dc:creator>struberg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://struberg.wordpress.com/?p=12</guid>
		<description><![CDATA[How to keep track of changes in your JPA entities. This is a kind of cheap 'history' of your data.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=12&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>The problem</strong><br />
In almost all projects which have some kind of administrative functionality, there is a need to keep track of changes done to the data.</p>
<p>If we take a car rental store as example, it is good to know who reserved a car and who changed a reservation.</p>
<p>Our entity looks like the following (only the important parts of classes are shown here)<br />
<code><br />
@Entity<br />
public class CarReservation {<br />
  @Id, @Version ..<br />
  private Car car;<br />
  private @Temporal.. Date reservedFrom;<br />
  private @Temporal.. Date reservedUntil;<br />
  private Customer reservedFor;<br />
  .. getters and setters<br />
}<br />
</code></p>
<p>Now let&#8217;s consider that the customer calls our shop and likes to move his reservation to a slightly different date. The clerk officer opens the reservation and changes it accordingly. Too bad that he edited the wrong reservation and saved it. Even if he recognises his error quickly, he has no chance to revert the wrong reservation back to the correct values, because they didn&#8217;t got stored in the system.</p>
<p><strong>The solution</strong><br />
JPA provides a nice way to receive lifecycle callbacks <a href="http://download-llnw.oracle.com/javaee/6/api/javax/persistence/package-summary.html">JPA2 JavaDoc</a>.<br />
We need to somehow get the old values at the time we store the changes in our entity so we can create a &#8216;diff&#8217;. Since there always exists exactly 1 instance of a DB entry per EntityManager, we don&#8217;t have a chance to get those old values at save time. There exists a dirty trick with opening a new EntityManager inside the save operation, but that doesn&#8217;t perform well. The way I get my hands on the old values is to store them in a Map at load time by utilising <a href="http://download-llnw.oracle.com/javaee/6/api/javax/persistence/PostLoad.html">@PostLoad</a> via a <a href="http://download-llnw.oracle.com/javaee/6/api/javax/persistence/EntityListeners.html">EntityListener</a>.</p>
<p>The single parts involved in the magic:</p>
<ul>
<li>The TrackChangesListener which listens to @PostLoad and @PreUpdate JPA events</li>
<li>A new @TrackChanges annotation which marks entity fields as being subject to be tracked</li>
<li>A new @ChangeLog annotation which mark the one String @Lob field to stores the changeLog</li>
<li>An Editor component which ThreadLocally stores the oldValues and knows which entities are currently being edited (for performance reasons). It also knows the current user so we can also store who edited the entry.</li>
</ul>
<p>How our Car entity looks after we applied the changelog functionality:<br />
<code>
<pre>
@Entity
@EntityListeners({TrackChangesListener.class})
public class CarReservation {
  @Id, @Version ..

  private @TrackChanges Car car;
  private @TrackChanges @Temporal.. Date reservedFrom;
  private @TrackChanges @Temporal.. Date reservedUntil;
  private @TrackChanges Customer reservedFor;
  private @ChangeLog @Lob String changeLog;
  .. getters and setters
}
</code>

And here comes the code:

First the annotations:
<code>
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TrackChanges {
}
</code>
and
<code>
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ChangeLog {
}
</code>

And here comes the most important part, the EntityListener:
<code>
public class TrackChangesListener
{
    @PostLoad
    public void loadOldData(Object he) {
        if (!Editor.isEdited(he)) {
            return;
        }

        Map oldData = new HashMap();

        collectOldValues(oldData, "", he);

        Editor.setOldData(he, oldData);
    }

    private void collectOldValues(Map oldData, String prefix, Object he)
    {
        List historisedFields = getHistorisedFields(he);

        for (Field field : historisedFields) {
            field.setAccessible(true);
            try
            {
                if (field.getAnnotation(Embedded.class) != null) {
                    Object value = field.get(he);
                    if (value != null) {
                        // recurse into the Embedded field
                        collectOldValues(oldData, prefix + field.getName() + ".", value);
                    }
                }
                else {
                    oldData.put(prefix + field.getName(), field.get(he));
                }
            }
            catch (IllegalAccessException e)
            {
                throw new RuntimeException(e);
            }
        }
    }

    @PreUpdate
    public void updateChangeLog(Object he) {
        if (!Editor.isEdited(he)) {
            return;
        }

        try
        {
            Field changeLogField = getChangeLogField(he);
            Validate.notNull(changeLogField, "could not find @ChangeLog field in Class " + he.getClass().getName());

            StringBuilder changeLog = new StringBuilder();

            String changeLogValue = (String) changeLogField.get(he);

            if (changeLogValue != null) {
                changeLog.append(changeLogValue).append("\n\n");
            }

            changeLog.append("changedBy " ).append(Editor.getUser());
            changeLog.append(" on ").append((new Date()).toGMTString()).append('\n');

            boolean changed = false;

            changed = collectChanges(changeLog, Editor.getOldData(he), "", he);

            // update the changeLog field if a trackable change was detected
            if (changed) {
                changeLogField.set(he, changeLog.toString());
            }
        }
        catch (IllegalAccessException e)
        {
            throw new RuntimeException(e);
        }
    }

    private Field getChangeLogField(Object he)
    {
        Field[] fields = he.getClass().getDeclaredFields();

        for (Field field : fields) {
            if (field.getAnnotation(ChangeLog.class) != null) {
                field.setAccessible(true);
                return field;
            }
        }
        return null;
    }

    private boolean collectChanges(StringBuilder changeLog, Map oldData, String prefix, Object he)
    {
        boolean changed = false;
        List historisedFields = getHistorisedFields(he);
        for (Field field : historisedFields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            try
            {
                if (field.getAnnotation(Embedded.class) != null) {
                    Object value = field.get(he);
                    if (value != null) {
                        // recurse into the Embedded field
                        changed |= collectChanges(changeLog, oldData, prefix + field.getName() + ".", value);
                    }
                }
                else {
                    Object newValue = field.get(he);
                    Object oldValue = oldData.get(prefix + fieldName);
                    changed |= addChangeLine(changeLog, prefix + fieldName, oldValue, newValue);
                }
            }
            catch (IllegalAccessException e)
            {
                throw new RuntimeException(e);
            }
        }
        return changed;
    }

    private boolean addChangeLine(StringBuilder changeLog, String fieldName, Object oldValue, Object newValue)
    {
        if (oldValue == null &amp;&amp; newValue == null) {
            return false;
        }
        if (oldValue != null &amp;&amp; oldValue.equals(newValue)) {
            // no change
            return false;
        }

        String changeLine = fieldName + " old: [" + (oldValue != null ? oldValue : "") + "] new: [" + (newValue != null ? newValue : "") + "]\n";
        changeLog.append(changeLine);
        return true;
    }

    private List getHistorisedFields(Object he)
    {
        Field[] fields = he.getClass().getDeclaredFields();
        List histFields = new ArrayList();

        for (Field field : fields) {
            if (field.getAnnotation(TrackChanges.class) != null) {
                histFields.add(field);
            }
        }

        return histFields;
    }

}
</pre>
<p></code></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/struberg.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/struberg.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/struberg.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/struberg.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/struberg.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/struberg.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/struberg.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/struberg.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/struberg.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/struberg.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/struberg.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/struberg.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/struberg.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/struberg.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=12&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://struberg.wordpress.com/2010/07/31/howto-changelog-with-jpa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/30fae5bce90608fb3df5c018c586aea6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">struberg</media:title>
		</media:content>
	</item>
		<item>
		<title>Are JSR-299 CDI Annotations too complicated?</title>
		<link>http://struberg.wordpress.com/2010/05/15/are-jsr-299-cdi-annotations-too-complicated/</link>
		<comments>http://struberg.wordpress.com/2010/05/15/are-jsr-299-cdi-annotations-too-complicated/#comments</comments>
		<pubDate>Sat, 15 May 2010 21:02:03 +0000</pubDate>
		<dc:creator>struberg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSR-299]]></category>

		<guid isPermaLink="false">http://struberg.wordpress.com/?p=4</guid>
		<description><![CDATA[After my talk at GeeCON, I got a few comments from folks who have the feeling that all those CDI annotations are a little bit too much. So, is CDI really an annotation mess? After reflecting this question, it became clear to me that this may seem so when looking at CDI for the first [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=4&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>After my talk at GeeCON, I got a few comments from folks who have the feeling that all those CDI annotations are a little bit too much.</p>
<p>So, is CDI really an annotation mess?</p>
<p>After reflecting this question, it became clear to me that this may seem so when looking at CDI for the first time. But on the other hand, what do you get from all those annotations? Let&#8217;s grab a bit deeper.</p>
<p>Ed Burns recently pointed me to a famous quote from an old computer science book [1] on how to build large software systems:<br />
1.) Build Abstractions<br />
2.) Establish conventional Interfaces<br />
3.) Establish new descriptive languages</p>
<p>In fact, 1.) and 2.) are already well covered in most Java applications &#8211; but can we interpret annotations as kind of a &#8216;meta-language&#8217;?<br />
I&#8217;d say yes &#8211; by writing your own set of annotations, you effectively create kind of your own domain specific language.  Now, what is a &#8216;programming language&#8217;? In a (not so strict) academical sense the answer would probably be &#8220;a way to tell your computer what and how it should execute&#8221;. And that is exactly what annotations can do for you!</p>
<p>You could easily create annotations (interceptors) like:<br />
<code><br />
@skipIf(test="param1==NULL OR today=Calendar.SUNDAY")<br />
public void myMethod(String param1) { ... }<br />
</code><br />
<code><br />
@cache(lru=3600)<br />
public List getCustomers(Partner p) { ... }</p>
<p></code><br />
<code><br />
@updateStatistics<br />
public Basket purchaseProduct(Product p) { ... }<br />
</code></p>
<p>Focusing back on CDI, it now becomes pretty clear that this really allows kind of &#8216;establishing a new descriptive language&#8217;. This isn&#8217;t only AOP in the sense of _only_ applying technical concerns anymore, but we really use lots of the annotations coming with CDI to create kind of language like semantic-rich execution instructions. This of course also includes self written ones, based on the CDI meta annotations.</p>
<p>Now, looking at all the CDI annotations (and mechanisms to interpret them) from _this_ perspective, I&#8217;d say you could gain a hell lot benefit from learning these few CDI annotations &#8211; if used wisely of course.</p>
<p>LieGrue,<br />
strub</p>
<p>[1] Structure and Interpretation of Computer Programs, Abelson and Sussman, MIT Press 1996. Ed also cites this in his &#8216;Secrets of Rockstar Programmers&#8217; book.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/struberg.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/struberg.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/struberg.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/struberg.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/struberg.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/struberg.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/struberg.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/struberg.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/struberg.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/struberg.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/struberg.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/struberg.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/struberg.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/struberg.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=struberg.wordpress.com&amp;blog=13696069&amp;post=4&amp;subd=struberg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://struberg.wordpress.com/2010/05/15/are-jsr-299-cdi-annotations-too-complicated/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/30fae5bce90608fb3df5c018c586aea6?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">struberg</media:title>
		</media:content>
	</item>
	</channel>
</rss>
