<?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>techbits.de &#187; java</title>
	<atom:link href="http://www.techbits.de/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.techbits.de</link>
	<description>thoughts on hardware, software, development and tech news</description>
	<lastBuildDate>Fri, 02 Dec 2011 22:51:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Recursive file iteration in Java</title>
		<link>http://www.techbits.de/2010/02/11/recursive-file-iteration-in-java/</link>
		<comments>http://www.techbits.de/2010/02/11/recursive-file-iteration-in-java/#comments</comments>
		<pubDate>Thu, 11 Feb 2010 21:15:48 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[apidesign]]></category>
		<category><![CDATA[bestpractice]]></category>

		<guid isPermaLink="false">http://www.techbits.de/?p=198</guid>
		<description><![CDATA[In a java frameworks talk I gave recently I showed the following example for finding files recursively&#8230; public void listFilesInDirectory(File dir) { File[] files = dir.listFiles(); if (files != null) { for (File f : files) { if (f.isDirectory()) { &#8230; <a href="http://www.techbits.de/2010/02/11/recursive-file-iteration-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In a java frameworks talk I gave recently I showed the following example for finding files recursively&#8230;</p>
<blockquote>
<pre>public void listFilesInDirectory(File dir) {
  File[] files = dir.listFiles();
    if (files != null) {
      for (File f : files) {
         if (f.isDirectory()) {
	    listFilesInDirectory(f);
	 }
	 else {
	    System.out.println(f.getName());
	}
     }
  }
}</pre>
</blockquote>
<p>&#8230; which in real projects often grows to a larger block of code. The web is full of code blocks like this for walking a directory tree. The best version I came across is<a id="wylk" title="this object oriented one by Torsten  Curdt" href="http://vafer.org/blog/20071112204524"> this object oriented one by Torsten Curdt</a>. Since you usually don&#8217;t want to write this yourself, I suggested in my talk to use FileUtils which makes recursive iteration much easier:</p>
<blockquote>
<pre>Collection jspFiles = FileUtils.listFiles(rootDirName,
                        new String[] { "jsp" }, true);</pre>
</blockquote>
<p>This looks concise and useful but as I tried to use it, I wasn&#8217;t too pleased with the FileUtils&#8217; solution. Here is why:</p>
<ul>
<li>The recursion is processed in one go, i.e. all results are written to a List even when using the iterateFiles method. The recursion is not processed iteratively.</li>
<li>You can not influence the directories that are searched.</li>
<li>Only files are returned, you can not search for directories.</li>
<li>The API is not very expressive (e.g. what does the &#8220;true&#8221; mean).</li>
<li>No generics (raw collection types are returned).</li>
</ul>
<h1>A Better API</h1>
<p>Not being satisfied with the solutions I found, I &#8220;dreamed up&#8221; my own API for listing and finding files. I don&#8217;t consider it complete but for the most part I am pleased with the ease of use that the builder pattern provides. The code for this can currently be found in an <a id="l6db" title="unrelated goole code project" href="http://code.google.com/p/data-integrity-check/source/browse/#svn/trunk/src/main/java/de/fmaul/common/io">unrelated goole code project</a>. The rest of this article shows the functions that are currently supported.</p>
<h2>Find files two ways</h2>
<p>There are generally two ways to use the result &#8211; as interator or as list:</p>
<p><span style="font-family: Arial;">1. Iterate over all files in the windows directory:</span></p>
<blockquote>
<pre><span style="font-family: Courier New;">for (File f : <strong>Files.find</strong>("c:\\windows")) {</span><br style="font-family: Courier New;" /><br style="font-family: Courier New;" /><span style="font-family: Courier New;">}</span></pre>
</blockquote>
<p>2. Get all the files in a directory as a list of files:</p>
<blockquote>
<pre><span style="font-family: Courier New;">List&lt;File&gt; allFiles = <strong>Files.find</strong>(somedir).<strong>list()</strong>;</span></pre>
</blockquote>
<p><span style="font-family: Verdana;">Except from the return type the second version does the same </span><span style="font-family: Courier New;"><span style="font-family: Verdana;">as the JDK command listFiles:</span></span></p>
<blockquote>
<pre>File[]  allFiles = (new File(somedir)).listFiles()</pre>
</blockquote>
<h2>Easy recursive listing</h2>
<p>To iterate all the files in the C:\Windows directory, you would use:</p>
<blockquote>
<pre><span style="font-family: Courier New;">for (File f : Files.find("c:\\windows").<strong>recursive()</strong>) {</span><br style="font-family: Courier New;" /><br style="font-family: Courier New;" /><span style="font-family: Courier New;">}</span></pre>
</blockquote>
<p>Note: This actually works iteratively, i.e. the recursion happens as you fetch files from the iterator. The result is not fetched into a huge list.</p>
<p>With a Predicate you can limit the recursion to specific directories. In this example all .svn directories within a source tree are skipped:</p>
<blockquote>
<pre><span style="font-family: Courier New;">Predicate&lt;File&gt; noSvnDirs = new Predicate&lt;File&gt;() {</span><br style="font-family: Courier New;" /><span style="font-family: Courier New;"> boolean apply(File file) {</span><br style="font-family: Courier New;" /><span style="font-family: Courier New;"> return !file.getName().equals(".svn");</span><br style="font-family: Courier New;" /><span style="font-family: Courier New;"> }</span><br style="font-family: Courier New;" /><span style="font-family: Courier New;">}</span></pre>
<pre><span style="font-family: Courier New;">for (File f : Files.find("src/java/").<strong>recursive(noSvnDir)</strong>) {</span><br style="font-family: Courier New;" /><br style="font-family: Courier New;" /><span style="font-family: Courier New;">}</span></pre>
</blockquote>
<h2>Want Files, Directories or both?</h2>
<p>Define if you want only files, only directories or both in your result with yield*()-Methods.</p>
<blockquote>
<pre>Files.find(someBaseDir).recursive().yieldFiles()  // this is the default
Files.find(someBaseDir).recursive().yieldDirectories()
Files.find(someBaseDir).recursive().yieldFilesAndDirectories()</pre>
</blockquote>
<h2>Filtering the results</h2>
<p>To get all textfiles within a dir use:</p>
<blockquote>
<pre>Files.find(dir).withExtension("txt").list();
Files.find(dir).ignoreCase().withExtension("txt").list();</pre>
</blockquote>
<p>You can also filter by Name, e.g. to find README files:</p>
<blockquote>
<pre>Files.find(dir).withName("README").list();
Files.find(dir).ignoreCase().withName("readme").list();</pre>
</blockquote>
<p>Note that the default matching is case sensitive. The commands caseSensitive() and ignoreCase() can be used to toggle the matching behaviour.</p>
<p>For special needs you can also specify a Predicate&lt;File&gt; to filter the resulting files.</p>
<blockquote>
<pre>Files.find(dir).recursive().withFilter(somePredicate).list();</pre>
</blockquote>
<h2>Finding Directories</h2>
<p>When looking for directories there are some special usecases that are supported, e.g. looking for directories that contain a specific file:</p>
<blockquote>
<pre>Files.find(dir).recursive().yieldDirectories()
               .containingFile("Thumbs.db");</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2010/02/11/recursive-file-iteration-in-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Android exploration continued</title>
		<link>http://www.techbits.de/2010/01/04/android-exploration-continued/</link>
		<comments>http://www.techbits.de/2010/01/04/android-exploration-continued/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 12:01:13 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[app]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.techbits.de/?p=192</guid>
		<description><![CDATA[I extended my android application with a preferences screen now, which is quite easy to do. A tutorial for creating a Preferences Activity got me started &#8211; unfortunaltely the xml preferences definition it uses is incorrect. The tags are names &#8230; <a href="http://www.techbits.de/2010/01/04/android-exploration-continued/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I extended my android application with a preferences screen now, which is quite easy to do.</p>
<ul>
<li>A <a href="http://www.androidguys.com/2008/09/29/whats-your-preference-part-one/">tutorial for creating a Preferences Activity</a> got me started &#8211; unfortunaltely the xml preferences definition it uses is incorrect. The tags are names of Classes which have to be capitalized.</li>
<li>The open the preferences activity I added a <a href="http://developer.android.com/guide/topics/ui/menus.html">Option Menu</a>.</li>
<li>I wanted to add some kind of progress indicator. I ended up using the <a href="http://developer.android.com/reference/android/app/ProgressDialog.html">ProgressDialog </a>and the <a href="http://developer.android.com/reference/android/os/AsyncTask.html">AsyncTask </a>to run the downloading and xml parsing in the background. To fix issues with device rotation I might have a look at the BetterAsyncTask in the <a href="http://github.com/kaeppler/droid-fu">Droid-FU library</a> later.</li>
<li>I also ran into DateFormat and Date issues with the UTC formated Date in the XML file. I Thought about using <a href="http://joda-time.sourceforge.net/"> joda-time</a> at least twice but then stuck to the JDK implementation for smaller app size. The fact that android brings it&#8217;s own class named DateFormat which just provides a localized JDK-DateFormat object doesn&#8217;t help either.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2010/01/04/android-exploration-continued/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>First Steps with Android</title>
		<link>http://www.techbits.de/2009/12/30/first-steps-with-android/</link>
		<comments>http://www.techbits.de/2009/12/30/first-steps-with-android/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 10:02:54 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://www.techbits.de/?p=189</guid>
		<description><![CDATA[In the last few days I started out with some android development. Here are some things learned so far developing my first app: The Android Tutorials are a great starting point, though i only followed through with the HelloWorld Tutorial. &#8230; <a href="http://www.techbits.de/2009/12/30/first-steps-with-android/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In the last few days I started out with some android development. Here are some things learned so far developing my first app:</p>
<ul>
<li>The Android Tutorials are a great starting point, though i only followed through with the <a href="http://developer.android.com/intl/de/resources/tutorials/hello-world.html">HelloWorld</a> Tutorial. In retrospect I should have looked at the <a href="http://developer.android.com/intl/de/resources/tutorials/notepad/index.html">Notepad Tutorial</a> a little closer because it explains important concepts (namely activities/intents).</li>
<li><a href="http://www.anddev.org/">http://www.anddev.org/</a> is a useful source for tutorials and code snippets</li>
<li>It&#8217;s still java but a completely different API, so you often have to look for classes and methods via code completion oder in examples to get things done.</li>
<li><strong>Downloading:</strong> Can be done with the included HTTP Client library. Unfortuantely <a href="http://dlinsin.blogspot.com/2009/08/http-basic-authentication-with-android.html">Android still uses an old version of the HTTP Client</a> though, which made it hard to find documentation (e.g. how to set authentication credentials). Additionally you shoudn&#8217;t forget to declare the INTERNET-permissions in your application manifest.</li>
<li><strong>Storing and retrieving Files</strong> looks fairly easy (getDir(), getCacheDir()-Methods are there) at first sight but you have to unerstand the Android filesystem security model if you don&#8217;t want to spend hours with debugging. The before mentoined methods use internal storage where each application stores it&#8217;s data independently. Public read/write (e.g. file exchange with other applications) is only possible when you store your content with the specific method openFileOutput(). The external SD card on the other hand can be openly accessed with the regular Java File API.</li>
<li><strong>XML Parsing:</strong> I started out with the sax parser but since my XML file was pretty complex I ditched it and downloaded<a href="http://brainflush.wordpress.com/2009/05/19/the-force-unleashed-xmlxpath-on-android-using-dom4j-and-jaxen/"> dom4j</a> which has a really easy to use API. Unfortunately it adds at least 200KB of final app size. I now realized I could have gone with the<a href="http://www.anddev.org/parse_xml_with_dom_-_getnodevalue_always_null-t3082.html"> regular DOM parser</a> which has a decent API. I&#8217;ll have to reevaluate this later &#8211; maybe the end user responsiveness does require the faster streaming parser approach (sax).</li>
<li><strong>UI design:</strong> Declarative XML based looks powerful and well thought out but I mostly stuck to tutorial layout for now. This is an area I still have to get into.</li>
</ul>
<p>Ok, that&#8217;s it for now. Android is turning out to be a great plattform &#8211; exciting times.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2009/12/30/first-steps-with-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding Googles GData Java API to your maven repository</title>
		<link>http://www.techbits.de/2009/08/06/adding-googles-gdata-java-api-to-your-maven-repository/</link>
		<comments>http://www.techbits.de/2009/08/06/adding-googles-gdata-java-api-to-your-maven-repository/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 17:09:34 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[gdata]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[mavenize]]></category>
		<category><![CDATA[mvn]]></category>

		<guid isPermaLink="false">http://www.techbits.de/?p=181</guid>
		<description><![CDATA[The google gdata apis do not come with maven POM-files. Someone went through the trouble to &#8220;mavenize&#8221; the source but it is limited to linux as build plattform and currently out of date (compile errors). So I installed the JARs &#8230; <a href="http://www.techbits.de/2009/08/06/adding-googles-gdata-java-api-to-your-maven-repository/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The<a href="http://code.google.com/intl/de-DE/apis/gdata/overview.html"> google gdata apis</a> do not come with maven POM-files. Someone went through the trouble to <a href="http://code.google.com/p/google-apis-mavenized/">&#8220;mavenize&#8221; the source</a> but it is limited to linux as build plattform and currently out of date (compile errors). So I installed the JARs from the binary distribution of the APIs into my local repository &#8211; which are of course missing the dependencies between the individual JAR files. Here are two batch files which I used to install the JARs quite painlessly:</p>
<p>install.bat:</p>
<blockquote>
<pre>@SET mvn=d:\java\maven\bin\mvn
@%mvn% install:install-file -DgroupId=com.google.gdata
       -DartifactId=%1 -Dversion=%2 -Dfile=%3 -Dpackaging=jar
       -DgeneratePom=true</pre>
</blockquote>
<p>installall.bat:</p>
<blockquote>
<pre>call install.bat gdata-analytics 2.0 gdata-analytics-2.0.jar
call install.bat gdata-appsforyourdomain 1.0 gdata-appsforyourdomain-1.0.jar
call install.bat gdata-base 1.0 gdata-base-1.0.jar
call install.bat gdata-blogger 2.0 gdata-blogger-2.0.jar
call install.bat gdata-books 1.0 gdata-books-1.0.jar
call install.bat gdata-calendar 1.0 gdata-calendar-2.0.jar
call install.bat gdata-client 1.0 gdata-client-1.0.jar
call install.bat gdata-codesearch 2.0 gdata-codesearch-2.0.jar
call install.bat gdata-contacts 3.0 gdata-contacts-3.0.jar
call install.bat gdata-core 1.0 gdata-core-1.0.jar
call install.bat gdata-docs 2.0 gdata-docs-2.0.jar
call install.bat gdata-finance 2.0 gdata-finance-2.0.jar
call install.bat gdata-health 2.0 gdata-health-2.0.jar
call install.bat gdata-maps 2.0 gdata-maps-2.0.jar
call install.bat gdata-media 1.0 gdata-media-1.0.jar
call install.bat gdata-photos 2.0 gdata-photos-2.0.jar
call install.bat gdata-spreadsheet 3.0 gdata-spreadsheet-3.0.jar
call install.bat gdata-webmastertools 2.0 gdata-webmastertools-2.0.jar
call install.bat gdata-youtube 2.0 gdata-youtube-2.0.jar</pre>
</blockquote>
<p>You surely could get fancy and automate the splitting between artifact-name and version number, but hey, I needed those JARs installed quickly and that&#8217;s what it does.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2009/08/06/adding-googles-gdata-java-api-to-your-maven-repository/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>IndexedList: A hybrid of a Java List and a Map</title>
		<link>http://www.techbits.de/2009/07/18/indexedlist-a-hybrid-of-a-java-list-and-a-map/</link>
		<comments>http://www.techbits.de/2009/07/18/indexedlist-a-hybrid-of-a-java-list-and-a-map/#comments</comments>
		<pubDate>Sat, 18 Jul 2009 11:00:09 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.techbits.de/?p=164</guid>
		<description><![CDATA[If been working on legacy data import code in the last months with a lot of code searching for exisiting objects in lists. I realized I needed a different collection to speed up searching for identifiers and couldn&#8217;t find any &#8230; <a href="http://www.techbits.de/2009/07/18/indexedlist-a-hybrid-of-a-java-list-and-a-map/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If been working on legacy data import code in the last months with a lot of code searching for exisiting objects in lists. I realized I needed a different collection to speed up searching for identifiers and couldn&#8217;t find any standard collection that matches my needs. I basically need an index like <span style="font-family: Courier New;">Maps.uniqueIndex()</span> from the <a href="http://code.google.com/p/google-collections/">Google Collections Library</a> provides but it should be updating dynamically and not only be generated once.</p>
<p><span id="more-164"></span>To summarize my requirements:</p>
<ul>
<li>A List (ArrayList) which can be modified as usual</li>
<li>A way to find objects (contains and get) in constant time by a custom attribute (like a HashMap)</li>
<li>No reliance on equals() and hashcode() because they cover more attributes (an can not be changed)</li>
</ul>
<p>The <span style="font-family: Courier New;">LinkedHashMap </span>seems to almost fit the bill but it is not a true List and therefore not a great drop in replacement.</p>
<p>What I&#8217;m using right now is a wrapper around a List which maintains an additional HashMap to find objects by the index criterium. The index is automatically updated whenever the list is modified. This is an example on how I use it:</p>
<blockquote>
<pre>// function to index Persons by their social security number<br style="font-family: Courier New;" />Function&lt;Person, String&gt; getSsnrForPerson =
  new Function&lt;Person, String&gt;() {<br style="font-family: Courier New;" />    String apply(Person person) {<br style="font-family: Courier New;" />      return person.getSocialSecurityNumber();<br style="font-family: Courier New;" />    }<br style="font-family: Courier New;" />  }</pre>
</blockquote>
<p>To create an indexed list for an empty ArrayList&lt;Person&gt; with an index on a person&#8217;s social security number you can then easily use the Class UniqueIndexedList:</p>
<blockquote>
<pre>UnqiueIndexedList&lt;Person, String&gt; myList =
  UnqiueIndexedList.create(getSsnrForPerson);</pre>
</blockquote>
<p>Of course all the usual methods of the List&lt;Person&gt; interface can be used as usual:</p>
<blockquote>
<pre>myList.add(somePerson);
myList.add(anotherPerson);
myList.get(i);
myList.iterator();</pre>
</blockquote>
<p>Additionaly there are  methods to access objects by index:<br style="font-family: Courier New;" /></p>
<blockquote>
<pre>boolean personIsInList = myList.containsByIndex("34897634853");</pre>
<pre>Person p = myList.getByIndex("34897634853");</pre>
</blockquote>
<p>The code for the list implementation currently resides here:</p>
<ul>
<li><a id="neqh" title="http://code.google.com/p/data-integrity-check/source/browse/trunk/src/main/java/de/fmaul/common/collect/IndexedList.java" href="http://code.google.com/p/data-integrity-check/source/browse/trunk/src/main/java/de/fmaul/common/collect/IndexedList.java">IndexedList.java</a></li>
<li><a id="uk2m" title="http://code.google.com/p/data-integrity-check/source/browse/trunk/src/main/java/de/fmaul/common/collect/UniqueIndexedList.java" href="http://code.google.com/p/data-integrity-check/source/browse/trunk/src/main/java/de/fmaul/common/collect/UniqueIndexedList.java">UniqueIndexedList.java</a></li>
</ul>
<p>It is basically a hybrid of a List and a special index-Map and works well so far. I am sure that finding objects in list for a given attribute is a very common usecase. Why hasn&#8217;t anyone solved this yet? Are there (better) alternatives that I&#8217;ve missed?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2009/07/18/indexedlist-a-hybrid-of-a-java-list-and-a-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EJB3 persistence with hibernate</title>
		<link>http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/</link>
		<comments>http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/#comments</comments>
		<pubDate>Mon, 17 Apr 2006 12:30:07 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ejb3]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[persistence]]></category>

		<guid isPermaLink="false">http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/</guid>
		<description><![CDATA[Since my trip to java posting I looked into EJB3 persistence (JSR-220) with hibernate as promised. It&#8217;s shocking how much the EJB3 specification resembles hibernate &#8211; Gavin King apparently got most if his hibernate semantics in there. I believe it&#8217;s &#8230; <a href="http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Since my <a href="http://www.techbits.de/2006/03/19/a-trip-to-java/">trip to java</a> posting I looked into EJB3 persistence (<a href="http://www.jcp.org/en/jsr/detail?id=220">JSR-220</a>) with <a href="http://www.hibernate.org/">hibernate</a> as promised. It&#8217;s shocking how much the EJB3 specification resembles hibernate &#8211; Gavin King apparently got most if his hibernate semantics in there. I believe it&#8217;s a good thing though. Former hibernate developers can adapt the new sepecification with little effort and on the other hand the definition of persitience classes has been cleaned up nicely with properly defined annotations.<br />
So far I&#8217;ve been able to create a simple example application with the hibernate entitymanager/annotations engine. It simply creates two objects, stores them in the database an reads them again with a query. The rest of this post shows how this example app is set up.<br />
<span id="more-31"></span><br />
</p>
<h3>Configuration</h3>
<p>First of all a configuration file for the database and the persistent classes is needed. The xml file <b>META-INF/persitence.xml</b> is used for that purpose. In my example application I used a local <a href="http://www.hsqldb.org/">hsqldb</a> database. In addition to the database each persistent class has to be specified in a class-element, in this case <b>example.pojo.Cat</b>.</p>
<p><code lang="xml"><br />
<?xml version="1.0" encoding="UTF-8"?></p>
<persistence>
<persistence-unit name="manager1"<br />
      transaction-type="RESOURCE_LOCAL"><br />
    <class>example.pojo.Cat</class></p>
<properties>
<property name="hibernate.dialect"<br />
        value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.connection.driver_class"<br />
        value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.url"<br />
        value="jdbc:hsqldb:file:database/ejb3test"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.shutdown">true</property>
    </properties>
  </persistence-unit>
</persistence>
</code></p>
<h3>Data classes with annotations</h3>
<p>As seen above only one persistent class is used in this application. It defines a cat, which has an id, a name and a birth date. In addition to that it also has a parent child relationship as a self reference (attributes mother and kittens). You can also see the annotations which define how all these attributes are persisted. This is the bare minimum of annotations that is required for EJB3 persistence to work. In a more complex application where you want a detailed control over relations, database tables, datatypes and query characteristics the annotations will also look a lot more complex.<br />
<code lang="java5"><br />
package example.pojo;</p>
<p>import java.util.ArrayList;<br />
import java.util.Date;<br />
import java.util.List;<br />
import javax.persistence.CascadeType;<br />
import javax.persistence.Entity;<br />
import javax.persistence.GeneratedValue;<br />
import javax.persistence.GenerationType;<br />
import javax.persistence.Id;<br />
import javax.persistence.ManyToOne;<br />
import javax.persistence.OneToMany;</p>
<p>@Entity<br />
public class Cat {</p>
<p>	private String name;<br />
	private Date birthDate;<br />
	private int id;<br />
	private Cat mother;<br />
	private List<Cat> kittens;</p>
<p>	public Cat() {<br />
		super();<br />
		setKittens(new ArrayList<Cat>());<br />
	}</p>
<p>	public void addKitten(Cat kitten) {<br />
		this.getKittens().add(kitten);<br />
		kitten.setMother(this);<br />
	}</p>
<p>	// -- GETTERs and SETTERs --</p>
<p>	@OneToMany(cascade = CascadeType.ALL, mappedBy="mother")<br />
	public List<Cat> getKittens() {<br />
		return kittens;<br />
	}<br />
	public void setKittens(List<Cat> kittens) {<br />
		this.kittens = kittens;<br />
	}</p>
<p>	@ManyToOne(optional=true)<br />
	public Cat getMother() {<br />
		return mother;<br />
	}<br />
	public void setMother(Cat parent) {<br />
		this.mother = parent;<br />
	}</p>
<p>	@Id	@GeneratedValue(strategy=GenerationType.AUTO)<br />
	public int getId() {<br />
		return id;<br />
	}<br />
	public void setId(int id) {<br />
		this.id = id;<br />
	}</p>
<p>	public String getName() {<br />
		return name;<br />
	}<br />
	public void setName(String name) {<br />
		this.name = name;<br />
	}</p>
<p>	public Date getBirthDate() {<br />
		return birthDate;<br />
	}<br />
	public void setBirthDate(Date birthDate) {<br />
		this.birthDate = birthDate;<br />
	}<br />
}<br />
</code></p>
<h3>The entity manager</h3>
<p>The EJB3 entity manager is what used to the session in hibernate. It provides all functionality to store, update and query objects from the database. In the example code below it is created from a EntityManagerFactory which makes use of the persistence.xml configuration file &#8211; you can see the reference to the persistence-unit <em>manager1</em> here.<br />
Using the entity manager a transaction is started, 2 cats are created, linked as mother and kitten and finally persited with a call to persist() of the entity manager. This step is as simple as with a good old hibernate. Same is true for the query part which follows after that &#8211; a parameterized query returns all cats that where born before 1.1.2003.<br />
<code lang="java5"><br />
package example;</p>
<p>import java.text.ParseException;<br />
import java.text.SimpleDateFormat;<br />
import java.util.Iterator;<br />
import java.util.List;</p>
<p>import javax.persistence.EntityManager;<br />
import javax.persistence.EntityManagerFactory;<br />
import javax.persistence.EntityTransaction;<br />
import javax.persistence.Persistence;</p>
<p>import example.pojo.Cat;</p>
<p>public class Test {</p>
<p>	public static void main(String[] args) throws ParseException {</p>
<p>		// Read configuration from META-INF/persistence.xml<br />
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");</p>
<p>		EntityManager em = emf.createEntityManager();</p>
<p>		// --------- CREATE CATS -----------</p>
<p>		EntityTransaction t = em.getTransaction();<br />
		t.begin();</p>
<p>		// Create two cats<br />
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");<br />
		Cat mimi = new Cat();<br />
		mimi.setName("Mimi");<br />
		mimi.setBirthDate(df.parse("2001-03-01"));<br />
		em.persist(mimi);</p>
<p>		Cat max = new Cat();<br />
		max.setName("Max");<br />
		max.setBirthDate(df.parse("2003-05-18"));<br />
		em.persist(max);</p>
<p>		// Mimi is the mother of max<br />
		mimi.addKitten(max);</p>
<p>		// Commit transaction to store the cats in the database<br />
		t.commit();</p>
<p>		// --------- QUERY CATS -----------</p>
<p>		// Get all cats that where born before 1.1.2003<br />
		List catList = em.createQuery(<br />
	    	"select cat from Cat as cat where cat.birthDate < ?1")<br />
	    	.setParameter(1, df.parse("2003-01-01"))<br />
	    	.getResultList();</p>
<p>		// Print the list of cats with the number of their children<br />
		Iterator catIterator = catList.iterator();<br />
		while (catIterator.hasNext()) {<br />
			Cat mycat = (Cat) catIterator.next();</p>
<p>			System.out.println(mycat.getName() + " children:"+<br />
					mycat.getKittens().size());<br />
		}</p>
<p>		// Close the Entity Manager<br />
		em.close();<br />
		emf.close();<br />
	}</p>
<p>}<br />
</code></p>
<h3>Preliminary conclusion</h3>
<ol>
<li>I realize, this simple example doesn't say much about the feature set of EJB3 compared to the hibernate features (caches, optimized queries, relations, etc..). It is a good starting point for further experiments though which is why I provide the <b>example eclipse project as a download</b> including all required libraries. This means this should run in any 3.1 eclipse out of the box.
<li>Did you notice that none of the import statements reference a hibernate specific package? The application only uses the javax.persistence interface so theoretically you should be able to switch from hibernate to any other ejb3 persistence solution without changing a single line of code.
<li>Getting rid of the hibernate mapping files which had to be edited separately from the code or be generated with xdoclet is a big plus in my opinion. I would move my last project from xdoclet tags to annotations in an instant if there wasn't the requirement to use java 1.4.
</ol>
<h3>Download the example</h3>
<p>If you like to experiment yourself, download the <a href="/wp-content/uploads/2006/04/Ejb3PersistenceTest.zip">Ejb3PersistenceTest.zip (5MB)</a> eclipse project. It contains all hibernate libraries (core, entity manager, annotations) to get you started.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Diving into java scripting frameworks</title>
		<link>http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/</link>
		<comments>http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/#comments</comments>
		<pubDate>Tue, 21 Mar 2006 20:10:01 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[beanshell]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[rhino]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/</guid>
		<description><![CDATA[As I wrote sunday, I experimented with beanshell and it worked pretty well und faster than I anticipated. Nevertheless I heard about some other scripting frameworks (and their integration in java 1.6) which motivated me to investigate a bit more &#8230; <a href="http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As I wrote sunday, I experimented with beanshell and it worked pretty well und faster than I anticipated. Nevertheless I heard about some other scripting frameworks (and their integration in java 1.6) which motivated me to investigate a bit more in this direction. Apparently <a href="http://www.mozilla.org/rhino/">Mozilla&#8217;s Rhino</a> is a very powerful yet fast framework that provides javascript aka ECMAscript. Performance benchmarks by Pankaj Kumar in his article <a href="http://www.pankaj-k.net/spubs/articles/beanshell_rhino_and_java_perf_comparison/index.html">BeanShell, Rhino and Java &#8212; Performance Comparison</a> show that my choice of beanshell as a scripting framework might not have been that best &#8211; performance wise. I&#8217;ll definately check out Rhino for use in my application.</p>
<p>Another interesting framework I came across when looking into scripting with java is the <a href="http://jakarta.apache.org/bsf/index.html">Apache Jakarta Bean Scripting Framework (BSF)</a> which provides a framework to create JSP pages in different scripting languages. To achieve this it offers a uniform interface which wraps several scripting languages like javascript, python, tcl and many more.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A trip to java</title>
		<link>http://www.techbits.de/2006/03/19/a-trip-to-java/</link>
		<comments>http://www.techbits.de/2006/03/19/a-trip-to-java/#comments</comments>
		<pubDate>Sun, 19 Mar 2006 22:09:39 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[beanshell]]></category>
		<category><![CDATA[ejb3]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[j2se]]></category>
		<category><![CDATA[mda]]></category>
		<category><![CDATA[uml]]></category>

		<guid isPermaLink="false">http://www.techbits.de/2006/03/19/a-trip-to-java/</guid>
		<description><![CDATA[Once again a long time has passed where I couldn&#8217;t find the time or motivation to write a post. I was mainly occupied with the specification of a java application which gave me the opportunity to get to know Sparx &#8230; <a href="http://www.techbits.de/2006/03/19/a-trip-to-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Once again a long time has passed where I couldn&#8217;t find the time or motivation to write a post. I was mainly occupied with the specification of a java application which gave me the opportunity to get to know <a href="http://sparxsystems.com/">Sparx System&#8217;s Enterprise Architect</a>. I only used the common uml diagram types and the code generation features for this project and they work pretty well. I&#8217;d love to make use of the more advanced features though and look into the whole <a href="http://en.wikipedia.org/wiki/Model-driven_architecture">MDA</a> approach a bit more. There is a fundamental difference in just drawing some class diagrams and really developing model driven from the ground up. Projects like <a href="http://www.andromda.org/">AndroMDA</a> to generate complete applications look promising and certainly could reduce the expenses for software development but I doubt I&#8217;ll find time to check it out properly any time soon. As for the modelling language I don&#8217;t think everything should be done with UML though &#8211; the approach to model every aspect in UML and using stereotypes to define &#8220;what it means&#8221; makes the modeling too confusing and complex imho. Some interesting views on MDA and Software Factories can be found in the podcast <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=156291#156291">MDA vs. Software Factories</a> and some older episodes.</p>
<p>At the moment I&#8217;m working on a prototype for another java application and got used to the new java 1.5 features like <a href="http://java.sun.com/developer/technicalArticles/J2SE/generics/">generics </a> and the new for each loops. The generics are definately the way to go for typesafe collections and I&#8217;ll try to use them from here on out. I found the wildcard <code>&lt;? extends&gt;</code> and some other constructions confusing at first but I do understand that there are <a href="http://www.fh-wedel.de/~si/seminare/ws05/Ausarbeitung/5.generics/genjava3.htm">several restrictions (german link)</a> when using generics. Someone should publish some design patterns for typical cases that require generics.</p>
<p>For that project I also experimented with <a href="http://www.beanshell.org/">BeanShell</a> which is basically a java scripting interpreter. I&#8217;ll probably use it for custom formulas which are evaluated dynamically within the java application. Easy to use and powerful. </p>
<p>The next component I&#8217;ll look into is <a href="http://www.hibernate.org/299.html">EJB3 persistence using Hibernate</a>. I have worked with the hibernate tools and reverse enginered some database tables but since I already have the POJO classes and don&#8217;t want to create all the old hibernate xml mapping files I might as well check out how to create EJB3 persistence by using annotations. More on that soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2006/03/19/a-trip-to-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

