<?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>Kevin&#039;s Blog</title>
	<atom:link href="http://blog.lckymn.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.lckymn.com</link>
	<description>IT, Java, Ubuntu, Linux</description>
	<lastBuildDate>Sun, 14 Apr 2013 12:01:21 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Git: Push to / Pull from Both Github and Bitbucket</title>
		<link>http://blog.lckymn.com/2013/03/11/git-push-to-pull-from-both-github-and-bitbucket/</link>
		<comments>http://blog.lckymn.com/2013/03/11/git-push-to-pull-from-both-github-and-bitbucket/#comments</comments>
		<pubDate>Sun, 10 Mar 2013 23:13:13 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Development Tools]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Bitbucket]]></category>
		<category><![CDATA[Github]]></category>
		<category><![CDATA[Pull]]></category>
		<category><![CDATA[Push]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=912</guid>
		<description><![CDATA[<p>Both Github and Bitbucket are good SCM hosting services. For some reason, you probably want to migrate your project from Github to Bitbucket or vice versa. It&#8217;s easy because you just need to change the remote repository info. Sometimes, you want to keep your code in both places which means you want to push it to both Github and Bitbucket.</p> <p>Pushing to both Github and Bitbucket is easy.</p> <p>Here is a project cloned from Github. If you check out the <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2013/03/11/git-push-to-pull-from-both-github-and-bitbucket/">Git: Push to / Pull from Both Github and Bitbucket</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>Both Github and Bitbucket are good SCM hosting services. For some reason, you probably want to migrate your project from Github to Bitbucket or vice versa. It&#8217;s easy because you just need to change the remote repository info.  Sometimes, you want to keep your code in both places which means you want to push it to both Github and Bitbucket.</p>
<p>Pushing to both Github and Bitbucket is easy.</p>
<p>Here is a project cloned from Github. If you check out the remote repository info, it has only Github repo info.</p>
<p></p><pre class="crayon-plain-tag">$ git remote -v show 
origin  git@github.com:YOUR_USERNAME/YOUR_PROJECT.git (fetch)
origin  git@github.com:YOUR_USERNAME/YOUR_PROJECT.git (push)</pre><p></p>
<p>The <code>YOUR_PROJECT/.git/config</code> file, of course, has only Github info.</p>
<p></p><pre class="crayon-plain-tag">[remote &quot;origin&quot;]
  fetch = +refs/heads/*:refs/remotes/origin/*
  url = git@github.com:YOUR_USERNAME/YOUR_PROJECT.git</pre><p>To add a remote git repository on Bitbucket, use <code>git remote set-url</code>.</p>
<p></p><pre class="crayon-plain-tag">$ git remote set-url origin --add ssh://git@bitbucket.org/YOUR_USERNAME/your_project.git</pre><p></p>
<p>Now, it has Bitbucket info too.</p>
<p></p><pre class="crayon-plain-tag">$ git remote -v show 
origin  git@github.com:YOUR_USERNAME/YOUR_PROJECT.git (fetch)
origin  git@github.com:YOUR_USERNAME/YOUR_PROJECT.git (push)
origin  ssh://git@bitbucket.org/YOUR_USERNAME/your_project.git (push)</pre><p></p>
<p><code>YOUR_PROJECT/.git/config</code></p><pre class="crayon-plain-tag">[remote &quot;origin&quot;]
  fetch = +refs/heads/*:refs/remotes/origin/*
  url = git@github.com:YOUR_USERNAME/YOUR_PROJECT.git
  url = ssh://git@bitbucket.org/YOUR_USERNAME/your_project.git</pre><p></p>
<p>Now, run <code>git push -u origin master</code> to set upstream.</p><pre class="crayon-plain-tag">$ git push -u origin master</pre><p></p>
<p>It&#8217;s enough for pushing to both Github and Bitbucket. So once it&#8217;s done, you can just do</p><pre class="crayon-plain-tag">$ git push</pre><p>Whenever you want to push to both.</p>
<p>e.g.)<br />
Make some changes, Commit and Push</p><pre class="crayon-plain-tag"># Add all changes
$ git add -A

# Commit changes
$ git commit -m &quot;added: .gitignore&quot;
[master 0e649a6] added: .gitignore
 1 file changed, 1 insertion(+)
 create mode 100644 .gitignore

# Push to Github and Bitbucket
$ git push
Counting objects: 4, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 286 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To git@github.com:YOUR_USERNAME/YOUR_PROJECT.git
   a24a46c..0e649a6  master -&gt; master
Counting objects: 4, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 286 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: bb/acl: YOUR_USERNAME is allowed. accepted payload.
To ssh://git@bitbucket.org/YOUR_USERNAME/your_project.git
   a24a46c..0e649a6  master -&gt; master</pre><p></p>
<p>If what you need is only to push to Github and Bitbucket then you don&#8217;t need to read this post any further. However, if you also want to pull data from both Github and Bitbucket, it requires a little more extra steps.</p>
<p>Before I show the steps, I need to point out another case that you might want to know. With what I&#8217;ve done here, it fetches the data only from Github when running the <code>git pull</code> command. If what you want is only changing it to make it pull from Bitbucket, it&#8217;s simple. You just need to swap the positions of origin urls in the <code>YOUR_PROJECT/.git/config</code> file.</p>
<p>So change from this</p><pre class="crayon-plain-tag">[remote &quot;origin&quot;]
  fetch = +refs/heads/*:refs/remotes/origin/*
  url = git@github.com:YOUR_USERNAME/YOUR_PROJECT.git
  url = ssh://git@bitbucket.org/YOUR_USERNAME/your_project.git</pre><p>to</p><pre class="crayon-plain-tag">[remote &quot;origin&quot;]
  fetch = +refs/heads/*:refs/remotes/origin/*
  url = ssh://git@bitbucket.org/YOUR_USERNAME/your_project.git
  url = git@github.com:YOUR_USERNAME/YOUR_PROJECT.git</pre><p></p>
<p>Now it pulls from Bitbucket instead of Github.</p>
<p>To pull from both Github and Bitbucket, first add the remote repository information using <code>git remote</code>.</p><pre class="crayon-plain-tag">$ git remote add github git@github.com:YOUR_USERNAME/YOUR_PROJECT.git 
$ git remote add bitbucket git@bitbucket.org:YOUR_USERNAME/your_project.git</pre><p></p>
<p>You can add both Github and Bitbucket or just the one that is not pulled when running <code>git pull</code>. It&#8217;s all up to you.<br />
Now, the <code>YOUR_PROJECT/.git/config</code> file contains the information of the new remote repositories just added.</p>
<p></p><pre class="crayon-plain-tag">$ git remote -v show 
bitbucket git@bitbucket.org:YOUR_USERNAME/your_project.git (fetch)
bitbucket git@bitbucket.org:YOUR_USERNAME/your_project.git (push)
github  git@github.com:YOUR_USERNAME/YOUR_PROJECT.git (fetch)
github  git@github.com:YOUR_USERNAME/YOUR_PROJECT.git (push)
origin  git@github.com:YOUR_USERNAME/YOUR_PROJECT.git (fetch)
origin  git@github.com:YOUR_USERNAME/YOUR_PROJECT.git (push)
origin  ssh://git@bitbucket.org/YOUR_USERNAME/your_project.git (push)</pre><p></p>
<p><code>YOUR_PROJECT/.git/config</code> now has &#8220;github&#8221; and &#8220;bitbucket&#8221; as well as &#8220;origin&#8221;.</p><pre class="crayon-plain-tag">[remote &quot;origin&quot;]
  fetch = +refs/heads/*:refs/remotes/origin/*
  url = git@github.com:YOUR_USERNAME/YOUR_PROJECT.git
  url = ssh://git@bitbucket.org/YOUR_USERNAME/your_project.git

[remote &quot;github&quot;]
  url = git@github.com:YOUR_USERNAME/YOUR_PROJECT.git
  fetch = +refs/heads/*:refs/remotes/github/*
[remote &quot;bitbucket&quot;]
  url = git@bitbucket.org:YOUR_USERNAME/your_project.git
  fetch = +refs/heads/*:refs/remotes/bitbucket/*</pre><p></p>
<p>If you run <code>git pull</code>, it still pulls from only Github so you need to also run <code>git pull bitbucket master</code>.</p>
<p>* pull from Github</p><pre class="crayon-plain-tag">$ git pull</pre><p>or</p><pre class="crayon-plain-tag">$ git pull github master</pre><p></p>
<p>* pull from Bitbucket</p><pre class="crayon-plain-tag">$ git pull bitbucket master</pre><p></p>
<p>If you want to pull it from all the remote repositories, you can use a function in shell script.</p>
<p>Add the following function to <code>.bash_aliases</code> or <code>.bashrc</code> or <code>.profile</code> depending on your OS (sorry Windows users).</p><pre class="crayon-plain-tag">gitpullall()
{
  repos_to_ignore=&quot;origin github&quot;
  should_ignore=-1

  echo &quot;running: git pull&quot;
  git pull
  echo &quot;&quot;

  for remote in `git remote`
    do

    for ignore in $repos_to_ignore
      do
        [ &quot;$remote&quot; == &quot;$ignore&quot; ] &amp;&amp; should_ignore=1 || :
    done

    if [ &quot;$should_ignore&quot; == &quot;-1&quot; ]
      then
      echo &quot;running: git pull $remote master&quot;
      git pull $remote master
      echo &quot;&quot;
    fi
  done
}</pre><p></p>
<p>Then you can simply run <code>gitpullall</code> to pull from all the remote repositories specified in the <code>YOUR_PROJECT/.git/config</code> file.</p>
<p>To ignore repositories when pulling, add the remote repository names to the <code>repos_to_ignore</code> variable in the <code>gitpullall</code> function above.</p>
<p></p><pre class="crayon-plain-tag">$ gitpullall 

running: git pull
Already up-to-date.

running: git pull bitbucket master
From bitbucket.org:YOUR_USERNAME/your_project
 * branch            master     -&gt; FETCH_HEAD
Already up-to-date.</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2013/03/11/git-push-to-pull-from-both-github-and-bitbucket/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Generics: Generics in Real Life Programming</title>
		<link>http://blog.lckymn.com/2012/12/06/java-generics-generics-in-real-life-programming/</link>
		<comments>http://blog.lckymn.com/2012/12/06/java-generics-generics-in-real-life-programming/#comments</comments>
		<pubDate>Thu, 06 Dec 2012 09:11:17 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[API Design]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mine]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Good API]]></category>
		<category><![CDATA[KommonLee]]></category>
		<category><![CDATA[Library]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=826</guid>
		<description><![CDATA[<p>It is surprising to see that there are still many people who do not use generics even when they are using JDK 5 or higher. I can often see it especially when I teach some Java programming subjects at uni. Generics can be very useful and I use it a lot in my libraries and projects. So I&#8217;d like to talk about generics but not a basic knowledge of it. I will talk about Java generics in real life programming <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2012/12/06/java-generics-generics-in-real-life-programming/">Java Generics: Generics in Real Life Programming</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>It is surprising to see that there are still many people who do not use generics even when they are using JDK 5 or higher.  I can often see it especially when I teach some Java programming subjects at uni.  Generics can be very useful and I use it a lot in my libraries and projects.  So I&#8217;d like to talk about generics but not a basic knowledge of it.  I will talk about Java generics in real life programming and how it can be useful as well as some unusual cases may occur and annoy you.  I am also going to explain some common cases of generics usage in my next post that I have plan to write soon (hopefully).  Then I&#8217;m going to write about more complex cases in the sense that it&#8217;s complex when it&#8217;s designed but rather simple when it&#8217;s used, and it&#8217;s also more practical.  It means I&#8217;ll probably write two more posts about generics so stay tuned if you&#8217;re interested.</p>
<p>Before I start to talk about usefulness of it, let&#8217;s start with problems that can happen if you don&#8217;t use generics when using generified types.<br />
If your code looks like this, you&#8217;re making your code error-prone.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
List list = new ArrayList();
</pre>
<p>As it discards all the generic type information in the class.  To see what exactly happens, better take a look at some example.</p>
<p>If you have type like</p>
<pre class="brush: java; title: ; notranslate">
public class SomeType&lt;T&gt;
{
  public &lt;E&gt; void test(final Collection&lt;E&gt; collection)
  {
    for (final E object : collection)
    {
      System.out.println(&quot;E: &quot; + object);
    }
  }

  public void test(final Set&lt;T&gt; set)
  {
    for (final T t : set)
    {
      System.out.println(&quot;T from set: &quot; + t);
    }
  }

  public void test(final List&lt;Integer&gt; integerList)
  {
    int result = 0;
    for (final Integer integer : integerList)
    {
      result += integer.intValue();
    }
    System.out.println(&quot;result: &quot; + result);
  }
}
</pre>
<p>and execute code like</p>
<pre class="brush: java; title: ; notranslate">
final SomeType someType = new SomeType();
final List&lt;String&gt; list = Arrays.asList(&quot;some&quot;, &quot;test&quot;, &quot;value&quot;);
someType.test(list);
</pre>
<p>Then you will get <code>ClassCastException</code> saying &#8220;<code>java.lang.String cannot be cast to java.lang.Integer</code>&#8221; in runtime but no errors in compile-time.  Why? because it uses <code>public void test(final List&lt;Integer> integerList)</code> method instead of <code>public &lt;E> void test(final Collection&lt;E> collection)</code>. But why does it use the one taking <code>List</code> of <code>Integer</code> instead of the one with the <code>Collection</code> of some type <code>E</code> when the passed parameter is a <code>List</code> of <code>String</code> which is a <code>Collection</code> of some type <code>E</code>, in this case, <code>String</code>?  The reason is that <code>SomeType</code> is generified but when using it, no generics are used.  If generified type is used without generic type info specified, the Java compiler makes it like the old type in JDK prior to 5.0 which doesn&#8217;t have generics.</p>
<p>Thus, the methods above all become like</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
  public void test(final Collection collection)

  public void test(final Set set)

  public void test(final List integerList)
</pre>
<p>So the closest type matched with a List of String is a <code>List</code> and that&#8217;s why <code>public void test(final List&lt;Integer> integerList)</code> is called.  But the method, <code>public &lt;E> void test(final Collection&lt;E> collection)</code>, has nothing to do with the generic type specified in the class <code>SomeType&lt;T></code>. It&#8217;s just a generic method and the <code>E</code> has nothing to do with the <code>T</code>.  Yeah, but if the type is generified, yet no generic type is specified when it is used, all the generics info including the ones in the generic methods is gone.</p>
<p>To solve the problem, you just need to specify the generic type.  In the case above, you can even use just &#8216;<code>?</code>&#8216; (wildcard) since you&#8217;re not using the generic type specified in the class but the generic method, <code>public &lt;E> void test(final Collection&lt;E> collection)</code>.</p>
<pre class="brush: java; title: ; notranslate">
final SomeType&lt;?&gt; someType = new SomeType&lt;Object&gt;();
final List&lt;String&gt; list = Arrays.asList(&quot;some&quot;, &quot;test&quot;, &quot;value&quot;);
someType.test(list);
</pre>
<p>Now, with generics, you don&#8217;t have the problem you had before without generics.</p>
<p>So, it&#8217;s clear why you should use generics when using generified types. What I just explained is actually not new but well known to most Java programmers.  Now, let&#8217;s talk about some benefits from using generics.</p>
<p>You can avoid a problem that you have with arrays if you use generics.  Arrays of reference types in Java are covariant so you may have a problem like this.</p>
<pre class="brush: java; title: ; notranslate">
  final Integer[] integerArray = { 1, 2, 3, 4, 5 };
  final Object[] objectArray = integerArray;
  objectArray[0] = &quot;test&quot;;
</pre>
<p>There is no compile-time error, yet running this code results in <code>java.lang.ArrayStoreException: java.lang.String</code> when <code>objectArray[0] = "test";</code> is executed.</p>
<p>Unlike arrays, generics are invariant, so if you use generics like,</p>
<pre class="brush: java; title: ; notranslate">
  final List&lt;Integer&gt; integerList = Arrays.asList(1, 2, 3, 4, 5);
  final List&lt;Object&gt; objectList = integerList;
</pre>
<p>You get a compile-time error.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
  final List&lt;Object&gt; objectList = (List&lt;Integer&gt;) integerList; // compile-time error
</pre>
<p>Even this one causes the compile-time error too since a <code>List</code> of <code>Integer</code> is not a subtype of <code>List</code> of <code>Object</code> (In arrays, an <code>Integer</code> array is a subtype of <code>Object</code> array).</p>
<p>On the other hand, you may need to cast it although it happens very occasionally.  Here is an example taken from one of my libraries.<br />
In <a href="http://projects.elixirian.org/kommonlee/wiki/GettingStarted#KommonLeeASM" target="_blank">KommonLee ASM</a>, there is a visitor class, <a href="http://projects.elixirian.org/kommonlee/browser/kommonlee-asm/src/main/java/org/elixirian/kommonlee/asm/analysis/visitor/MethodAnalysisClassVisitor.java?rev=35ed1294703b87011a781d780161cc7bb310a336" target="_blank"><code>MethodAnalysisClassVisitor</code></a>.</p>
<pre class="brush: java; title: ; notranslate">
public class MethodAnalysisClassVisitor&lt;T, M extends Member&gt; extends EmptyVisitor
{
  private final MemberCollector&lt;M&gt; memberCollector;
  private final Class&lt;T&gt; theClass;
  private final Map&lt;M, String[]&gt; memberToParameterNamesMap;

  public MethodAnalysisClassVisitor(final MemberCollector&lt;M&gt; memberCollector, final Class&lt;T&gt; theClass,
      final Map&lt;M, String[]&gt; memberToParameterNamesMap)
  {
    this.memberCollector = memberCollector;
    this.theClass = theClass;
    this.memberToParameterNamesMap = memberToParameterNamesMap;
  }
  // Remainder omitted...
}
</pre>
<p>This visitor collects all the methods / constructors and their parameter names.  Why do I need this kind of tool?  It&#8217;s because I needed to get the parameter names of constructors in a class for one of my libraries, <a href="http://projects.elixirian.org/json-statham" target="_blank">JSON Statham</a>, but there was no easy way to get the parameter names of methods or constructors in Java.  <a href="http://en.wikipedia.org/wiki/Reflection_(computer_programming)" target="_blank">Reflection</a> <a href="http://en.wikipedia.org/wiki/Reflection_(computer_programming)#Java" target="_blank">in Java</a> certainly doesn&#8217;t have this convenience which is, I believe, an integral part for library / framework development although it would be depending on what sort of library it is.  So I had to use <a href="http://en.wikipedia.org/wiki/ObjectWeb_ASM" target="_blank">ASM</a> to get the method parameter names.  I was shocked when I first discovered it.  Anyway, back to the original topic again, the visitor is used by <a href="http://projects.elixirian.org/kommonlee/browser/kommonlee-asm/src/main/java/org/elixirian/kommonlee/asm/analysis/AsmMethodAndConstructorAnalyser.java?rev=014f4eb66c0ca58f6f9acb5eff2bd8490d131c50#L137" target="_blank">AsmMethodAndConstructorAnalyser</a>.</p>
<pre class="brush: java; title: ; notranslate">
public class AsmMethodAndConstructorAnalyser implements MethodAndConstructorAnalyser
{
  // ...

  @Override
  public &lt;T&gt; Map&lt;Constructor&lt;T&gt;, String[]&gt; findConstructorsWithParameterNames(final Class&lt;T&gt; theClass)
      throws IllegalArgumentException
  {
    final Map&lt;Constructor&lt;T&gt;, String[]&gt; constructorToParameterNamesMap = new LinkedHashMap&lt;Constructor&lt;T&gt;, String[]&gt;();

    @SuppressWarnings({ &quot;cast&quot;, &quot;unchecked&quot;, &quot;rawtypes&quot; })
    final Map&lt;Constructor&lt;?&gt;, String[]&gt; map = (Map&lt;Constructor&lt;?&gt;, String[]&gt;) ((Map) constructorToParameterNamesMap);

    getClassReader(theClass).accept(
        new MethodAnalysisClassVisitor&lt;T, Constructor&lt;?&gt;&gt;(constructorCollector, theClass, map), 0);
    return constructorToParameterNamesMap;
  }
  // ...
}
</pre>
<p>I know that the type <code>M</code> defined in the <code>MethodAnalysisClassVisitor</code> is <code>Constructor&lt;T></code> in this particular method as I&#8217;m passing <code>Class&lt;T></code> and want to collect all the constructors in it which are all <code>Constructor&lt;T></code>, yet the Java compiler can&#8217;t figure it out so I get a compile-time error if I just do</p>
<pre class="brush: java; highlight: [4]; title: ; notranslate">
    final Map&lt;Constructor&lt;T&gt;, String[]&gt; constructorToParameterNamesMap = new LinkedHashMap&lt;Constructor&lt;T&gt;, String[]&gt;();

    getClassReader(theClass).accept(
        new MethodAnalysisClassVisitor&lt;T, Constructor&lt;?&gt;&gt;(constructorCollector, theClass, constructorToParameterNamesMap), 0);
</pre>
<p>Therefore, what I did was:<br />
first, cast <code>Map&lt;Constructor&lt;T>, String[]> constructorToParameterNamesMap</code> to a raw type Map then it will lose all the generic type info.<br />
second, I can cast it to <code>Map</code> of any key value pair since the Java compiler erases all the generic types when it&#8217;s compiled.<br />
finally, I ended up having the following lines of code. I had to add <code>@SuppressWarnings({ "cast", "unchecked", "rawtypes" })</code> to make the compiler happy. I could do it because I know the constructors stored in the Map are all Constructors of <code>T</code> type.</p>
<pre class="brush: java; highlight: [2]; title: ; notranslate">
  @SuppressWarnings({ &quot;cast&quot;, &quot;unchecked&quot;, &quot;rawtypes&quot; })
  final Map&lt;Constructor&lt;?&gt;, String[]&gt; map = (Map&lt;Constructor&lt;?&gt;, String[]&gt;) ((Map) constructorToParameterNamesMap);

  getClassReader(theClass).accept(
      new MethodAnalysisClassVisitor&lt;T, Constructor&lt;?&gt;&gt;(constructorCollector, theClass, map), 0);
</pre>
<p>This doesn&#8217;t happen often though.  So most of the time, you don&#8217;t need to do it and can enjoy type safety that generics offer.</p>
<p>Along with the benefit I mentioned above with the case compared with arrays, generics offer convenience of postponing specifying the type information until it is used with compile-time type safety.  One example that everyone knows is Java&#8217;s collections framework.  The programmer of collections didn&#8217;t know what types would be stored in the collections when it was created, thus when it came out, it stored just an object type as there were no generics.  This is the part where Java loses static typing although it&#8217;s a static type language.  However, after introduction of generics, the users of collections can have compile-time type safety.  Ironically, the collections are one of the most popular examples of how generics can be useful, yet according to <a href="http://www.gafter.com/~neal" target="_blank">Neal Gafter</a>, it&#8217;s one of the most important reasons why generics are implemented using type erasure and wild-card, which make generics more complex.  If you&#8217;re interested in it, you&#8217;d better watch <a href="http://www.infoq.com/presentations/neal-gafter-evolving-java" target="_blank">his presentation</a>.</p>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
Although Generics were introduced in JDK 5.0, the GJ compiler that can handle generics were introduced much earlier in JDK 1.3 but it was disabled according to the Java language specification.
</div>
<p>Generics give us compile-time type safety but it&#8217;s compile-time only because, as I just mentioned, it does type erasure which means the compiler removes all the generic type information when it compiles, and that&#8217;s why we can&#8217;t create a generic type object or array like.</p>
<pre class="brush: java; title: ; notranslate">
T t = new T();
T[] t = new T[10];
</pre>
<p>This is impossible in Java and that&#8217;s why you don&#8217;t see method like <code>E[] toArray()</code> but <code>Object[] toArray()</code> and <code>&lt;T> T[] toArray(T[] a)</code> in the Collection class and its sub classes.  You can create an array of E type if an instance of array of E is given as a parameter value.  For example,</p>
<pre class="brush: java; title: ; notranslate">
public &lt;E&gt; E[] copyArray(final E[] array)
{
  @SuppressWarnings(&quot;unchecked&quot;)
  final E[] copiedArray = (E[]) Array
                          .newInstance(array
                                        .getClass()
                                        .getComponentType(),
                                      array.length);
  System.arraycopy(array, 0, copiedArray, 0, array.length);
  return copiedArray;
}
</pre>
<p>It takes an array of E object then creates a new array object of E then copies all the elements in the given one to the new one then returns it.</p>
<p>How is it possible? It&#8217;s possible because now I&#8217;m dealing with an &#8216;array object&#8217; of <code>E</code> type not the generic type <code>E</code> directly so I can get the class of the array object in order to take the component type of the element stored in the array.  So first, get the class of <code>E[]</code> &#8216;object&#8217; (not class) which is a parameter value and given in runtime, then I can get the component type of it.  However, the following case is impossible.</p>
<pre class="brush: java; highlight: [11]; title: ; notranslate">
public &lt;E, NE, F extends Function1&lt;E, NE&gt;&gt; NE[] apply(final F function, final E[] source)
{
  final List&lt;NE&gt; list = new ArrayList&lt;NE&gt;();
  for (final E element : source)
  {
    list.add(function.apply(element));
  }
  @SuppressWarnings(&quot;unchecked&quot;)
  final NE[] resultArray = list.toArray(
      (NE[]) Array
          .newInstance(NE[].class // &lt;- compile time error here: Illegal class literal for the type parameter NE!!!
                      .getComponentType(),
                       list.size()));
  return resultArray;
}
</pre>
<p>Because there is no such thing as an <code>NE[]</code> &#8216;class&#8217; (not object), there is no way to get the class.  When it&#8217;s compiled, <code>NE[]</code> becomes an Object array (<code>Object[]</code>).</p>
<p>I used to hate this type erasure as I had some issues when I developed my libraries.  However, I do not anymore.  It&#8217;s not just because of the reason mentioned <a href="http://java.dzone.com/articles/questioning-reality-generics" target="_blank">here</a>.  I have mine and will explain it later in this post.</p>
<p>So let me talk about why we use generics again.  We use it to have compile-time type safety without having to decide the type when designing the API.  One example can be found in my old post about <a href="http://blog.lckymn.com/2011/09/11/easier-and-better-way-to-use-jdbc/#use-generics" target="_blank">Easier and Better Way to Use JDBC</a>.  Simply, it makes use of callback function object much more useful.</p>
<p>Let&#8217;s say you want to map a type stored in a <code>List</code> to some other type. If you don&#8217;t use generics, you probably need to make a method for each mapped type like</p>
<pre class="brush: java; title: ; notranslate">
public List&lt;BigDecimal&gt; takePricesOf(List&lt;Product&gt; list)
{
  List&lt;BigDecimal&gt; newList = new ArrayList&lt;BigDecimal&gt;();
  for (Product product : list)
  {
    newList.add(product.getPrice());
  }
  return newList;
}

public List&lt;DiscountedProduct&gt; toDiscountedProducts(int discountRate, List&lt;Product&gt; list)
{
  List&lt;DiscountedProduct&gt; newList = new ArrayList&lt;DiscountedProduct&gt;();
  for (Product product : list)
  {
    newList.add(new DiscountedProduct(product, discountRate));
  }
  return newList;
}

// and more...
</pre>
<p>(OK, here are actually generics used but it&#8217;s only for using List).</p>
<p>It can become one reusable method with some callback function object like.</p>
<pre class="brush: java; title: ; notranslate">
public interface Mapper
{
  Object map(Object input);
}
</pre>
<pre class="brush: java; title: ; notranslate">
public List&lt;Object&gt; mapWithoutGenerics(Mapper mapperWithoutGenerics, List&lt;?&gt; list) // &lt;- this cannot be List&lt;Object&gt; since you want to pass a List of any type not just List&lt;Object&gt;.
{
  List&lt;Object&gt; newList = new ArrayList&lt;Object&gt;();
  for (Object object : list)
  {
    newList.add(mapperWithoutGenerics.map(object));
  }
  return newList;
}
</pre>
<p>When you use it.</p>
<pre class="brush: java; title: ; notranslate">
List&lt;Object&gt; productPriceList = mapWithoutGenerics(new Mapper() {
  public Object map(Object input)
  {
    Product product = (Product) input;
    return product.getPrice();
  }
}, productList);
</pre>
<p>Now, you don&#8217;t have compile-time type safety anymore so you may pass a <code>List</code> of any type.<br />
So the following code doesn&#8217;t cause any compile-time error but the runtime exception that is <code>java.lang.ClassCastException</code>.</p>
<pre class="brush: java; highlight: [4,7]; title: ; notranslate">
List&lt;Object&gt; productPriceList = mapWithoutGenerics(new Mapper() {
  public Object map(Object input)
  {
    Product product = (Product) input;
    return product.getPrice();
  }
}, Arrays.asList(&quot;Some&quot;, &quot;String&quot;, &quot;List&quot;));
</pre>
<p>&nbsp;</p>
<p>It can surely become much better with generics.</p>
<pre class="brush: java; title: ; notranslate">
public interface Function1&lt;T, R&gt;
{
  R apply(T input);
}
</pre>
<pre class="brush: java; title: ; notranslate">
public &lt;T, R, F extends Function1&lt;T, R&gt;&gt; List&lt;R&gt; map(F mapper, List&lt;T&gt; list)
{
  final List&lt;R&gt; newList = new ArrayList&lt;R&gt;();
  for (final T t : list)
  {
    newList.add(mapper.apply(t));
  }
  return newList;
}
</pre>
<p>Then when you use it.</p>
<pre class="brush: java; title: ; notranslate">
final List&lt;BigDecimal&gt; productPriceList = map(new Function1&lt;Product, BigDecimal&gt;() {
  @Override
  public BigDecimal apply(final Product product)
  {
    return product.getPrice();
  }
}, productList);
</pre>
<p>Or the function object can be reused.</p>
<pre class="brush: java; title: ; notranslate">
private static final Function1&lt;Product, BigDecimal&gt; PRODUCT_TO_PRICE_MAPPER = new Function1&lt;Product, BigDecimal&gt;() {
  @Override
  public BigDecimal apply(final Product product)
  {
    return product.getPrice();
  }
};

//...

final List&lt;BigDecimal&gt; productPriceList        = map(PRODUCT_TO_PRICE_MAPPER, productList);
final List&lt;BigDecimal&gt; anotherProductPriceList = map(PRODUCT_TO_PRICE_MAPPER, anotherProductList);
</pre>
<p>The other method that is <code>toDiscountedProducts()</code> can be done with this generic map method and <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" target="_blank">closure</a>.</p>
<pre class="brush: java; highlight: [1,7]; title: ; notranslate">
final int discountRate = 15;

final List&lt;DiscountedProduct&gt; discountedProductList = map(new Function1&lt;Product, DiscountedProduct&gt;() {
  @Override
  public DiscountedProduct apply(final Product product)
  {
    return new DiscountedProduct(product, discountRate);
  }
}, productList);
</pre>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
Although Java doesn&#8217;t really have closure, the Function1 above is used as a closure because it&#8217;s accessing a non-local variable, and in almost all the cases when people say that Java doesn&#8217;t have closure, they actually mean a way to support <a href="http://en.wikipedia.org/wiki/First-class_function" target="_blank">first-class functions</a> (e.g. <a href="http://openjdk.java.net/projects/lambda" target="_blank">lambda expression to support first-class functions in Java</a>).
</div>
<p>Speaking of generics used for collections, I should point out that it would have been much more useful, <b>if</b> the collections had got methods like select (or filter), map, etc.</p>
<p>So if you had got a List of Integer and wanted to get all the positive ones, you would have done like.</p>
<pre class="brush: java; title: ; notranslate">
List&lt;Integer&gt; positiveIntegerList = integerList.select(new Condition1&lt;Integer&gt;() {
  public boolean isMet(Integer integer)
  {
    return 0 &lt; integer.intValue();
  }
});
</pre>
<p>Or getting all the prices from the List of Product object as I already showed.  Unfortunately Java&#8217;s Collections don&#8217;t have those methods.  Well, my collection library has it, but it&#8217;s incomplete and not so compatible with existing code using Java&#8217;s collections although it has a way to convert from and to Java ones.  So to keep using Java&#8217;s collections, I made some helper methods to achieve the goal which is having one generic method to apply different kinds of functions to all the elements in the collections.  By the way, why do I bother about it?  Can&#8217;t I just use <code>for</code> or <code>foreach</code> loop?  Sure, I can. So why?  With the generic methods mentioned above and function objects, I can focus on the actual problems.  For instance, to get all the prices from the list of Product, my concern should be getting the price of each Product not how to use <code>for</code> or <code>foreach</code> loop.</p>
<p>Here, I need to worry about using foreach and creating <code>ArrayList</code>.</p>
<pre class="brush: java; title: ; notranslate">
List&lt;BigDecimal&gt; productPriceList = new ArrayList&lt;BigDecimal&gt;();
for (Product product : productList)
{
  productPriceList.add(product.getPrice());
}
</pre>
<p>With the generic one (if there were one), I wouldn&#8217;t.</p>
<pre class="brush: java; title: ; notranslate">
List&lt;BigDecimal&gt; productPriceList = productList.map(new Function1&lt;Product, BigDecimal&gt;() {
  public BigDecimal apply(Product product)
  {
    return product.getPrice(); // &lt;- here I'm focusing on getting the price.
  }
});
</pre>
<p>Since Java doesn&#8217;t support first-class function, the syntax is not so pleasant.  However, JDK 8 will have lambda expression to support it so when it comes out, it can probably be like.</p>
<pre class="brush: java; title: ; notranslate">
List&lt;BigDecimal&gt; productPriceList = productList.map((product) -&gt; product.getPrice());
// It hasn't been finalised yet so the syntax can be different.
</pre>
<p>Anyway, Java collections still don&#8217;t have those methods so, as I said already, I made the ones for the collections.  So let me talk about one of these that is <code>Selector</code>.  What <code>Selector</code> does is checking all the elements in a collection and takes only the ones that meet the given <code>Condition</code>.  I wanted to have only one Selector that can easily deal with all the classes extends <code>Collection</code> instead of having one for each (e.g. <code>ListToArrayListSelector</code>, <code>ListToHashSetSetSelector</code>, <code>SetToListSelector</code>, and so on). Thus I made it like this.</p>
<pre class="brush: java; title: ; notranslate">
public class IterableToCollectionSelector&lt;E, T extends Iterable&lt;? extends E&gt;, C extends Condition1&lt;? super E&gt;, R extends Collection&lt;E&gt;&gt;
    implements Selector1&lt;T, C, R&gt;
{
  @Override
  public R select(final C condition, final T source)
  {
    final R result = // &lt;- How can I get the Collection instance of R?
    for (final E element : source)
    {
      if (condition.isMet(element))
      {
        result.add(element);
      }
    }
    return result;
  }
}
</pre>
<p>Here are <a href="http://projects.elixirian.org/kommonlee/browser/kommonlee-core/src/main/java/org/elixirian/kommonlee/type/functional/Condition1.java" target="_blank">Condition1</a> and <a href="http://projects.elixirian.org/kommonlee/browser/kommonlee-core/src/main/java/org/elixirian/kommonlee/type/selector/Selector1.java" target="_blank">Selector1</a> in my library.</p>
<pre class="brush: java; title: ; notranslate">
public interface Condition1&lt;T&gt;
{
  boolean isMet(T input);
}
</pre>
<pre class="brush: java; title: ; notranslate">
public interface Selector1&lt;T, C, R&gt;
{
  R select(C condition, T source);
}
</pre>
<p>Let me explain it step by step. First,</p>
<pre class="brush: java; title: ; notranslate">
public class IterableToCollectionSelector&lt;E, T extends Iterable&lt;? extends E&gt;, C extends Condition1&lt;? super E&gt;, R extends Collection&lt;E&gt;&gt;
    implements Selector1&lt;T, C, R&gt;
</pre>
<dl>
<dt><code>E</code></dt>
<dd><code>E</code> is a type of an element stored in the given collection.</dd>
<dt><code>T</code></dt>
<dd>
<p><code>T</code> is any type extends Iterable of the type extends E.</p>
<ol>
<li> Why is it <code>Iterable</code> of any type extends <code>E</code> (<code>? extneds E</code>)? Otherwise, you can&#8217;t use a <code>List</code> of any sub type of <code>E</code>.<br />
  It would be easier to understand with an example. Let&#8217;s say you need to get a List of Product the price of which is greater than 50 dollars.  If it&#8217;s just <code>Iterable&lt;E></code> then you have no problem with passing a List of Product yet you do have when you try to pass a <code>List</code> of <code>DiscountedProduct</code> which is a sub class of <code>Product</code> and it should be perfectly valid to pass it as a parameter of the selector made for Product (Think about <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" target="_blank">Liskov substitution principle</a>).<br />
  If you have <code>Iterable&lt;? extends E></code>, you can pass <code>E</code> type and any sub-types of <code>E</code>, in this case, <code>Product</code> and <code>DiscountedProduct</code> are all fine.</li>
<li>
<p>Then why <code>T extends Iterable</code>? Can I just have <code>Iterable</code> for the input type then I can remove the generic type <code>T</code>?  Yes, it&#8217;s OK, but what if there is anyone who wants to extends this class and wants to restrict the input type to only List instead of any sub-type of Iterable (probably if you care about <a href="http://en.wikipedia.org/wiki/Open/closed_principle" target="_blank">Open/closed principle</a>)?<br />
      If you have a class like this.</p>
<pre class="brush: java; highlight: [3]; title: ; notranslate">
// Notice that T extends Iterable&lt;? extends E&gt; is gone, and it has Iterable&lt;? extends E&gt; instead (No T).
public class IterableToCollectionSelector&lt;E, C extends Condition1&lt;? super E&gt;, R extends Collection&lt;E&gt;&gt; implements
  Selector1&lt;Iterable&lt;? extends E&gt;, C, R&gt;
{
}
</pre>
<p>  You can&#8217;t restrict the input type to something other than <code>Iterable&lt;? extends E></code>, and if you try to override the select method in the sub-class of it.<br />
e.g.)</p>
<pre class="brush: java; highlight: [4,5]; title: ; notranslate">
public class IterableToArrayListSelector&lt;E&gt; extends
  IterableToCollectionSelector&lt;E, Condition1&lt;? super E&gt;, ArrayList&lt;E&gt;&gt;
{
  @Override
  public ArrayList&lt;E&gt; select(final Condition1&lt;? super E&gt; condition, final List&lt;? extends E&gt; source)
  {
    return super.select(condition, source);
  }
}
</pre>
<p>You will get a compile-time error because <code>T</code> is not the same as &#8220;<code>? extends T</code>&#8220;. In this case, &#8220;<code>Iterable&lt;? extends E></code>&#8221; specified as a generic type <code>T</code> for the <code>Selector1&lt;T, C, R></code> is not the same as &#8220;<code>? extends T</code>&#8221; that is, in here, <code>List&lt;? extends E></code> (one of &#8220;<code>T extends Iterable&lt;? extends E></code>&#8220;) in the overridden method <code>select()</code> (It&#8217;s not actually overridden as <code>List&lt;? extends E></code> can&#8217;t be a substitute for <code>Iterable&lt;? extends E></code> here).  Still not sure why <code>List</code> can&#8217;t be used? Well, think about this. <code>List&lt;String></code> is not the same as and can&#8217;t be a substitute for <code>List&lt;Object></code>.  You know it, and I already explained it earlier when I talked about the side-effect of using arrays.  Then think about this one.  Can <code>List&lt;List&lt;?>></code> be a substitute for <code>List&lt;Iterable&lt;?>></code>? No, it&#8217;s just like <code>List&lt;String></code> and <code>List&lt;Object></code>, and the problem we have here is the same.</p>
<p>  So</p>
<pre class="brush: java; title: ; notranslate">
public class IterableToCollectionSelector&lt;E, T extends Iterable&lt;? extends E&gt;, C extends Condition1&lt;? super E&gt;, R extends Collection&lt;E&gt;&gt;
  implements Selector1&lt;T, C, R&gt;
</pre>
<p>  gives me freedom to restrict the input iterable to whatever extends Iterable I want.<br />
e.g.)</p>
<pre class="brush: java; title: ; notranslate">
public class IterableToArrayListSelector&lt;E&gt; extends
    IterableToCollectionSelector&lt;E, List&lt;? extends E&gt;, Condition1&lt;? super E&gt;, ArrayList&lt;E&gt;&gt;
</pre>
<p>There will be a compile-time error when passing a Set instead of a List for the input value of the select() method.</p>
</li>
</ol>
</dd>
<dt>
    <code>C extends Condition1&lt;? super E></code>
  </dt>
<dd>
    Next one is <code>C extends Condition1&lt;? super E></code>. What? Why is the input type of the <code>Condition1</code> &#8220;<code>? super E</code>&#8220;?  Because, with &#8220;<code>? super E</code>&#8220;, I can have one <code>Condition1</code> object for many sub-types of the type <code>E</code>.  Imagine that you want to get a <code>List</code> of <code>Product</code> the price of which is greater than 20, you can have a <code>Condition1</code> for <code>Product</code>, then if you also need to get a <code>List</code> of <code>DiscountedProduct</code> the price of which is also greater than 20, you can reuse that <code>Condition1</code> object for it as <code>DiscountedProduct</code> is a sub-type of <code>Product</code> which means <code>Condition1&lt;Product></code> is a kind of <code>Condition1&lt;? super DiscountedProduct></code>.  If I have &#8220;<code>C extends Condition1&lt;E></code>&#8221; then I can&#8217;t do that, but because it&#8217;s &#8220;<code>C extends Condition1&lt;? super E></code>&#8220;, I can.
  </dd>
<dt>
    <code>R</code>
  </dt>
<dd>
    The last one is <code>R</code>.  <code>R extends Collection&lt;E></code> so it can be any sub-type of Collection.
  </dd>
</dl>
<p>Now let&#8217;s look at the method. Here I have some problem.</p>
<pre class="brush: java; highlight: [3]; title: ; notranslate">
  public R select(final C condition, final T source)
  {
    final R result = // &lt;- How can I get the Collection instance of R???
    for (final E element : source)
    {
      if (condition.isMet(element))
      {
        result.add(element);
      }
    }
    return result;
  }
</pre>
<p>If it&#8217;s one type of <code>Collection</code>, I can easily create it but it&#8217;s not determined yet.  It will be set when it&#8217;s used. Then why don&#8217;t I postpone instantiation of it until it&#8217;s used.  More precisely when the selector is instantiated.  So I just create another type to create one of <code>Collection</code> also using generics.</p>
<pre class="brush: java; title: ; notranslate">
public interface CollectionCreator&lt;E, T extends Collection&lt;? extends E&gt;&gt;
{
  T createCollection();
}
</pre>
<p>So it can be used to create any sub-types of Collection.<br />
e.g.) for ArrayList</p>
<pre class="brush: java; title: ; notranslate">
public class ArrayListCreator&lt;E&gt; implements CollectionCreator&lt;E, ArrayList&lt;E&gt;&gt;
{
  @Override
  public ArrayList&lt;E&gt; createCollection()
  {
    return new ArrayList&lt;E&gt;();
  }
}
</pre>
<p>for HashSet</p>
<pre class="brush: java; title: ; notranslate">
public class HashSetCreator&lt;E&gt; implements CollectionCreator&lt;E, HashSet&lt;E&gt;&gt;
{
  @Override
  public HashSet&lt;E&gt; createCollection()
  {
    return new HashSet&lt;E&gt;();
  }
}
</pre>
<p>With all these, the final version of <code>IterableToCollectionSelector</code> is</p>
<pre class="brush: java; title: ; notranslate">
public class IterableToCollectionSelector&lt;E, T extends Iterable&lt;? extends E&gt;, C extends Condition1&lt;? super E&gt;, R extends Collection&lt;E&gt;&gt;
    implements Selector1&lt;T, C, R&gt;
{
  private final CollectionCreator&lt;E, ? extends R&gt; collectionCreator;

  public &lt;CC extends CollectionCreator&lt;E, ? extends R&gt;&gt; IterableToCollectionSelector(final CC collectionCreator)
  {
    this.collectionCreator = collectionCreator;
  }

  @Override
  public R select(final C condition, final T source)
  {
    final R result = collectionCreator.createCollection();
    for (final E element : source)
    {
      if (condition.isMet(element))
      {
        result.add(element);
      }
    }
    return result;
  }
}
</pre>
<p>It needs to have <code>CollectionCreator</code> but it&#8217;s immutable so I don&#8217;t need to worry about the state of the selector object once it&#8217;s created.</p>
<p>When <code>IterableToCollectionSelector</code> is used, it looks</p>
<pre class="brush: java; title: ; notranslate">
// selector for the List of Product.
final IterableToCollectionSelector&lt;Product, Iterable&lt;Product&gt;, Condition1&lt;Product&gt;, ArrayList&lt;Product&gt;&gt; collectionSelector =
  new IterableToCollectionSelector&lt;Product, Iterable&lt;Product&gt;, Condition1&lt;Product&gt;, ArrayList&lt;Product&gt;&gt;(new ArrayListCreator());
final List&lt;Product&gt; resultList = collectionSelector.select(greaterThan20, productList);

// selector for the List of DiscountedProduct
final IterableToCollectionSelector&lt;DiscountedProduct, Iterable&lt;DiscountedProduct&gt;, Condition1&lt;Product&gt;, ArrayList&lt;DiscountedProduct&gt;&gt; collectionSelector2 =
  new IterableToCollectionSelector&lt;DiscountedProduct, Iterable&lt;DiscountedProduct&gt;, Condition1&lt;Product&gt;, ArrayList&lt;DiscountedProduct&gt;&gt;(new ArrayListCreator());
final List&lt;DiscountedProduct&gt; resultList2 = collectionSelector2.select(greaterThan20, discountedProductList)
</pre>
<p>Wait, do I have to create the <code>IterableToCollectionSelector</code> whenever I need to use it for a different type?  It seems like it&#8217;s waste of memory and not to mention of boilerplate code. OK, here comes why I don&#8217;t hate generics&#8217; type erasure anymore.  Considering type erasure, both objects, used above, actually have no difference in runtime.</p>
<p>So what I can do is that I can create a helper class containing one really generic <code>IterableToCollectionSelector</code> then cast it using a generic method so that it always returns the same instance but can be used for different types with compile-time type safety.  It would be clear if I just show the code.</p>
<pre class="brush: java; title: ; notranslate">
public class CollectionUtil
{
  private static final IterableToCollectionSelector&lt;?, ? extends Iterable&lt;?&gt;, ? extends Condition1&lt;?&gt;, ? extends ArrayList&lt;?&gt;&gt; ITERABLE_TO_ARRAY_LIST_SELECTOR =
    new IterableToCollectionSelector&lt;Object, Iterable&lt;?&gt;, Condition1&lt;Object&gt;, ArrayList&lt;Object&gt;&gt;(
        new ArrayListCreator&lt;Object&gt;());

  public static &lt;E, T extends Iterable&lt;? extends E&gt;, C extends Condition1&lt;? super E&gt;&gt; IterableToCollectionSelector getIterableToCollectionSelector()
  {
    @SuppressWarnings(&quot;unchecked&quot;)
    final IterableToCollectionSelector&lt;E, T, C, ArrayList&lt;E&gt;&gt; iterableToCollectionSelector =
      (IterableToCollectionSelector&lt;E, T, C, ArrayList&lt;E&gt;&gt;) ITERABLE_TO_ARRAY_LIST_SELECTOR;
    return iterableToCollectionSelector;
  }
}
</pre>
<p>And similarly, <code>ArrayListCreator</code> doesn&#8217;t have to be created more than once.  It doesn&#8217;t have any state so one instance can be and should be reused.</p>
<pre class="brush: java; title: ; notranslate">
public class ArrayListCreator&lt;E&gt; implements CollectionCreator&lt;E, ArrayList&lt;E&gt;&gt;
{
  public static final ArrayListCreator&lt;Object&gt; ARRAY_LIST_CREATOR = new ArrayListCreator&lt;Object&gt;();

  @Override
  public ArrayList&lt;E&gt; createCollection()
  {
    return newArrayList();
  }

  public static &lt;E&gt; ArrayListCreator&lt;E&gt; getInstance()
  {
    @SuppressWarnings(&quot;unchecked&quot;)
    final ArrayListCreator&lt;E&gt; arrayListCreator = (ArrayListCreator&lt;E&gt;) ARRAY_LIST_CREATOR;
    return arrayListCreator;
  }
}
</pre>
<p>So <code>CollectionUtil</code> is rewritten.</p>
<pre class="brush: java; title: ; notranslate">
public class CollectionUtil
{
  private static final IterableToCollectionSelector&lt;?, ? extends Iterable&lt;?&gt;, ? extends Condition1&lt;?&gt;, ? extends ArrayList&lt;?&gt;&gt; ITERABLE_TO_ARRAY_LIST_SELECTOR =
    new IterableToCollectionSelector&lt;Object, Iterable&lt;?&gt;, Condition1&lt;Object&gt;, ArrayList&lt;Object&gt;&gt;(
        ArrayListCreator.getInstance());

  public static &lt;E, T extends Iterable&lt;? extends E&gt;, C extends Condition1&lt;? super E&gt;&gt; IterableToCollectionSelector getIterableToCollectionSelector()
  {
    @SuppressWarnings(&quot;unchecked&quot;)
    final IterableToCollectionSelector&lt;E, T, C, ArrayList&lt;E&gt;&gt; iterableToCollectionSelector =
      (IterableToCollectionSelector&lt;E, T, C, ArrayList&lt;E&gt;&gt;) ITERABLE_TO_ARRAY_LIST_SELECTOR;
    return iterableToCollectionSelector;
  }
}
</pre>
<pre class="brush: java; gutter: false; highlight: [3]; title: ; notranslate">
@SuppressWarnings(&quot;unchecked&quot;)
final IterableToCollectionSelector&lt;E, T, C, ArrayList&lt;E&gt;&gt; iterableToCollectionSelector =
  (IterableToCollectionSelector&lt;E, T, C, ArrayList&lt;E&gt;&gt;) ITERABLE_TO_ARRAY_LIST_SELECTOR;
</pre>
<p>This is possible due to type erasure, so you don&#8217;t have to create many objects of the same type with different generic type info (e.g. instances of the same type, &#8216;<code>IterableToCollectionSelector</code>&#8216;, with &#8216;different generic types&#8217; like different <code>E</code>, <code>T</code>, <code>C</code>) which will be all the same in runtime.  That&#8217;s why I do not hate type erasure anymore.  Of course, you need to <code>@SuppressWarnings</code> to make the compiler quiet, but it&#8217;s not a big deal and I know what I&#8217;m doing.  It&#8217;s perfectly valid.</p>
<p>The condition can be reused.</p>
<pre class="brush: java; title: ; notranslate">
final Condition1&lt;Product&gt; greaterThan20 = new Condition1&lt;Product&gt;() {
  private final BigDecimal twenty = new BigDecimal(&quot;20&quot;);
  @Override
  public boolean isMet(final Product input)
  {
    return 0 &gt; twenty.compareTo(input.getPrice());
  }
};
</pre>
<p>Now I can just do,</p>
<pre class="brush: java; title: ; notranslate">
final IterableToCollectionSelector&lt;Product, Iterable&lt;Product&gt;, Condition1&lt;Product&gt;, ArrayList&lt;Product&gt;&gt; collectionSelectorForProduct =
  CollectionUtil.getIterableToCollectionSelector();
final List&lt;Product&gt; resultForProduct = collectionSelectorForProduct.select(greaterThan20, productList);

final IterableToCollectionSelector&lt;DiscountedProduct, Iterable&lt;DiscountedProduct&gt;, Condition1&lt;Product&gt;, ArrayList&lt;DiscountedProduct&gt;&gt; collectionSelectorForDiscountedProduct =
  CollectionUtil.getIterableToCollectionSelector();
final List&lt;DiscountedProduct&gt; resultForDiscountedProduct = collectionSelectorForDiscountedProduct.select(greaterThan20, discountedProductList);
</pre>
<p>Each time when you get an instance of <code>IterableToCollectionSelector</code> using the <code>getIterableToCollectionSelector()</code> method, you get the same <code>IterableToCollectionSelector</code> instance.</p>
<p>OK, that sounds good but do I really need to know all those complex <code>E</code>, <code>T</code>, <code>C</code>, <code>R</code> and even wildcard like &#8220;<code>? extends E</code>&#8221; or &#8220;<code>? super E</code>&#8220;?  Well, you don&#8217;t have to.  It depends on what you do.  If you&#8217;re a library or framework developer, you should probably.  Otherwise, not really.  The library or API designer should carefully design it to offer APIs that are easy to use and understand for the users of the library.  The designer or architect, on the other hand, should know the things I talked about here to make complex things simple.  That&#8217;s our job, isn&#8217;t it?  Making a complex thing simple then solve it.  Anyway, most of the time, you don&#8217;t need to deal with that kind of complex API if you&#8217;re an application developer.  Your company should have at least one person who can deal with it and he/she should provide easy to use APIs.  If your company doesn&#8217;t have any, ask your boss to hire one. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   Using well designed good APIs can surely save your time which means saving your company&#8217;s money.  Also less error-prone.</p>
<p>So how can the <code>IterableToCollectionSelector</code> be simple so that the users wouldn&#8217;t need to care about <code>E</code>, <code>T</code>, <code>C</code>, etc.</p>
<p>The library designer should create more specific type of selector like</p>
<pre class="brush: java; title: ; notranslate">
public final class IterableToArrayListSelector&lt;E&gt; extends
    IterableToCollectionSelector&lt;E, Iterable&lt;? extends E&gt;, Condition1&lt;? super E&gt;, ArrayList&lt;E&gt;&gt;
{
  IterableToArrayListSelector(final ArrayListCreator&lt;E&gt; collectionCreator)
  {
    super(collectionCreator);
  }
}
</pre>
<p>Then <code>CollectionUtil</code> becomes</p>
<pre class="brush: java; title: ; notranslate">
public class CollectionUtil
{
  private static final IterableToArrayListSelector&lt;?&gt; ITERABLE_TO_ARRAY_LIST_SELECTOR =
    new IterableToArrayListSelector&lt;Object&gt;(ArrayListCreator.getInstance());

  public static &lt;E&gt; IterableToArrayListSelector&lt;E&gt; getIterableToArrayListSelector()
  {
    @SuppressWarnings(&quot;unchecked&quot;)
    final IterableToArrayListSelector&lt;E&gt; iterableToCollectionSelector =
      (IterableToArrayListSelector&lt;E&gt;) ITERABLE_TO_ARRAY_LIST_SELECTOR;
    return iterableToCollectionSelector;
  }
}
</pre>
<p>Now using it is much easier.<br />
(with static import)</p>
<pre class="brush: java; title: ; notranslate">
import static your.package_name.here.CollectionUtil.*;

// ...

final IterableToArrayListSelector&lt;Product&gt; arrayListSelectorForProduct =
  getIterableToArrayListSelector();
final List&lt;Product&gt; resultForProduct = arrayListSelectorForProduct.select(greaterThan20, productList);

final IterableToArrayListSelector&lt;DiscountedProduct&gt; arrayListSelectorForDiscountedProduct =
  getIterableToArrayListSelector();
final List&lt;DiscountedProduct&gt; resultForDiscountedProduct =
  arrayListSelectorForDiscountedProduct.select(greaterThan20, discountedProductList);
</pre>
<p>You may not be satisfied yet, because you have the variables for the <code>IterableToArrayListSelector</code> objects.  Should you have these?  No, you don&#8217;t have to. So you probably try like this.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
final List&lt;Product&gt; resultForProduct = getIterableToArrayListSelector()
                                         .select(greaterThan20, productList);
</pre>
<p>Yet, this doesn&#8217;t work. When <code>getIterableToArrayListSelector()</code> is called there is no generic type info given so it returns just an object of <code>IterableToArrayListSelector&lt;Object></code>.  Thus it causes a compile-time error on calling <code>select(greaterThan20, productList)</code>.</p>
<p>It can be solved by specifying the generic type like.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
final List&lt;Product&gt; resultForProduct2 = CollectionUtil.&lt;Product&gt; getIterableToArrayListSelector()
                                          .select(greaterThan20, productList);
</pre>
<p>It&#8217;s not so elegant though.  It can be solved as well. How? instead of having the <code>getIterableToArrayListSelector()</code> method to get an instance of <code>IterableToArrayListSelector</code>, why don&#8217;t I just create another generic <code>select()</code> method which does both getting the instance and calling the <code>select()</code> method in it.</p>
<p>So <code>CollectionUtil</code> is re-written.</p>
<pre class="brush: java; title: ; notranslate">
public class CollectionUtil
{
  private static final IterableToArrayListSelector&lt;?&gt; ITERABLE_TO_ARRAY_LIST_SELECTOR =
    new IterableToArrayListSelector&lt;Object&gt;(ArrayListCreator.getInstance());

  public static &lt;E, T extends Iterable&lt;? extends E&gt;, C extends Condition1&lt;? super E&gt;&gt; ArrayList&lt;E&gt; select(
      final C condition, final T iterable)
  {
    final IterableToArrayListSelector&lt;E&gt; iterableToCollectionSelector =
      (IterableToArrayListSelector&lt;E&gt;) ITERABLE_TO_ARRAY_LIST_SELECTOR;
    return iterableToCollectionSelector.select(condition, iterable);
  }
}
</pre>
<p>How to use? Really simple.<br />
(also with static import)</p>
<pre class="brush: java; title: ; notranslate">
import static your.package_name.here.CollectionUtil.*;

// ...

final List&lt;Product&gt; resultForProduct = select(greaterThan20, productList);

final List&lt;DiscountedProduct&gt; resultForDiscountedProduct = select(greaterThan20, discountedProduct);
</pre>
<p>So it&#8217;s</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
final IterableToCollectionSelector&lt;Product, Iterable&lt;Product&gt;, Condition1&lt;Product&gt;, ArrayList&lt;Product&gt;&gt; collectionSelectorForProduct =
  getIterableToCollectionSelector();
final List&lt;Product&gt; resultForProduct = collectionSelectorForProduct.select(greaterThan20, productList);
</pre>
<p>VS</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
final List&lt;Product&gt; resultForProduct = select(greaterThan20, productList);
</pre>
<p>As you can see, depending on how you use generics it can give you a really nice, simple and easy to use API.</p>
<p>Just a moment.  It might not be enough.  That select takes an <code>Iterable</code> object and returns an <code>ArrayList</code> object, but what if I want to get <code>HashSet</code> instead, or what about taking an array as an input parameter instead of an <code>Iterable</code> object?  It can be accomplished too, but I&#8217;m not going to explain it here.  I&#8217;ll do it later when I talk about good API design in another post not in the generics series.</p>
<p>In the meantime, you can use what I&#8217;ve already provided in my library that is <a href="http://projects.elixirian.org/kommonlee/wiki/GettingStarted#CollectionUtil" target="_blank">KommonLee</a>.</p>
<p>If you use it, you can simply do</p>
<pre class="brush: java; title: ; notranslate">
final List&lt;Product&gt; anotherPositiveIntegerList = selector()
        .fromIterable()
        .toArrayList()
        .select(greaterThan20, productList);
</pre>
<p>OR</p>
<pre class="brush: java; title: ; notranslate">
final Set&lt;Product&gt; anotherPositiveIntegerList = selector()
        .fromIterable()
        .toHashSet()
        .select(greaterThan20, productList);
</pre>
<p>OR</p>
<pre class="brush: java; title: ; notranslate">
Product[] productArray = // ...
final List&lt;Product&gt; anotherPositiveIntegerList = selector()
        .fromArray()
        .toArrayList()
        .select(greaterThan20, productArray);
</pre>
<p>and so on&#8230;<br />
More examples are <a href="http://goo.gl/AkdcK" target="_blank">&gt;&gt;here&lt;&lt;</a><br />
It also has Mappers and SelectableMappers so you can convert one type stored in a Collection to another.</p>
<p>Also the example code I used here is available on Github. <a href="http://goo.gl/mwM3z" target="_blank">Example Code: CLICK HERE!!!</a></p>
<p>Next post about generics would be about something easier than the selector example.  So it would be some practical but easier, then the final post would be about really complex one when it&#8217;s designed but easy when it&#8217;s used.  It is also very practical and useful.  Unfortunately, however, I can&#8217;t tell when I can write it as I need to think about good examples to explain.  As you can see above, it can be difficult to understand without example code (or even with it, still difficult).  I do actually have some examples but it&#8217;s the code I made for my work so I can&#8217;t just use it. Anyway, I will figure it out so stay tuned.<br />
&nbsp;<br />
&nbsp;</p>
<blockquote class="twitter-tweet tw-align-center"><p>Java Generics: Generics in Real Life Programming &#8211; <a href="http://t.co/wLMJyLCP" title="http://dzone.com/I5lP">dzone.com/I5lP</a> &#8211; @<a href="https://twitter.com/dzone">dzone</a> Big Link by kevinshlee</p>
<p>&mdash; DZone (@DZone) <a href="https://twitter.com/DZone/status/277194720017518592" data-datetime="2012-12-07T23:35:45+00:00">December 7, 2012</a></p></blockquote>
<div style="text-align: center">Thanks for those who retweeted and favorited this post.</div>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2012/12/06/java-generics-generics-in-real-life-programming/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>New Homepage</title>
		<link>http://blog.lckymn.com/2012/12/06/new-homepage/</link>
		<comments>http://blog.lckymn.com/2012/12/06/new-homepage/#comments</comments>
		<pubDate>Wed, 05 Dec 2012 19:29:56 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[JSON Statham]]></category>
		<category><![CDATA[KommonLee]]></category>
		<category><![CDATA[Mine]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[About Me]]></category>
		<category><![CDATA[My Homepage]]></category>
		<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=811</guid>
		<description><![CDATA[<p>I&#8217;ve renovated my homepage.</p> <p>The old one was <div id="attachment_812" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/12/kevin-home-old1.png"><img src="http://blog.lckymn.com/wp-content/uploads/2012/12/kevin-home-old1.png" alt="" title="My homepage - OLD" width="640" height="577" class="size-full wp-image-812" /></a><p class="wp-caption-text">My homepage &#8211; OLD</p></div></p> <p><a href="http://lckymn.com" target="_blank">The new one</a> is <div id="attachment_813" class="wp-caption alignnone" style="width: 781px"><a href="http://lckymn.com" target="_blank"><img src="http://blog.lckymn.com/wp-content/uploads/2012/12/kevin-home-new-1.png" alt="" title="My homepage - New" width="771" height="520" class="size-full wp-image-813" /></a><p class="wp-caption-text">My homepage &#8211; New</p></div> It looks much better in Google Chrome and Firefox than IEs (It doesn&#8217;t work in IE6 at all).</p> <p><a href="http://lckymn.com/kevin-projects.html" target="_blank">My <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2012/12/06/new-homepage/">New Homepage</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve renovated my homepage.</p>
<p>The old one was<br />
<div id="attachment_812" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/12/kevin-home-old1.png"><img src="http://blog.lckymn.com/wp-content/uploads/2012/12/kevin-home-old1.png" alt="" title="My homepage - OLD" width="640" height="577" class="size-full wp-image-812" /></a><p class="wp-caption-text">My homepage &#8211; OLD</p></div></p>
<p><a href="http://lckymn.com" target="_blank">The new one</a> is<br />
<div id="attachment_813" class="wp-caption alignnone" style="width: 781px"><a href="http://lckymn.com" target="_blank"><img src="http://blog.lckymn.com/wp-content/uploads/2012/12/kevin-home-new-1.png" alt="" title="My homepage - New" width="771" height="520" class="size-full wp-image-813" /></a><p class="wp-caption-text">My homepage &#8211; New</p></div><br />
It looks much better in Google Chrome and Firefox than IEs (It doesn&#8217;t work in IE6 at all).</p>
<p><a href="http://lckymn.com/kevin-projects.html" target="_blank">My projects</a> and <a href="http://lckymn.com/about-kevin.html" target="_blank">about me</a> page are also added.<br />
<div id="attachment_814" class="wp-caption alignnone" style="width: 650px"><a href="http://lckymn.com/kevin-projects.html" target="_blank"><img src="http://blog.lckymn.com/wp-content/uploads/2012/12/kevin-home-new-projects-1024x639.png" alt="" title="My Projects" width="640" height="399" class="size-large wp-image-814" /></a><p class="wp-caption-text">My Projects</p></div></p>
<div id="attachment_815" class="wp-caption alignnone" style="width: 650px"><a href="http://lckymn.com/about-kevin.html" target="_blank"><img src="http://blog.lckymn.com/wp-content/uploads/2012/12/kevin-home-new-about-me-1024x644.png" alt="" title="About Me" width="640" height="402" class="size-large wp-image-815" /></a><p class="wp-caption-text">About Me</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2012/12/06/new-homepage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Videos I recommend to (Java) Programmers</title>
		<link>http://blog.lckymn.com/2012/12/06/videos-i-recommend-to-java-programmers/</link>
		<comments>http://blog.lckymn.com/2012/12/06/videos-i-recommend-to-java-programmers/#comments</comments>
		<pubDate>Wed, 05 Dec 2012 16:08:11 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[API Design]]></category>
		<category><![CDATA[Closure]]></category>
		<category><![CDATA[Effective Java]]></category>
		<category><![CDATA[Good API Design]]></category>
		<category><![CDATA[Guy Steele]]></category>
		<category><![CDATA[Joshua Bloch]]></category>
		<category><![CDATA[Neal Gafter]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=800</guid>
		<description><![CDATA[For better Java programming Google I/O 2008 &#8211; Effective Java Reloaded &#8211; Joshua Bloch <p><object width="960" height="720"><embed src="http://www.youtube.com/v/pi_I7oD_uGI?version=3&#38;hl=en_US" type="application/x-shockwave-flash" width="960" height="720" allowscriptaccess="always" allowfullscreen="true"></embed></object> &#160; &#160;</p> Effective Java &#8211; Still Effective After All These Years &#8211; Joshua Bloch <p><object width="1280" height="720"><embed src="http://www.youtube.com/v/V1vQf4qyMXg?version=3&#38;hl=en_US" type="application/x-shockwave-flash" width="1280" height="720" allowscriptaccess="always" allowfullscreen="true"></embed></object> &#160; &#160; &#160; &#160;</p> For better API / language design Growing a Language, by Guy Steele <p><object width="960" height="720"><embed src="http://www.youtube.com/v/_ahvzDzKdB0?version=3&#38;hl=en_US" type="application/x-shockwave-flash" width="960" height="720" allowscriptaccess="always" allowfullscreen="true"></embed></object> &#160; &#160;</p> How To Design A Good API and <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2012/12/06/videos-i-recommend-to-java-programmers/">Videos I recommend to (Java) Programmers</a>...]</p>]]></description>
				<content:encoded><![CDATA[<h3>For better Java programming</h3>
<h4>Google I/O 2008 &#8211; Effective Java Reloaded &#8211; Joshua Bloch</h4>
<p><object width="960" height="720"><param name="movie" value="http://www.youtube.com/v/pi_I7oD_uGI?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/pi_I7oD_uGI?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="960" height="720" allowscriptaccess="always" allowfullscreen="true"></embed></object><br />
&nbsp;<br />
&nbsp;</p>
<h4>Effective Java &#8211; Still Effective After All These Years &#8211; Joshua Bloch</h4>
<p><object width="1280" height="720"><param name="movie" value="http://www.youtube.com/v/V1vQf4qyMXg?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/V1vQf4qyMXg?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="1280" height="720" allowscriptaccess="always" allowfullscreen="true"></embed></object><br />
&nbsp;<br />
&nbsp;<br />
&nbsp;<br />
&nbsp;</p>
<h3>For better API / language design</h3>
<h4>Growing a Language, by Guy Steele</h4>
<p><object width="960" height="720"><param name="movie" value="http://www.youtube.com/v/_ahvzDzKdB0?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/_ahvzDzKdB0?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="960" height="720" allowscriptaccess="always" allowfullscreen="true"></embed></object><br />
&nbsp;<br />
&nbsp;</p>
<h4>How To Design A Good API and Why it Matters &#8211; Joshua Bloch</h4>
<p><object width="960" height="720"><param name="movie" value="http://www.youtube.com/v/heh4OeB9A-c?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/heh4OeB9A-c?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="960" height="720" allowscriptaccess="always" allowfullscreen="true"></embed></object><br />
&nbsp;<br />
&nbsp;</p>
<h4>Evolving the Java Language &#8211; Neal Gafter</h4>
<p><a href="http://www.infoq.com/presentations/neal-gafter-evolving-java" target="_blank">http://www.infoq.com/presentations/neal-gafter-evolving-java</a><br />
&nbsp;<br />
&nbsp;</p>
<h4>Advanced Topics In Programming Languages: Closures For Java &#8211; Neal Gafter</h4>
<p><object width="960" height="720"><param name="movie" value="http://www.youtube.com/v/yUmWQHzN5ZU?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/yUmWQHzN5ZU?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="960" height="720" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2012/12/06/videos-i-recommend-to-java-programmers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Look and Say Sequence (Java)</title>
		<link>http://blog.lckymn.com/2012/09/09/look-and-say-sequence/</link>
		<comments>http://blog.lckymn.com/2012/09/09/look-and-say-sequence/#comments</comments>
		<pubDate>Sat, 08 Sep 2012 19:19:36 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mine]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Currying]]></category>
		<category><![CDATA[Function]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Look and Say]]></category>
		<category><![CDATA[Look and Say Sequence]]></category>
		<category><![CDATA[Recursion]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=743</guid>
		<description><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Look-and-say_sequence">Look and say sequence</a> is the sequence of numbers generated from the previous number by reading off the digits of which the number consists.</p> So the first number is 1 then there is one &#34;1&#34;. one 1 -&#62; 11 Now use the number &#34;11&#34; and there are two 1s. two 1s -&#62; 21 21: one 2 and one 1 -&#62; 1211 1211: one 1, one 2 and two 1s -&#62; 111221 111221: three 1s, two 2s and one 1 <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2012/09/09/look-and-say-sequence/">Look and Say Sequence (Java)</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Look-and-say_sequence">Look and say sequence</a> is the sequence of numbers generated from the previous number by reading off the digits of which the number consists.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
So the first number is 1 then there is one &quot;1&quot;. one 1 -&gt; 11
Now use the number &quot;11&quot; and there are two 1s. two 1s -&gt; 21
21: one 2 and one 1 -&gt; 1211
1211: one 1, one 2 and two 1s -&gt; 111221
111221: three 1s, two 2s and one 1 -&gt; 312211
312211: one 3, one 1, two 2s and two 1 -&gt; 13112221
13112221: one 1, one 3, two 1s, three 2s and one 1 -&gt; 1113213211
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
----------------------------------------------------------------
1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211 ...
</pre>
<p>The Java programme code which reads off the given number can be written like </p>
<pre class="brush: java; title: ; notranslate">
public static String LookAndSayUsingForLoop(final String number)
{
  if (null == number || number.isEmpty())
  {
    return &quot;&quot;;
  }
  int firstCharPosition = 0;
  final StringBuilder stringBuilder = new StringBuilder();
  for (int i = 0; i &lt; number.length(); i++)
  {
    if (number.charAt(firstCharPosition) != number.charAt(i))
    {
      //
      // the char at the current position is not equal to the first char
      // in the group of the equal chars so collect the chars
      // from the first char position to just before the current position.
      //
      final String digitsFound = number.substring(firstCharPosition, i);
      stringBuilder.append(digitsFound
                          .length())
                   .append(number
                          .charAt(firstCharPosition));
      firstCharPosition = i; // set the new first char position
    }
  }
  /* add the leftover */
  stringBuilder.append(number
                      .substring(firstCharPosition,
                                 number.length())
                      .length())
               .append(number
                      .charAt(firstCharPosition));
  return stringBuilder.toString();
}
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(LookAndSayUsingForLoop(&quot;1&quot;));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
11
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(LookAndSayUsingForLoop(&quot;11&quot;));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
21
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(LookAndSayUsingForLoop(&quot;21&quot;));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
1211
</pre>
<p>So to get the first ten elements,</p>
<pre class="brush: java; title: ; notranslate">
String result1 = number;
System.out.print(result1 + &quot; &quot;);
for (int i = 1; i &lt; howMany; i++)
{
  result1 = LookAndSayUsingForLoop(result1);
  System.out.print(result1 + &quot; &quot;);
}
</pre>
<p>It prints out.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
</pre>
<p>It can be simpler if <a href="http://en.wikipedia.org/wiki/Recursion_(computer_science)">recursion</a> is used.<br />
The LookAndSayUsingForLoop method can be re-written like</p>
<pre class="brush: java; title: ; notranslate">
private static String lookAndSayV1(final String number, final int position)
{
  if (number.length() == position)
  {
    // reached the end which means every digit in the number is
    // equal to one another so just read off the entire number.
    return String.valueOf(number.length()) + number.charAt(0);
  }
  final char firstChar = number.charAt(0);
  return firstChar == number.charAt(position) ?
            // the current char equals to the first one so keep checking
            lookAndSayV1(number, position + 1) :
            // otherwise, read off until just before the current position
            // then check from the current position
            // calling this function itself again.
            String.valueOf(number
                          .substring(0, position)
                          .length()) +
              firstChar +
              lookAndSayV1(number
                          .substring(position), 0);
}
</pre>
<p>The result is exactly the same as the one using &#8216;for&#8217; loop.</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(lookAndSayV1(&quot;1&quot;, 0));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
11
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(lookAndSayV1(&quot;11&quot;, 0));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
21
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(lookAndSayV1(&quot;21&quot;, 0));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
1211
</pre>
<p>To get the first ten elements, another recursive method can be used.</p>
<pre class="brush: java; title: ; notranslate">
public static String lookAndSay(final int howMany, final String number)
{
  return 0 &gt;= howMany ? &quot;&quot; : number + &quot; &quot; + lookAndSay(howMany - 1, lookAndSayV1(number, 0));
}
</pre>
<pre class="brush: java; title: ; notranslate">
final String number = &quot;1&quot;;
final String result = lookAndSay(10, number);
System.out.println(result);
</pre>
<p>Result:</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
</pre>
<p>The method lookAndSayV1() can be re-written using only one return statement and a few conditional operations.</p>
<pre class="brush: java; title: ; notranslate">
private static String lookAndSayV2(final String number, final int position)
{
  return number.length() == position ?
            String.valueOf(number
                          .length()) +
              number.charAt(0) :
            (number.charAt(0) == number.charAt(position) ?
                lookAndSayV2(number, position + 1) :
                String.valueOf(number
                              .substring(0, position)
                              .length()) +
                  number.charAt(0) +
                  lookAndSayV2(number
                            .substring(position), 0));
}
</pre>
<p>This works the same as the lookAndSayV1() method. The code would be more readable with readOff() method.</p>
<pre class="brush: java; title: ; notranslate">
private static String readOff(final String digits)
{
  return String.valueOf(digits.length()) + digits.charAt(0);
}

private static String lookAndSayV3(final String number, final int position)
{
  return number.length() == position ?
            readOff(number) :
            (number.charAt(0) == number.charAt(position) ?
                lookAndSayV3(number, position + 1) :
                readOff(number
                      .substring(0, position)) +
                      lookAndSayV3(number
                                  .substring(position), 0));
}

public static String lookAndSay3(final int howMany, final String number)
{
  return 0 &gt;= howMany ? &quot;&quot; : number + &quot; &quot; + lookAndSay3(howMany - 1, lookAndSayV3(number, 0));
}
</pre>
<p>If the numbers should be stored in a List object, it can be done like</p>
<pre class="brush: java; title: ; notranslate">
public static void lookAndSayUsingList(final String number, final int howMany, final List&lt;String&gt; resultList)
{
  resultList.add(number);
  if (resultList.size() &lt; howMany)
  {
    lookAndSayUsingList(lookAndSayV3(number, 0), howMany, resultList);
  }
}
</pre>
<pre class="brush: java; title: ; notranslate">
final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
lookAndSayUsingList(number, howMany, resultList);
System.out.println(resultList);
</pre>
<p>If you prefer having returned result,</p>
<pre class="brush: java; title: ; notranslate">
private static List&lt;String&gt; lookAndSayUsingList2(final String number, final int howMany, final List&lt;String&gt; list)
{
  list.add(number);
  if (list.size() &lt; howMany)
  {
    return lookAndSayUsingList2(lookAndSayV3(number, 0), howMany, list);
  }
  return Collections.unmodifiableList(new ArrayList&lt;String&gt;(list));
}
</pre>
<p>The last line which returns an unmodifiable list object should use a new ArrayList object instead of directly using list.<br />
Just making list unmodifiableList is not enough as the caller of this method can still modify the given parameter list<br />
e.g.) Just have Collections.unmodifiableList(list); will result in</p>
<pre class="brush: java; title: ; notranslate">
final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
resultList.add(number);
final List&lt;String&gt; result = lookAndSayUsingList2(resultList, howMany);
// result.add(&quot;test&quot;); // &lt;- this does not work! runtime exception!
resultList.add(&quot;test&quot;); // &lt;- yet this does!!!
// Now the result has &quot;test&quot; at the end although it's unmodifiable List.
// It was modified using resultList.
</pre>
<p>If you don&#8217;t want to pass a List object, create another method and use it with the lookAndSayUsingList2() method.</p>
<pre class="brush: java; title: ; notranslate">
public static List&lt;String&gt; lookAndSayUsingList2(final String number, final int howMany)
{
  final List&lt;String&gt; list = new ArrayList&lt;String&gt;();
  return lookAndSayUsingList2(number, howMany, list);
}
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(lookAndSayUsingList2(number, howMany));
</pre>
<p>Finally, using a Function object.</p>
<pre class="brush: java; title: ; notranslate">
public interface LookAndSayFunction
{
  void apply(String number, int howMany);
}
</pre>
<pre class="brush: java; title: ; notranslate">
final List&lt;String&gt; resultListFromFunctionObject = new ArrayList&lt;String&gt;();
new LookAndSayFunction() {
  @Override
  public void apply(final String number, final int howMany)
  {
    resultListFromFunctionObject.add(number);
    if (resultListFromFunctionObject.size() &lt; howMany)
    {
      apply(lookAndSayV3(number, 0), howMany);
    }
  }
}.apply(number, howMany);

System.out.println(resultListFromFunctionObject);
</pre>
<p>Don&#8217;t want to get a mutable List object staying outside the function?</p>
<pre class="brush: java; title: ; notranslate">
public interface Function1&lt;T, R&gt;
{
  R apply(T input);
}

public interface Function2&lt;T1, T2, R&gt;
{
  R apply(T1 input1, T2 input2);
}
</pre>
<pre class="brush: java; title: ; notranslate">
final Function2&lt;String, Integer, List&lt;String&gt;&gt; anotherFunction =
  new Function2&lt;String, Integer, List&lt;String&gt;&gt;() {
    @Override
    public List&lt;String&gt; apply(final String number, final Integer howMany)
    {
      return new Function&lt;List&lt;String&gt;&gt;() {
        @Override
        public List&lt;String&gt; apply()
        {
          final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
          return new Function1&lt;String, List&lt;String&gt;&gt;() {
            @Override
            public List&lt;String&gt; apply(final String number)
            {
              resultList.add(number);
              if (resultList.size() &lt; howMany.intValue())
              {
                return apply(lookAndSayV3(number, 0));
              }
              return Collections.unmodifiableList(resultList);
            }
          }.apply(number);
        }
      }.apply();
    }
  };

System.out.println(anotherFunction.apply(number, howMany));
</pre>
<p>Or <a href="http://en.wikipedia.org/wiki/Currying">currying</a> can be used.</p>
<pre class="brush: java; title: ; notranslate">
final Function1&lt;Integer, Function1&lt;String, List&lt;String&gt;&gt;&gt; lookAndSayWithCurrying =
new Function1&lt;Integer, Function1&lt;String, List&lt;String&gt;&gt;&gt;() {
  @Override
  public Function1&lt;String, List&lt;String&gt;&gt; apply(final Integer howMany)
  {
    return new Function1&lt;String, List&lt;String&gt;&gt;() {
      @Override
      public List&lt;String&gt; apply(final String number)
      {
        final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
        return new Function1&lt;String, List&lt;String&gt;&gt;() {
          @Override
          public List&lt;String&gt; apply(final String number)
          {
            resultList.add(number);
            if (resultList.size() &lt; howMany.intValue())
            {
              return apply(lookAndSayV3(number, 0));
            }
            return Collections.unmodifiableList(resultList);
          }
        }.apply(number);
      }
    };
  }
};
System.out.println(lookAndSayWithCurrying.apply(howMany)
        .apply(number));
</pre>
<p>The function can be reused.</p>
<pre class="brush: java; title: ; notranslate">
final Function1&lt;String, List&lt;String&gt;&gt; lookAndSayToGet10Elements = lookAndSayWithCurrying.apply(10);
System.out.println(lookAndSayToGet10Elements.apply(number));
System.out.println(lookAndSayToGet10Elements.apply(number));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
</pre>
<pre class="brush: java; title: ; notranslate">
final Function1&lt;String, List&lt;String&gt;&gt; lookAndSayToGet5Elements = lookAndSayWithCurrying.apply(5);
System.out.println(lookAndSayToGet5Elements.apply(number));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
[1, 11, 21, 1211, 111221]
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(lookAndSayToGet5Elements.apply(&quot;111221&quot;));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
[111221, 312211, 13112221, 1113213211, 31131211131221]
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(lookAndSayToGet5Elements.apply(&quot;21&quot;));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
[21, 1211, 111221, 312211, 13112221]
</pre>
<pre class="brush: java; title: ; notranslate">
System.out.println(lookAndSayToGet5Elements.apply(&quot;1&quot;));
</pre>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Result:
[1, 11, 21, 1211, 111221]
</pre>
<p>If you want to fix the number and get different numbers of elements as the results from the look and say function,</p>
<pre class="brush: java; title: ; notranslate">
final Function1&lt;String, Function1&lt;Integer, List&lt;String&gt;&gt;&gt; lookAndSayWithCurryingAndNumberFixed =
  new Function1&lt;String, Function1&lt;Integer, List&lt;String&gt;&gt;&gt;() {
    @Override
    public Function1&lt;Integer, List&lt;String&gt;&gt; apply(final String number)
    {
      return new Function1&lt;Integer, List&lt;String&gt;&gt;() {
        @Override
        public List&lt;String&gt; apply(final Integer howMany)
        {
          final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
          return new Function1&lt;String, List&lt;String&gt;&gt;() {
            @Override
            public List&lt;String&gt; apply(final String number)
            {
              resultList.add(number);
              if (resultList.size() &lt; howMany.intValue())
              {
                return apply(lookAndSayV3(number, 0));
              }
              return Collections.unmodifiableList(resultList);
            }
          }.apply(number);
        }
      };
    }
  };
</pre>
<pre class="brush: java; title: ; notranslate">
final Function1&lt;Integer, List&lt;String&gt;&gt; lookAndSayWithNumberFixed = lookAndSayWithCurryingAndNumberFixed.apply(&quot;1&quot;);
System.out.println(lookAndSayWithNumberFixed.apply(3));
System.out.println(lookAndSayWithNumberFixed.apply(5));
System.out.println(lookAndSayWithNumberFixed.apply(10));
</pre>
<p>Results:</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
[1, 11, 21]
[1, 11, 21, 1211, 111221]
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
</pre>
<p>Here are all the examples.<br />
<script src="https://gist.github.com/3678544.js?file=LookAndSaySequenceExample.java"></script></p>
<p>Results:</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Using LookAndReadUsingForLoop: 
String result1 = number;
System.out.print(result1 + &quot; &quot;);
for (int i = 1; i &lt; howMany; i++)
{
  result1 = LookAndSayUsingForLoop(result1);
  System.out.print(result1 + &quot; &quot;);
}
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
--------------------------------------------------------------------------------

Using lookAndSayV1: 
System.out.println(lookAndSay(howMany, number));
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
--------------------------------------------------------------------------------

Using lookAndSaV2: 
System.out.println(lookAndSay2(howMany, number));
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
--------------------------------------------------------------------------------

Using lookAndSaV3: 
System.out.println(lookAndSay3(howMany, number));
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
--------------------------------------------------------------------------------

Using lookAndSayUsingList: 
final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
lookAndSayUsingList(number, howMany, resultList);
System.out.println(resultList);
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
--------------------------------------------------------------------------------

Using lookAndSayUsingList2: 
System.out.println(lookAndSayUsingList2(number, howMany, new ArrayList&lt;String&gt;()));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
--------------------------------------------------------------------------------

Using another lookAndSayUsingList2 (without passing List): 
System.out.println(lookAndSayUsingList2(number, howMany))
--------------------------------------------------------------------------------

Using Function object: 
final List&lt;String&gt; resultListFromFunctionObject = new ArrayList&lt;String&gt;();
new LookAndSayFunction() {
  @Override
  public void apply(final String number, final int howMany)
  {
    resultListFromFunctionObject.add(number);
    if (resultListFromFunctionObject.size() &lt; howMany)
    {
      apply(lookAndSayV3(number, 0), howMany);
    }
  }
}.apply(number, howMany);
System.out.println(resultListFromFunctionObject);
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
--------------------------------------------------------------------------------

Using Function object with returned List object: 
final Function2&lt;String, Integer, List&lt;String&gt;&gt; anotherFunction = new Function2&lt;String, Integer, List&lt;String&gt;&gt;() {
  @Override
  public List&lt;String&gt; apply(final String number, final Integer howMany)
  {
    return new Function&lt;List&lt;String&gt;&gt;() {
      @Override
      public List&lt;String&gt; apply()
      {
        final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
        return new Function1&lt;String, List&lt;String&gt;&gt;() {
          @Override
          public List&lt;String&gt; apply(final String number)
          {
            resultList.add(number);
            if (resultList.size() &lt; howMany.intValue())
            {
              return apply(lookAndSayV3(number, 0));
            }
            return Collections.unmodifiableList(resultList);
          }
        }.apply(number);
      }
    }.apply();
  }
};
System.out.println(anotherFunction.apply(number, howMany));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

System.out.println(anotherFunction.apply(number, 5));
[1, 11, 21, 1211, 111221]

System.out.println(anotherFunction.apply(number, 7));
[1, 11, 21, 1211, 111221, 312211, 13112221]
--------------------------------------------------------------------------------

Using currying (number of elements fixed): 
final Function1&lt;Integer, Function1&lt;String, List&lt;String&gt;&gt;&gt; lookAndSayWithCurrying =
  new Function1&lt;Integer, Function1&lt;String, List&lt;String&gt;&gt;&gt;() {
    @Override
    public Function1&lt;String, List&lt;String&gt;&gt; apply(final Integer howMany)
    {
      return new Function1&lt;String, List&lt;String&gt;&gt;() {
        @Override
        public List&lt;String&gt; apply(final String number)
        {
          final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
          return new Function1&lt;String, List&lt;String&gt;&gt;() {
            @Override
            public List&lt;String&gt; apply(final String number)
            {
              resultList.add(number);
              if (resultList.size() &lt; howMany.intValue())
              {
                return apply(lookAndSayV3(number, 0));
              }
              return Collections.unmodifiableList(resultList);
            }
          }.apply(number);
        }
      };
    }
  };
lookAndSayWithCurrying.apply(howMany)
    .apply(number);
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

final Function1&lt;String, List&lt;String&gt;&gt; lookAndSayToGet10Elements = lookAndSayWithCurrying.apply(10);
System.out.println(lookAndSayToGet10Elements.apply(number));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

System.out.println(lookAndSayToGet10Elements.apply(number));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

System.out.println(lookAndSayToGet10Elements.apply(number));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]


final Function1&lt;String, List&lt;String&gt;&gt; lookAndSayToGet5Elements = lookAndSayWithCurrying.apply(5);
System.out.println(lookAndSayToGet5Elements.apply(number));
[1, 11, 21, 1211, 111221]

System.out.println(lookAndSayToGet5Elements.apply(number));
[1, 11, 21, 1211, 111221]

System.out.println(lookAndSayToGet5Elements.apply(number));
[1, 11, 21, 1211, 111221]

System.out.println(lookAndSayToGet5Elements.apply(&quot;111221&quot;));
[111221, 312211, 13112221, 1113213211, 31131211131221]

System.out.println(lookAndSayToGet5Elements.apply(&quot;21&quot;));
[21, 1211, 111221, 312211, 13112221]

System.out.println(lookAndSayToGet5Elements.apply(&quot;1&quot;));
[1, 11, 21, 1211, 111221]
--------------------------------------------------------------------------------

Using currying (number fixed): 
final Function1&lt;String, Function1&lt;Integer, List&lt;String&gt;&gt;&gt; lookAndSayWithCurryingAndNumberFixed =
  new Function1&lt;String, Function1&lt;Integer, List&lt;String&gt;&gt;&gt;() {
    @Override
    public Function1&lt;Integer, List&lt;String&gt;&gt; apply(final String number)
    {
      return new Function1&lt;Integer, List&lt;String&gt;&gt;() {
        @Override
        public List&lt;String&gt; apply(final Integer howMany)
        {
          final List&lt;String&gt; resultList = new ArrayList&lt;String&gt;();
          return new Function1&lt;String, List&lt;String&gt;&gt;() {
            @Override
            public List&lt;String&gt; apply(final String number)
            {
              resultList.add(number);
              if (resultList.size() &lt; howMany.intValue())
              {
                return apply(lookAndSayV3(number, 0));
              }
              return Collections.unmodifiableList(resultList);
            }
          }.apply(number);
        }
      };
    }
  };
final Function1&lt;Integer, List&lt;String&gt;&gt; lookAndSayWithNumberFixed = lookAndSayWithCurryingAndNumberFixed.apply(&quot;1&quot;);
System.out.println(lookAndSayWithNumberFixed.apply(howMany));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

System.out.println(lookAndSayWithNumberFixed.apply(3));
[1, 11, 21]

System.out.println(lookAndSayWithNumberFixed.apply(5));
[1, 11, 21, 1211, 111221]

System.out.println(lookAndSayWithNumberFixed.apply(10));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2012/09/09/look-and-say-sequence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Five Things You Didn&#8217;t Know About PostgreSQL</title>
		<link>http://blog.lckymn.com/2012/08/25/five-things-you-didnt-know-about-postgresql/</link>
		<comments>http://blog.lckymn.com/2012/08/25/five-things-you-didnt-know-about-postgresql/#comments</comments>
		<pubDate>Sat, 25 Aug 2012 10:27:51 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Development Tools]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[MS SQL]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Postgres]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[Transaction]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=719</guid>
		<description><![CDATA[<p>This proves that the decision I made about three years ago was right! <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p> <div> <p><a href="http://vimeo.com/43536445">Rob Conery &#8211; Five Things You Didn&#8217;t Know About PostgreSQL</a> from <a href="http://vimeo.com/ndcoslo">NDCOslo</a> on <a href="http://vimeo.com">Vimeo</a>.</p> </div> ]]></description>
				<content:encoded><![CDATA[<p>This proves that the decision I made about three years ago was right! <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div>
<iframe src="http://player.vimeo.com/video/43536445" width="1024" height="576" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
<p><a href="http://vimeo.com/43536445">Rob Conery &#8211; Five Things You Didn&#8217;t Know About PostgreSQL</a> from <a href="http://vimeo.com/ndcoslo">NDCOslo</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2012/08/25/five-things-you-didnt-know-about-postgresql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What&#8217;s new in new mQlicker</title>
		<link>http://blog.lckymn.com/2012/08/05/whats-new-in-new-mqlicker/</link>
		<comments>http://blog.lckymn.com/2012/08/05/whats-new-in-new-mqlicker/#comments</comments>
		<pubDate>Sun, 05 Aug 2012 13:03:51 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Mine]]></category>
		<category><![CDATA[mQlicker]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Audience Interaction System]]></category>
		<category><![CDATA[Audience Response System]]></category>
		<category><![CDATA[New Version]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=676</guid>
		<description><![CDATA[<p>I&#8217;ve been developing <a href="http://www.mqlicker.com">mQlicker</a> for approximately two years. Dr. Raban, Sverre and I co-founded a startup about two year ago and we started developing it. The first official release happened last February, and now we are about to release a new version of <a href="http://www.mqlicker.com">mQlicker</a>. Before we do, I&#8217;d like to point out the new features and changes in the new one.</p> <p><a href="http://www.mqlicker.com">mQlicker</a> is a audience response system (audience interaction system / classroom interaction system) which can give <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2012/08/05/whats-new-in-new-mqlicker/">What&#8217;s new in new mQlicker</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been developing <a href="http://www.mqlicker.com">mQlicker</a> for approximately two years. Dr. Raban, Sverre and I co-founded a startup about two year ago and we started developing it. The first official release happened last February, and now we are about to release a new version of <a href="http://www.mqlicker.com">mQlicker</a>. Before we do, I&#8217;d like to point out the new features and changes in the new one.</p>
<p><a href="http://www.mqlicker.com">mQlicker</a> is a audience response system (audience interaction system / classroom interaction system) which can give a voice to the audience. It can be used for classroom, presentation, lecture, survey, quiz, etc. It consists of two main UIs which are the user UI for those who want to get the responses from people and the respondent UI for those who respond.</p>
<div id="attachment_679" class="wp-caption aligncenter" style="width: 683px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/00_mQlicker.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/00_mQlicker.jpg" alt="What&#039;s new in new mQlicker" title="00_mQlicker" width="673" height="449" class="size-full wp-image-679" /></a><p class="wp-caption-text">What&#8217;s new in new mQlicker</p></div>
<h1>1. Respondent UI</h1>
<h2>1.1. Design Change in Respondent UI</h2>
<div id="attachment_680" class="wp-caption aligncenter" style="width: 567px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_01_old.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_01_old.jpg" alt="OLD: Respondent UI" title="01_respondent_UI_01_old" width="557" height="503" class="size-full wp-image-680" /></a><p class="wp-caption-text">OLD: Respondent UI</p></div>
<p>The old version of the respondent UI for computers doesn&#8217;t look so pretty. The look is also too different from the one displayed on the mobile devices (Please see how it looks on iPhone).<br />
The new one looks prettier and similar to the mobile one.</p>
<p><div id="attachment_681" class="wp-caption aligncenter" style="width: 330px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_02_iPhone.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_02_iPhone.jpg" alt="Respondent UI: iPhone" title="01_respondent_UI_02_iPhone" width="640" height="922" class="size-full wp-image-681" /></a><p class="wp-caption-text">Respondent UI: iPhone</p></div> <div id="attachment_682" class="wp-caption aligncenter" style="width: 568px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_02_new.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_02_new.jpg" alt="New Respondent UI" title="01_respondent_UI_02_new" width="558" height="502" class="size-full wp-image-682" /></a><p class="wp-caption-text">New Respondent UI</p></div></p>
<h2>1.2. Page Breaks.</h2>
<p><div id="attachment_683" class="wp-caption aligncenter" style="width: 483px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_03_old.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_03_old.jpg" alt="OLD: All qeustions on one page" title="01_respondent_UI_03_old" width="473" height="655" class="size-full wp-image-683" /></a><p class="wp-caption-text">OLD: All qeustions on one page</p></div><br />
In the old version, there is no way to put a different number of question on one page. So all the questions are on a single page as you can see.</p>
<p><div id="attachment_684" class="wp-caption aligncenter" style="width: 631px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_04_new.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_04_new.jpg" alt="New Respondent UI with different number of question on each page." title="01_respondent_UI_04_new" width="621" height="887" class="size-full wp-image-684" /></a><p class="wp-caption-text">New Respondent UI with different number of question on each page.</p></div><br />
The new version has page break so it can have many pages with a different number of questions as you wish.<br />
<div id="attachment_685" class="wp-caption aligncenter" style="width: 631px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_05_new.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_05_new.jpg" alt="New Respondent UI with one question on one page." title="01_respondent_UI_05_new" width="621" height="883" class="size-full wp-image-685" /></a><p class="wp-caption-text">New Respondent UI with one question on one page.</p></div></p>
<h2>1.3. Optional Questions.</h2>
<p><div id="attachment_686" class="wp-caption aligncenter" style="width: 567px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_06_old_no_optional.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_06_old_no_optional.jpg" alt="Old Respondent UI without optional questions" title="01_respondent_UI_06_old_no_optional" width="557" height="654" class="size-full wp-image-686" /></a><p class="wp-caption-text">Old Respondent UI without optional questions</p></div><br />
The old version does not support an optional questions which means all the questions are mandatory. Therefore, if you forget to answer any question, your answer cannot be submitted.</p>
<p><div id="attachment_687" class="wp-caption aligncenter" style="width: 647px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_07_new_optional.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_07_new_optional.jpg" alt="New Respondent UI with an optional question" title="01_respondent_UI_07_new_optional" width="637" height="534" class="size-full wp-image-687" /></a><p class="wp-caption-text">New Respondent UI with an optional question</p></div><br />
From the new version, optional questions can be created.</p>
<h2>1.4. Missing Answer Indicator for Mandatory Questions.</h2>
<p><div id="attachment_688" class="wp-caption aligncenter" style="width: 565px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_08_old_no_error_indicator.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_08_old_no_error_indicator.jpg" alt="Old Respondent UI with no missing answer indicator" title="01_respondent_UI_08_old_no_error_indicator" width="555" height="653" class="size-full wp-image-688" /></a><p class="wp-caption-text">Old Respondent UI with no missing answer indicator</p></div><br />
There was no way to find the missing answers without checking each question carefully when you forgot to answer some questions.</p>
<p><div id="attachment_689" class="wp-caption aligncenter" style="width: 638px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_09_new_error_indicator.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_09_new_error_indicator.jpg" alt="New Respondent UI with a missing answer indicator" title="01_respondent_UI_09_new_error_indicator" width="628" height="876" class="size-full wp-image-689" /></a><p class="wp-caption-text">New Respondent UI with a missing answer indicator</p></div><br />
The new one highlights it, so you can simple take care of those missing ones.</p>
<h2>1.5. Other Answer</h2>
<p><div id="attachment_690" class="wp-caption aligncenter" style="width: 568px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_10_old_no_other_answer.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_10_old_no_other_answer.jpg" alt="Old Respondent UI with no other answer" title="01_respondent_UI_10_old_no_other_answer" width="558" height="654" class="size-full wp-image-690" /></a><p class="wp-caption-text">Old Respondent UI with no other answer</p></div><br />
The multiple choice questions did not allow the respondent to answer anything other than the ones provided with the question.</p>
<p><div id="attachment_691" class="wp-caption aligncenter" style="width: 638px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_11_new_other_answer.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_11_new_other_answer.jpg" alt="New Respondent UI with other answer" title="01_respondent_UI_11_new_other_answer" width="628" height="874" class="size-full wp-image-691" /></a><p class="wp-caption-text">New Respondent UI with other answer</p></div><br />
However, the new version has other answer field so now you can get some other opinions than what you provided from the respondents.</p>
<h2>1.6. Result is Visible to the Respondents.</h2>
<p><div id="attachment_692" class="wp-caption aligncenter" style="width: 565px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_12_old_no_result.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_12_old_no_result.jpg" alt="Old Respondent UI with no result after submission" title="01_respondent_UI_12_old_no_result" width="555" height="624" class="size-full wp-image-692" /></a><p class="wp-caption-text">Old Respondent UI with no result after submission</p></div><br />
Previously, the respondents can see the result of all the responses after submit their answers.</p>
<p><div id="attachment_693" class="wp-caption aligncenter" style="width: 642px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_13_new_result_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_13_new_result_01.jpg" alt="New Respondent UI with result after answer submission" title="01_respondent_UI_13_new_result_01" width="632" height="652" class="size-full wp-image-693" /></a><p class="wp-caption-text">New Respondent UI with result after answer submission</p></div><br />
<div id="attachment_694" class="wp-caption aligncenter" style="width: 642px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_14_new_result_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_14_new_result_02.jpg" alt="New Respondent UI with result after answer submission" title="01_respondent_UI_14_new_result_02" width="632" height="652" class="size-full wp-image-694" /></a><p class="wp-caption-text">New Respondent UI with result after answer submission</p></div><br />
<div id="attachment_695" class="wp-caption aligncenter" style="width: 640px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_15_new_result_03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_15_new_result_03.jpg" alt="New Respondent UI with result after answer submission" title="01_respondent_UI_15_new_result_03" width="630" height="652" class="size-full wp-image-695" /></a><p class="wp-caption-text">New Respondent UI with result after answer submission</p></div><br />
<div id="attachment_696" class="wp-caption aligncenter" style="width: 639px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_16_new_result_04.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/01_respondent_UI_16_new_result_04.jpg" alt="New Respondent UI with result after answer submission" title="01_respondent_UI_16_new_result_04" width="629" height="651" class="size-full wp-image-696" /></a><p class="wp-caption-text">New Respondent UI with result after answer submission</p></div><br />
With new one, it is possible to see the result although it needs a little more improvement (the improved one will come soon).</p>
<h1>2. User UI</h1>
<div id="attachment_698" class="wp-caption aligncenter" style="width: 786px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_02_old_question_editor.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_02_old_question_editor.jpg" alt="Old User UI" title="02_user_UI_02_old_question_editor" width="776" height="900" class="size-full wp-image-698" /></a><p class="wp-caption-text">Old User UI</p></div>
<div id="attachment_699" class="wp-caption aligncenter" style="width: 834px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_03_new_question_editor.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_03_new_question_editor.jpg" alt="New User UI" title="02_user_UI_03_new_question_editor" width="824" height="910" class="size-full wp-image-699" /></a><p class="wp-caption-text">New User UI</p></div>
<h2>2.1. Rich Text Editor</h2>
<p>Please compare the new one with the old one. You could only have plain text without any formatting. Now, it is possible to format your text just like using a word processor.</p>
<h2>2.2 Result Visible to Respondent</h2>
<p>As already mentioned above, you can set the interaction to make the response result visible to the respondents once they submit their answers.</p>
<h2>2.3. Other Answer</h2>
<p>You can make the multiple choice questions have other answers with the label you want (Other? Something else?, etc).</p>
<h2>2.4 Optional Question</h2>
<p>Questions and be optional so not all of them are mandatory.</p>
<h2>2.5. Page Breaks</h2>
<p>You can easily set the number of questions per page by just clicking the page breaker bar to enable and disabled it.</p>
<h2>2.6. Images in Question</h2>
<p>Now you can upload an image file or set the location of the image to display it with the question.<br />
<div id="attachment_700" class="wp-caption aligncenter" style="width: 984px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_04_new_question_editor_embed_image_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_04_new_question_editor_embed_image_01.jpg" alt="User UI - Question with image" title="02_user_UI_04_new_question_editor_embed_image_01" width="974" height="719" class="size-full wp-image-700" /></a><p class="wp-caption-text">User UI &#8211; Question with image</p></div><br />
<div id="attachment_701" class="wp-caption aligncenter" style="width: 982px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_05_new_question_editor_embed_image_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_05_new_question_editor_embed_image_02.jpg" alt="User UI - Question with image" title="02_user_UI_05_new_question_editor_embed_image_02" width="972" height="719" class="size-full wp-image-701" /></a><p class="wp-caption-text">User UI &#8211; Question with image</p></div><br />
<div id="attachment_702" class="wp-caption aligncenter" style="width: 985px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_06_new_question_editor_embed_image_03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_06_new_question_editor_embed_image_03.jpg" alt="User UI - Question with image" title="02_user_UI_06_new_question_editor_embed_image_03" width="975" height="719" class="size-full wp-image-702" /></a><p class="wp-caption-text">User UI &#8211; Question with image</p></div><br />
<div id="attachment_703" class="wp-caption aligncenter" style="width: 640px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_06_new_question_editor_embed_image_04_respondent_UI.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_06_new_question_editor_embed_image_04_respondent_UI.jpg" alt="Respondent UI - Question with image" title="02_user_UI_06_new_question_editor_embed_image_04_respondent_UI" width="630" height="729" class="size-full wp-image-703" /></a><p class="wp-caption-text">Respondent UI &#8211; Question with image</p></div></p>
<h2>2.7 Slide type question</h2>
<p>Sometimes you only need to provide some text that you want your audience to read. Now you can have a slide type question which only displays the text you provide!</p>
<h2>2.8. Running Session Indicator</h2>
<p><div id="attachment_697" class="wp-caption aligncenter" style="width: 710px"><a href="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_01_old_new_session_indicator_icon.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2012/08/02_user_UI_01_old_new_session_indicator_icon.jpg" alt="New User UI has a running session indicator" title="02_user_UI_01_old_new_session_indicator_icon" width="700" height="290" class="size-full wp-image-697" /></a><p class="wp-caption-text">New User UI has a running session indicator</p></div><br />
The new one has a running session indicator icon on the interaction so you can easily recognise which one has any running sessions without expanding interaction.</p>
<p>OK, that&#8217;s it. There are still several minor things but not that big deal so I rather not talk about here.<br />
I hope you enjoy the new <a href="http://www.mqlicker.com">mQlicker</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2012/08/05/whats-new-in-new-mqlicker/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>String Concatenation vs Conditional Operator in Java and JavaScript</title>
		<link>http://blog.lckymn.com/2012/07/26/string-concatenation-vs-conditional-operator-in-java-and-javascript/</link>
		<comments>http://blog.lckymn.com/2012/07/26/string-concatenation-vs-conditional-operator-in-java-and-javascript/#comments</comments>
		<pubDate>Thu, 26 Jul 2012 11:32:01 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[boolean]]></category>
		<category><![CDATA[conditional expression]]></category>
		<category><![CDATA[Conditional operator]]></category>
		<category><![CDATA[false]]></category>
		<category><![CDATA[precedence]]></category>
		<category><![CDATA[String concatenation]]></category>
		<category><![CDATA[true]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=661</guid>
		<description><![CDATA[<p>Java:</p> System.out.println(&#34;client &#34; + authorized ? &#34;authorized&#34; : &#34;unauthorized&#34;); <p>JavaScript:</p> alert('client ' + authorized ? 'authorized' : 'unauthorized'); <p>(Let&#8217;s assume that the <code>authorized</code> is a parameter variable)</p> <p>In Java, if you write code like this, you definitely get a compile time error, since String concatenation gets higher precedence than conditional operator whereas in JavaScript, you don&#8217;t get any error although String concatenation has higher precedence just like Java.</p> <p>Reason for that is unlike Java which allows only <code>true</code> or <code>false</code> <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2012/07/26/string-concatenation-vs-conditional-operator-in-java-and-javascript/">String Concatenation vs Conditional Operator in Java and JavaScript</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>Java:</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
System.out.println(&quot;client &quot; + authorized ? &quot;authorized&quot; : &quot;unauthorized&quot;);
</pre>
<p>JavaScript:</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('client ' + authorized ? 'authorized' : 'unauthorized');
</pre>
<p>(Let&#8217;s assume that the <code>authorized</code> is a parameter variable)</p>
<p>In Java, if you write code like this, you definitely get a compile time error, since String concatenation gets higher precedence than conditional operator whereas in JavaScript, you don&#8217;t get any error although String concatenation has higher precedence just like Java.</p>
<p>Reason for that is unlike Java which allows only <code>true</code> or <code>false</code> (or boxed Boolean) for conditional expression, in JavaScript, there are several cases that make conditional expression working and make the evaluation result of it false (<code>false</code>, <code>undefined</code>, <code>0</code>, <code>Number.NaN</code>, <code>""</code> (empty String), etc.) or true (cases other than the ones making it <code>false</code>). So if you have some value other than those and test it, the result is <code>true</code>.</p>
<p>e.g.) some cases making the evaluation of conditional expression false.</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
if (0)
{
  // false so never come here.
}

if (undefined)
{
  // false so never come here.
}

if (Number.NaN)
{
  // false so never come here.
}

if (false)
{
  // false so never come here.
}

if (&quot;&quot;)
{
  // false so never come here.
}
</pre>
<p>e.g.) some cases making the evaluation of conditional expression true.</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
if (1)
{
  // true!
}

if (&quot;some value&quot;)
{
  // true!
}

if (true)
{
  // of course true!
}

if ({})
{
  // true!
}


if ({&quot;someName&quot;:&quot;someValue&quot;})
{
  // true!
}


if ([])
{
  // true!
}


if ([1,2,3,])
{
  // true!
}
</pre>
<p>So this code</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('client ' + authorized ? 'authorized' : 'unauthorized');
</pre>
<p>will eventually become like</p>
<p>if authorized is true,</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('client true' ? 'authorized' : 'unauthorized');
</pre>
<p>then</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('authorized');
</pre>
<p>if authorized is false,</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('client false' ? 'authorized' : 'unauthorized');
</pre>
<p>then</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('authorized');
</pre>
<p>if the caller of the function didn&#8217;t send the <code>authorized</code>.</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('client undefined' ? 'authorized' : 'unauthorized');
</pre>
<p>then</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('authorized');
</pre>
<p>So if you want to get the result you want, the conditional operator part should be wrapped in parentheses.</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
alert('client ' + (authorized ? 'authorized' : 'unauthorized'));
</pre>
<p>In Java, you must!</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
System.out.println(&quot;client &quot; + (authorized ? &quot;authorized&quot; : &quot;unauthorized&quot;));
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2012/07/26/string-concatenation-vs-conditional-operator-in-java-and-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Do You Hate Java?</title>
		<link>http://blog.lckymn.com/2012/02/27/do-you-hate-java/</link>
		<comments>http://blog.lckymn.com/2012/02/27/do-you-hate-java/#comments</comments>
		<pubDate>Sun, 26 Feb 2012 15:35:28 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mQlicker]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[JSON Statham]]></category>
		<category><![CDATA[Object-Oriented Programming]]></category>
		<category><![CDATA[Platform]]></category>
		<category><![CDATA[Tool]]></category>
		<category><![CDATA[verbose]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=637</guid>
		<description><![CDATA[<p></p> <div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);"> Java.next <p><a href="http://www.infoq.com/presentations/Java-next">http://www.infoq.com/presentations/Java-next</a> </div> <p>I quite agree with him.</p> <p>What mistake most people make when they compare Java with other programming languages and talk about how bad Java is is that they only talk about the Java programming language but not Java platform. It is not really fair to talk about Java without thinking its ecosystem including the platform, frameworks, libraries, tools, etc. As <a <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2012/02/27/do-you-hate-java/">Do You Hate Java?</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p></p>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
<h3>Java.next</h3>
<p><a href="http://www.infoq.com/presentations/Java-next">http://www.infoq.com/presentations/Java-next</a>
</div>
<p>I quite agree with him.</p>
<p>What mistake most people make when they compare Java with other programming languages and talk about how bad Java is is that they only talk about the Java programming language but not Java platform.  It is not really fair to talk about Java without thinking its ecosystem including the platform, frameworks, libraries, tools, etc.  As <a href="http://www.infoq.com/presentations/Java-next">Erik says in the talk above</a>, if you use vim to programme Java code, it&#8217;s like pounding a nail with your head.  People complain about static typing but with help from proper IDEs, it can actually increase programming productivity not to mention of easier debugging.</p>
<p>What about Java&#8217;s verbosity?  Programming is a conversation between a computer and a human.  Imagine, instead of using a human language, we use all mathematical symbols to talk, would it be so easy to understand?</p>
<p><img src="http://www.clker.com/cliparts/8/0/d/b/1197149806969053368nicubunu_Victory.svg.hi.png" style="width: 64px;" /><br />
What does this picture mean? It might be 2? or victory? But if I say, &#8220;two&#8221; or &#8220;victory&#8221; then it&#8217;s clear.  There are places where simple symbols and icons are helpful (think about iPhone app icons and math problems) while there are some other places where verbose instructions are helpful.  Verbosity in Java, in fact, helps you understand the code written by you or others.  It doesn&#8217;t mean there is no room for <a href="http://openjdk.java.net/projects/lambda" title="Project Lambda" alt="Project Lambda">Lambda (closure)</a> in Java though.  Java with Lambda can result in much simpler code, but without it, it&#8217;s still not that bad to read.  Anyway, Lambda will come to Java soon (JDK 8 ), and I&#8217;m looking forward to it as <a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html" title="State of the Lambda, December 2011, 4th edition" alt="State of the Lambda, December 2011, 4th edition">it looks much nicer</a> than its initial state.  I do functional programming using Java in many places in my project so it would be nice to have Lambda, but without it, I&#8217;m still fine.  What I more desire to have in Java is a way to retrieve the names of method parameters using <a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)" title="Reflection" alt="Reflection">reflection</a> (or some other simple and easy way).  I had to use <a href="http://en.wikipedia.org/wiki/ObjectWeb_ASM" title="ObjectWeb ASM" alt="ObjectWeb ASM">ASM</a> instead to solve this issue.  Why do I need that?  I needed it to develop <a href="http://projects.elixirian.org/json-statham" title="JSON Statham, Java/Json Mapper" alt="JSON Statham, Java/Json Mapper">JSON Statham</a>, Java/Json mapper library, to use one of my projects that is <a href="http://www.mqlicker.com" title="mQlicker, audience interaction system / audience response system" alt="mQlicker, audience response system / audience interaction system">mQlicker (audience response system)</a>.  I can keep using ASM but it&#8217;s a library to decompose and modify Java bytecode so there can be some situations where I cannot use it (e.g. Android uses its own bytecode that is dalvik bytecode, and ASM doesn&#8217;t support it as far as I know).</p>
<p>Some people perhaps complain about the design patterns.  If you don&#8217;t need it, you don&#8217;t have to or should not use it.  We do not programme to apply the patterns.  We do programme to solve our problems.  We can use the patterns if these solve our problems.  If applying it causes more problems, don&#8217;t use it.  I don&#8217;t try to apply the patterns first.  I code to solve a problem and later find my solution is actually some pattern A.  It&#8217;s usually like this.  When I know exactly what pattern solves my problem, then of course, I use it, but I&#8217;ve never coded in order to use the patterns I know unless I need to write some example code to show how to use the patterns.</p>
<p>Some others may say like &#8220;Framework A is too heavy and complex. It took me more time to learn than developing apps and still requires more time to develop than the time spent on development without it.&#8221;  If it&#8217;s the case, you should not use it.  You&#8217;ve got lots of other choices so why bother to stick to only one thing?  Albert Einstein said that repeating the same thing over and over again and expecting different results is insane.  You can try something else.  Usually, if you feel like that about the framework you&#8217;re using, it&#8217;s either you don&#8217;t need it or you&#8217;re not good enough to use it.  &#8220;you don&#8217;t need it&#8221; might mean the framework really sucks or it&#8217;s not appropriate to your project.  &#8220;you&#8217;re not good enough to use it&#8221; probably means &#8220;you&#8217;re not good enough YET to use it and need more knowledge to learn it then will be able to use it properly.&#8221;  Either way, try something else as well then you will possibly have some more idea of what to use.  You don&#8217;t have to repeat the same thing and have the same bad result.</p>
<p>I know there are too many bad examples of Java code and projects which are enough to make a really bad impression of Java on people who try to learn and use it.  Fortunately, owing to the Internet, we can easily find good ones too these days.  If I read only those terrible Java code examples and books, I would probably not use Java.  So don&#8217;t read too old Java books and go to some developer&#8217;s websites to find some good Java examples.  I also have to admit that there are really horrible and poorly designed APIs in Java (e.g. JAXP DOM API, java.net.URL, java.util.Calendar, etc.).  There are also no immutable collections in Java JDK (there are unmodifiable collections but these are not really immutable since the collection passed as the parameter of Collections.unmodifiableXxx() methods can be modified by the user of the Collections utility class or any objects having the reference to the parameter collection).  These are bad, but it can be solved by using other nice libraries (e.g. XStream, XOM, dom4j, Joda-Time, DATE4J, Apache Commons, Guava, etc.).</p>
<p>Don&#8217;t be extremist.  Object-oriented programming or functional programming is not the answer to your problems.  You may need both to solve your problem or neither might help you solve your issue.  It&#8217;s just one of the tools you can use to solve your problems.  Don&#8217;t waste your time to argue which is superior to the other.</p>
<p>By the way, I don&#8217;t like Java.  It&#8217;s just a tool.  I can use whatever tools that solve or help me solve my problems.  Wouldn&#8217;t you feel weird if I say &#8220;I like a hammer but hate a screwdriver&#8221;?  I neither like nor dislike these tools.  I just need a hammer to put a nail into a well and a screwdriver to tighten a screw.  Wouldn&#8217;t it look so stupid if I attempt to pound a nail with a screwdriver or try to tighten a screw using a hammer?  I use Java as it is just a proper tool to solve some of my problems.  For other problems, I use some other tools.</p>
<p>Hmmm, come to think of it, I&#8217;d rather not waste my time on this kind of topic anymore.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2012/02/27/do-you-hate-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easier and Better Way to Use JDBC</title>
		<link>http://blog.lckymn.com/2011/09/11/easier-and-better-way-to-use-jdbc/</link>
		<comments>http://blog.lckymn.com/2011/09/11/easier-and-better-way-to-use-jdbc/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 20:51:52 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[Mine]]></category>
		<category><![CDATA[Persistence]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Callback]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[DB]]></category>
		<category><![CDATA[First-Class Function]]></category>
		<category><![CDATA[JDBC tutorial]]></category>
		<category><![CDATA[Strategy Pattern]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=599</guid>
		<description><![CDATA[<p>I can still see many tutorials of <a href="http://en.wikipedia.org/wiki/Java_Database_Connectivity">JDBC</a> that are not really talking about how JDBC programming can be done easily and more practically &#038; efficiently. I can understand that those tutorials are to give a very basic level of knowledge of JDBC. Besides, we do often not use JDBC directly any more these days. There are easier and simpler solutions like <a href="http://en.wikipedia.org/wiki/Object-relational_mapping">Object Relational Mapping (ORM)</a> and other persistence frameworks. I use <a href="http://en.wikipedia.org/wiki/Java_Persistence_API">Java Persistence API (JPA)</a> with <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2011/09/11/easier-and-better-way-to-use-jdbc/">Easier and Better Way to Use JDBC</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>I can still see many tutorials of <a href="http://en.wikipedia.org/wiki/Java_Database_Connectivity">JDBC</a> that are not really talking about how JDBC programming can be done easily and more practically &#038; efficiently.  I can understand that those tutorials are to give a very basic level of knowledge of JDBC. Besides, we do often not use JDBC directly any more these days. There are easier and simpler solutions like <a href="http://en.wikipedia.org/wiki/Object-relational_mapping">Object Relational Mapping (ORM)</a> and other persistence frameworks. I use <a href="http://en.wikipedia.org/wiki/Java_Persistence_API">Java Persistence API (JPA)</a> with <a href="http://en.wikipedia.org/wiki/Hibernate_(Java)">Hibernate</a> and <a href="http://www.querydsl.com">QueryDSL</a> (Personally, I think QueryDSL is great. I cannot imagine life without QueryDSL anymore when using JPA. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ). There are also other choices. For instance, <a href="http://en.wikipedia.org/wiki/EclipseLink">EclipseLink</a> and <a href="http://en.wikipedia.org/wiki/OpenJPA">OpenJPA</a> both of which are JPA implementations, <a href="http://en.wikipedia.org/wiki/Java_Data_Objects">Java Data Objects (JDO)</a>, <a href="http://en.wikipedia.org/wiki/MyBatis">MyBatis</a>, the successor of <a href="http://en.wikipedia.org/wiki/IBATIS">iBATIS</a>, and so on.</p>
<p>However, there may come a time when you need to directly use JDBC.  It can be developing an application which requires accessing and using database or for developing your own Java persistence framework. One way or another it is good to learn this very fundamental Java persistence technology to get some good things from it as well as its drawback in order to avoid it.  I am not going to talk about what JDBC is or how to use it as there are plenty of other tutorials explaining these on the Internet.  What I am going to do is talking about better and easier way to use JDBC.  I will not cover every single detail about it though, as my point here is giving some idea to use it better and there are already known solutions that provide what I am going to explain.</p>
<p>There are four steps to take to explain the better way of using JDBC. First of all, I will show a typical way to use JDBC then point out problems in it. After that analyse it to find a better way. Finally, I will implement it.</p>
<h2>Preparation</h2>
<h3>Database and JDBC Driver</h3>
<p>In my examples, I&#8217;ve used MySQL 5.1 and MySQL Connection/J 5.1.17 downloaded from the <a href="http://www.mysql.com/downloads/connector/j">Connector/J download page</a> on the MySQL website.</p>
<p>mysql-connector-java-5.1.17.zip</p>
<p>If you don&#8217;t want to become a user of the site, you can click the &#8220;No thanks, just take me to the downloads!&#8221; link at the bottom.<br />
What you need is only one jar file that is mysql-connector-java-5.1.17-bin.jar in the zip file.</p>
<h3>Java Beans</h3>
<p>There are three JavaBeans used in the example to contain the data from the database.</p>
<pre class="brush: java; title: ; notranslate">
public class Person
{
  private Long id;
  private String surname;
  private String givenName;
  private Address address;

  // getters and setters omitted.
}
</pre>
<pre class="brush: java; title: ; notranslate">
public class Address
{
  private String street;
  private String suburb;
  private String state;
  private String country;
  private String postcode;
  private Date birthday;

  // constructors, getters and setters omitted.
}
</pre>
<pre class="brush: java; title: ; notranslate">
import java.util.Date;

public class Book
{
  private Long id;
  private String title;
  private String authours;
  private String edition;
  private String isbn10;
  private String isbn13;
  private String publisher;
  private Date publishingDate;

  // getters and setters omitted.
}
</pre>
<pre class="brush: java; title: ; notranslate">
</pre>
<h2>1. Typical Way to Use JDBC</h2>
<p>Here is a very typical way to use JDBC when retrieving data from the database.</p>
<pre class="brush: java; title: ; notranslate">
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;

try
{
  // get connection.
  connection = DriverManager.getConnection(&quot;jdbc:mysql://localhost:3306/testdb&quot;,
                                           &quot;testuser&quot;,
                                           &quot;1234&quot;);

  final String sql = &quot;SELECT * FROM people&quot;;
  
  // get PreparedStatement
  statement = connection.prepareStatement(sql);
  
  // run the query and get the result stored in the ResultSet.
  resultSet = statement.executeQuery();
  
  final List&lt;Person&gt; people = new ArrayList&lt;Person&gt;();
  while (resultSet.next())
  {
    // Map each row to a Person object and add it to the Person List, people.
    final Person person = new Person();
    person.setId(resultSet.getLong(&quot;person_id&quot;));
    person.setSurname(resultSet.getString(&quot;surname&quot;));
    person.setGivenName(resultSet.getString(&quot;given_name&quot;));
    final Address address =
      new Address(resultSet.getString(&quot;street&quot;),
          resultSet.getString(&quot;city&quot;),
          resultSet.getString(&quot;state&quot;),
          resultSet.getString(&quot;country&quot;),
          resultSet.getString(&quot;postcode&quot;));
    person.setAddress(address);
    person.setBirthday(new Date(resultSet
                          .getDate(&quot;birthday&quot;)
                          .getTime()));
    people.add(person);
  }
  System.out.println(people);
}
catch (final SQLException e)
{
  // you MUST catch SQLException exception
  // or add the throws clause having SQLException to the method declaration.
  e.printStackTrace();
}
finally
{
  // close ResultSet, PreparedStatement and Connection.
  if (null != resultSet)
  {
    try
    {
      resultSet.close();
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
  }
  if (null != statement)
  {
    try
    {
      statement.close();
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
  }
  if (null != connection)
  {
    try
    {
      connection.close();
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
  }
}
</pre>
<h2>2. Problems</h2>
<p>Now, I will make <a href="http://en.wikipedia.org/wiki/Data_access_object">DAO</a>s for Person and Book objects to examine what issues we can have when we follow the typical way to use JDBC mentioned above. Here is the PersonDao interface.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_old.dao;

import java.util.List;

import com.lckymn.kevin.tutorial.jdbc_old.beans.Person;

public interface PersonDao
{
  Person find(Long id);
  List&lt;Person&gt; findPeopleByState(String state);
  List&lt;Person&gt; getAllPeople();
}
</pre>
<p>The following one is the BookDao interface.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_old.dao;

import java.util.List;

import com.lckymn.kevin.tutorial.jdbc_old.beans.Book;

public interface BookDao
{
  Book find(Long id);
  List&lt;Book&gt; findBooksByPublisher(String publisher);
}
</pre>
<p>Before making the implementations of these, I will create an abstract class for both DAOs.</p>
<pre class="brush: java; title: ; notranslate">
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public abstract class AbstractDao
{
  private final String url;
  private final String username;
  private final String password;

  public AbstractDao(final String url, final String username, final String password)
  {
    this.url = url;
    this.username = username;
    this.password = password;
  }

  protected final Connection getConnection() throws SQLException
  {
    /*
     * depending on the version of JDBC (prior to 4.0) you may need to load the driver first.
     */
    return DriverManager.getConnection(url, username, password);
  }
}
</pre>
<p>Or for better use of database connection, Using <a href="http://en.wikipedia.org/wiki/Connection_pool">Connection Pool</a> and <a href="http://en.wikipedia.org/wiki/Datasource">DataSource</a> is desirable.</p>
<pre class="brush: java; title: ; notranslate">
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

public abstract class AbstractDao
{
  private final DataSource dataSource;

  public AbstractDao(final DataSource dataSource)
  {
    this.dataSource = dataSource;
  }

  protected final Connection getConnection() throws SQLException
  {
    return dataSource.getConnection();
  }
}
</pre>
<p>Here is the implementation of PersonDao. The PersonDao extends AbstractDao thus it can get the Connection from the <code>getConnection()</code> method in the super class.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_old.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lckymn.kevin.tutorial.jdbc_old.beans.Address;
import com.lckymn.kevin.tutorial.jdbc_old.beans.Person;
import com.lckymn.kevin.tutorial.jdbc_old.dao.AbstractDao;
import com.lckymn.kevin.tutorial.jdbc_old.dao.PersonDao;

public class PersonDaoImpl extends AbstractDao implements PersonDao
{
  // constructor omitted...

  @Override
  public Person find(final Long id)
  {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    final List&lt;Person&gt; result = new ArrayList&lt;Person&gt;();
    try
    {
      connection = getConnection();
      final String sql = &quot;SELECT * FROM people WHERE person_id = ?&quot;;
      statement = connection.prepareStatement(sql);
      statement.setLong(1, id);
      resultSet = statement.executeQuery();
      while (resultSet.next())
      {
        final Person person = new Person();
        person.setId(resultSet.getLong(&quot;person_id&quot;));
        person.setSurname(resultSet.getString(&quot;surname&quot;));
        person.setGivenName(resultSet.getString(&quot;given_name&quot;));
        final Address address =
          new Address(resultSet.getString(&quot;street&quot;),
              resultSet.getString(&quot;city&quot;),
              resultSet.getString(&quot;state&quot;),
              resultSet.getString(&quot;country&quot;),
              resultSet.getString(&quot;postcode&quot;));
        person.setAddress(address);
        person.setBirthday(new Date(resultSet
                              .getDate(&quot;birthday&quot;)
                              .getTime()));
        result.add(person);
      }
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (null != resultSet)
        try { resultSet.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != statement)
        try { statement.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != connection)
        try { connection.close(); }
        catch (final SQLException e) { e.printStackTrace(); }
    }
    return result.isEmpty() ? null : result.get(0);
  }

  @Override
  public List&lt;Person&gt; findPeopleByState(final String state)
  {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    final List&lt;Person&gt; result = new ArrayList&lt;Person&gt;();
    try
    {
      connection = getConnection();
      final String sql = &quot;SELECT * FROM people WHERE state = ?&quot;;
      statement = connection.prepareStatement(sql);
      statement.setString(1, state);
      resultSet = statement.executeQuery();
      while (resultSet.next())
      {
        final Person person = new Person();
        person.setId(resultSet.getLong(&quot;person_id&quot;));
        person.setSurname(resultSet.getString(&quot;surname&quot;));
        person.setGivenName(resultSet.getString(&quot;given_name&quot;));
        final Address address =
          new Address(resultSet.getString(&quot;street&quot;),
              resultSet.getString(&quot;city&quot;),
              resultSet.getString(&quot;state&quot;),
              resultSet.getString(&quot;country&quot;),
              resultSet.getString(&quot;postcode&quot;));
        person.setAddress(address);
        person.setBirthday(new Date(resultSet
                              .getDate(&quot;birthday&quot;)
                              .getTime()));
        result.add(person);
      }
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (null != resultSet)
        try { resultSet.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != statement)
        try { statement.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != connection)
        try { connection.close(); }
        catch (final SQLException e) { e.printStackTrace(); }
    }
    return result;
  }

  @Override
  public List&lt;Person&gt; getAllPeople()
  {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    final List&lt;Person&gt; result = new ArrayList&lt;Person&gt;();
    try
    {
      connection = getConnection();
      final String sql = &quot;SELECT * FROM people&quot;;
      statement = connection.prepareStatement(sql);
      resultSet = statement.executeQuery();
      while (resultSet.next())
      {
        final Person person = new Person();
        person.setId(resultSet.getLong(&quot;person_id&quot;));
        person.setSurname(resultSet.getString(&quot;surname&quot;));
        person.setGivenName(resultSet.getString(&quot;given_name&quot;));
        final Address address =
          new Address(resultSet.getString(&quot;street&quot;),
              resultSet.getString(&quot;city&quot;),
              resultSet.getString(&quot;state&quot;),
              resultSet.getString(&quot;country&quot;),
              resultSet.getString(&quot;postcode&quot;));
        person.setAddress(address);
        person.setBirthday(new Date(resultSet
                              .getDate(&quot;birthday&quot;)
                              .getTime()));
        result.add(person);
      }
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (null != resultSet)
        try { resultSet.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != statement)
        try { statement.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != connection)
        try { connection.close(); }
        catch (final SQLException e) { e.printStackTrace(); }
    }
    return result;
  }
}
</pre>
<p>As you can see, there is too much boilerplate code here. Then what about the implementation of  BookDao?</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_old.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lckymn.kevin.tutorial.jdbc_old.beans.Book;
import com.lckymn.kevin.tutorial.jdbc_old.dao.AbstractDao;
import com.lckymn.kevin.tutorial.jdbc_old.dao.BookDao;

public class BookDaoImpl extends AbstractDao implements BookDao
{
  public BookDaoImpl(final String url, final String username, final String password)
  {
    super(url, username, password);
  }

  @Override
  public Book find(final Long id)
  {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    final List&lt;Book&gt; result = new ArrayList&lt;Book&gt;();
    try
    {
      connection = getConnection();
      final String sql = &quot;SELECT * FROM book WHERE book_id = ?&quot;;
      statement = connection.prepareStatement(sql);
      statement.setLong(1, id);
      resultSet = statement.executeQuery();
      while (resultSet.next())
      {
        final Book book = new Book();
        book.setId(resultSet.getLong(&quot;book_id&quot;));
        book.setTitle(resultSet.getString(&quot;title&quot;));
        book.setAuthours(resultSet.getString(&quot;authours&quot;));
        book.setEdition(resultSet.getString(&quot;edition&quot;));
        book.setIsbn10(resultSet.getString(&quot;isbn10&quot;));
        book.setIsbn13(resultSet.getString(&quot;isbn13&quot;));
        book.setPublisher(resultSet.getString(&quot;publisher&quot;));
        book.setPublishingDate(resultSet.getDate(&quot;publishing_date&quot;));
        result.add(book);
      }
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (null != resultSet)
        try { resultSet.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != statement)
        try { statement.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != connection)
        try { connection.close(); }
        catch (final SQLException e) { e.printStackTrace(); }
    }
    return result.isEmpty() ? null : result.get(0);
  }

  @Override
  public List&lt;Book&gt; findBooksByPublisher(final String publisher)
  {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    final List&lt;Book&gt; result = new ArrayList&lt;Book&gt;();
    try
    {
      connection = getConnection();
      final String sql = &quot;SELECT * FROM book WHERE publisher = ?&quot;;
      statement = connection.prepareStatement(sql);
      statement.setString(1, publisher);
      resultSet = statement.executeQuery();
      while (resultSet.next())
      {
        final Book book = new Book();
        book.setId(resultSet.getLong(&quot;book_id&quot;));
        book.setTitle(resultSet.getString(&quot;title&quot;));
        book.setAuthours(resultSet.getString(&quot;authours&quot;));
        book.setEdition(resultSet.getString(&quot;edition&quot;));
        book.setIsbn10(resultSet.getString(&quot;isbn10&quot;));
        book.setIsbn13(resultSet.getString(&quot;isbn13&quot;));
        book.setPublisher(resultSet.getString(&quot;publisher&quot;));
        book.setPublishingDate(resultSet.getDate(&quot;publishing_date&quot;));
        result.add(book);
      }
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (null != resultSet)
        try { resultSet.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != statement)
        try { statement.close(); }
        catch (final SQLException e) { e.printStackTrace(); }

      if (null != connection)
        try { connection.close(); }
        catch (final SQLException e) { e.printStackTrace(); }
    }
    return result;
  }
}
</pre>
<p>Just the same&#8230; OK, now I will compare just one method in each DAO and try to find if there are any similarities in these methods. One method from PersonDaoImpl is <code>findPeopleByState(String)</code> and the other one from BookDaoImpl is <code>findBooksByPublisher(String)</code>.</p>
<p>Let&#8217;s see what are different.<br />
<div id="attachment_610" class="wp-caption aligncenter" style="width: 891px"><a href="http://blog.lckymn.com/wp-content/uploads/2011/09/method-comparison-between-person-dao-and-book-dao1.png"><img src="http://blog.lckymn.com/wp-content/uploads/2011/09/method-comparison-between-person-dao-and-book-dao1.png" alt="Method Comparison Between PersonDao and BookDao" title="Method Comparison Between PersonDao and BookDao" width="881" height="821" class="size-full wp-image-610" /></a><p class="wp-caption-text">Method Comparison Between PersonDao and BookDao</p></div></p>
<p>As you can see, except for a few parts highlighted, I&#8217;ve just repeated the same code. That means if the user of the DAO can dynamically give the code for these few differences when using it, I do not need to repeat the same code over and over again.</p>
<p>There is another problem in the catch block that catches the SQLException which can be thrown in the try block containing the main part of the code snippet.</p>
<pre class="brush: java; title: ; notranslate">
}
catch (final SQLException e)
{
  e.printStackTrace(); // It just prints the StackTrace and ignores the exception.
}
finally
{
</pre>
<p>It just prints the StackTrace and ignores the exception, and this may cause a more serious problem as the exception is simply ignored so the programmers cannot easily find what went wrong. I need to deal with it too.</p>
<h2>3. Finding Better Way</h2>
<p>I will create a JdbcManager which takes care of selection, insertion, update and deletion of data.</p>
<p>I will try something very easy to do first. In the typical DAO code, every method has a finally block having really ugly code snippet to close ResultSet, Statement and Connection. I am sick of it so want to get rid of it first, but I cannot simply remove that code as it&#8217;s absolutely necessary therefore it&#8217;s there. Then I can make a method which closes those objects quietly without throwing any exception, for it&#8217;s already in the finally block and there might be already an exception thrown. So I don&#8217;t want the finally block to throw another exception which interrupts the fist exception.</p>
<p>My JdbcManager class will have the following method to close ResultSet, Statement and Connection.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
private void closeQuietly(final Connection connection,
                          final PreparedStatement statement,
                          final ResultSet resultSet)
{
  if (null != resultSet)
    try { resultSet.close(); }
    catch (final SQLException e) { e.printStackTrace(); } // or log properly

  if (null != statement)
    try { statement.close(); }
    catch (final SQLException e) { e.printStackTrace(); } // or log properly

  if (null != connection)
    try { connection.close(); }
    catch (final SQLException e) { e.printStackTrace(); } // or log properly
}
</pre>
<p>So now <code>findPeopleByState(String)</code> looks like this.</p>
<pre class="brush: java; gutter: false; highlight: [1,7,11,13,17,18,19,20,21,22,23,24,25,26,27,28,29,30,36]; title: ; notranslate">
public List&lt;Person&gt; findPeopleByState(final String state)
{
  Connection connection = null;
  PreparedStatement statement = null;
  ResultSet resultSet = null;

  final List&lt;Person&gt; result = new ArrayList&lt;Person&gt;();
  try
  {
    connection = getConnection();
    final String sql = &quot;SELECT * FROM people WHERE state = ?&quot;;
    statement = connection.prepareStatement(sql);
    statement.setString(1, state);
    resultSet = statement.executeQuery();
    while (resultSet.next())
    {
      final Person person = new Person();
      person.setId(resultSet.getLong(&quot;person_id&quot;));
      person.setSurname(resultSet.getString(&quot;surname&quot;));
      person.setGivenName(resultSet.getString(&quot;given_name&quot;));
      final Address address =
        new Address(resultSet.getString(&quot;street&quot;),
                    resultSet.getString(&quot;city&quot;),
                    resultSet.getString(&quot;state&quot;),
                    resultSet.getString(&quot;country&quot;),
                    resultSet.getString(&quot;postcode&quot;));
      person.setAddress(address);
      person.setBirthday(new Date(resultSet
                            .getDate(&quot;birthday&quot;)
                            .getTime()));
      result.add(person);
    }
  }
  catch (final SQLException e)
  {
    e.printStackTrace();
  }
  finally
  {
    closeQuietly(connection, statement, resultSet);
  }
  return result;
}
</pre>
<p><a id="use-generics"></a></p>
<p>Now think about the highlighted lines that are different depending on what type of object should be returned.<br />
The first one is the method signature. I will talk about the parameters later and now focus on only the return type.</p>
<pre class="brush: java; gutter: false; highlight: [1]; title: ; notranslate">
public List&lt;Person&gt; findPeopleByState(final String state)
</pre>
<p>It returns a List of Person but what if I want to get a List of Book? So the return type is of type List, but the type of the element should be contained in the List is undecided. It should be pending until the user of the method specifies it. In this kind of situation, what do we normally use? When we design an API and want to defer specifying what type to use until the user of the API decides it with providing compile-time type safety, we use <a href="http://en.wikipedia.org/wiki/Generics_in_Java">Generics</a> in Java.<br />
So I can just easily make the method a generic method so that the return type would be depending on how the user of the method uses it.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
public &lt;T&gt; T findPeopleByState( *don't worry about params for a while* )
</pre>
<p>The second part is the same, I don&#8217;t know what type of object the user wants to have in the List, so I just use a generic type parameter T.<br />
So I&#8217;ve changed this</p>
<pre class="brush: java; gutter: false; highlight: [1]; title: ; notranslate">
final List&lt;Person&gt; result = new ArrayList&lt;Person&gt;();
</pre>
<p>to</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
final List&lt;T&gt; result = new ArrayList&lt;T&gt;();
</pre>
<p>The third one is easy. It can easily become a parameter of the method.</p>
<pre class="brush: java; gutter: false; highlight: [1]; title: ; notranslate">
final String sql = &quot;SELECT * FROM people WHERE state = ?&quot;;
</pre>
<p>So the method signature would be like</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
public &lt;T&gt; T findPeopleByState(String sql, *don't worry about the rest params for now* )
</pre>
<p>Next one also looks simple. It&#8217;s just one line of code. Well, it is one line in this example but can be many lines depending on the given parameter values.</p>
<pre class="brush: java; gutter: false; highlight: [1]; title: ; notranslate">
statement.setString(1, state);
</pre>
<p>So it might be like</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
statement.setLong(1, longValue);
statement.setString(2, stringValue);
statement.setBoolean(3, booleanValue);
</pre>
<p>So it seems like it will possibly have many parameters from the user of my method. So I think I should use some kind of Collection type containing the parameters or an array of Object containing these because the types of the parameters can vary. Wait. More conveniently I can just use varargs so that the user of my method doesn&#8217;t need to create any extra instance of collection or array to pass the parameters although using varargs results in creation of an array by compiler, yet in the user&#8217;s point of view, it&#8217;s hidden so can be very convenient.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
public &lt;T&gt; T findPeopleByState(String sql,
                               //possibly more params here
                               Object ... params)
</pre>
<p>The types of the parameters can vary so I put Object type varargs. Now I need to set the parameters to the PreparedStatement. Since the varargs is actually an array, I can iterate over it to get each parameter then I use an index to get a parameter and index + 1 to set the parameterIndex in the PreparedStatement as it starts from 1. I will cover here only primitive types (including boxed ones), String and other commonly used reference types in db programming which are Date, Calendar and BigDecimal. All the other types will cause an IllegalArgumentException. It can of course improve but I am just giving an idea to use it better so am trying to make it just simple enough to understand with providing the idea. So the code would be</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
private void setParameters(final PreparedStatement statement, final Object... parameters) throws SQLException
{
  for (int i = 0, length = parameters.length; i &lt; length; i++)
  {
    final Object parameter = parameters[i];
    final int parameterIndex = i + 1;
    if (null == parameter)
    {
      statement.setObject(parameterIndex, null);
    }
    else if (parameter instanceof Boolean)
    {
      statement.setBoolean(parameterIndex, (Boolean) parameter);
    }
    else if (parameter instanceof Character)
    {
      statement.setString(parameterIndex, String.valueOf(parameter));
    }
    else if (parameter instanceof Byte)
    {
      statement.setByte(parameterIndex, (Byte) parameter);
    }
    else if (parameter instanceof Short)
    {
      statement.setShort(parameterIndex, (Short) parameter);
    }
    else if (parameter instanceof Integer)
    {
      statement.setInt(parameterIndex, (Integer) parameter);
    }
    else if (parameter instanceof Long)
    {
      statement.setLong(parameterIndex, (Long) parameter);
    }
    else if (parameter instanceof Float)
    {
      statement.setFloat(parameterIndex, (Float) parameter);
    }
    else if (parameter instanceof Double)
    {
      statement.setDouble(parameterIndex, (Double) parameter);
    }
    else if (parameter instanceof String)
    {
      statement.setString(parameterIndex, (String) parameter);
    }
    else if (parameter instanceof Date)
    {
      statement.setDate(parameterIndex, new java.sql.Date(((Date) parameter)
                                            .getTime()));
    }
    else if (parameter instanceof Calendar)
    {
      statement.setDate(parameterIndex, new java.sql.Date(((Calendar) parameter)
                                            .getTimeInMillis()));
    }
    else if (parameter instanceof BigDecimal)
    {
      statement.setBigDecimal(parameterIndex, (BigDecimal) parameter);
    }
    else
    {
      throw new IllegalArgumentException(String.format(
          &quot;Unknown type of the parameter is found. [param: %s, paramIndex: %s]&quot;,
          parameter,
          parameterIndex));
    }
  }
}
</pre>
<p>It can be used by other methods in the JdbcManager as well, so I made it a method.</p>
<p>Next is</p>
<pre class="brush: java; gutter: false; highlight: [3,4,5,6,7,8,9,10,11,12,13,14,15,16]; title: ; notranslate">
while (resultSet.next())
{
  final Person person = new Person();
  person.setId(resultSet.getLong(&quot;person_id&quot;));
  person.setSurname(resultSet.getString(&quot;surname&quot;));
  person.setGivenName(resultSet.getString(&quot;given_name&quot;));
  final Address address =
    new Address(resultSet.getString(&quot;street&quot;),
                resultSet.getString(&quot;city&quot;),
                resultSet.getString(&quot;state&quot;),
                resultSet.getString(&quot;country&quot;),
                resultSet.getString(&quot;postcode&quot;));
  person.setAddress(address);
  person.setBirthday(new Date(resultSet
                        .getDate(&quot;birthday&quot;)
                        .getTime()));
  result.add(person);
}
</pre>
<p>The highlighted part should be done by the user of the API. The JdbcManager does&#8217;t know what should be there nor can it guess what data the user of it wants to retrieve from the database. It looks like I can use <a href="http://en.wikipedia.org/wiki/Callback_(computer_programming)">Callback</a> here. Java does not have <a href="http://en.wikipedia.org/wiki/First-class_function">First-Class Function</a> yet (Java will have First-Class Function in the form of <a href="http://en.wikipedia.org/wiki/Lambda_(programming)">lambda expression</a> in the <a href="http://en.wikipedia.org/wiki/Java_version_history#Java_SE_8">Java SE 8</a>. <a href="http://openjdk.java.net/projects/lambda/">Click here to get more details about Project Lambda</a>), but I can define an interface which maps data in a ResultSet row to a Java object and let the user pass an instance of class implementing the interface or an anonymous class instance of the interface can be used too.<br />
What I need to consider is the return type and the ResultSet as I&#8217;m now trying to map the data in the ResultSet to a Java object (return type). So the mapper interface should look like.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

public interface RowMapper&lt;T&gt;
{
  T map(ResultSet resultSet) throws SQLException;
}
</pre>
<p>Notice that I&#8217;ve also added the throws clause having SQLException as using ResultSet requires it and that&#8217;s why we put try-catch block in our code using JDBC. The SQLException thrown in the <code>map()</code> method will be handled by the try-catch block in the main part of the JdbcManager <code>select()</code> method.</p>
<p>There is one last issue left. Now I need to take care of ignoring SQLException in the catch block.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
}
catch (final SQLException e)
{
  e.printStackTrace();
}
finally
</pre>
<p>I can properly log it instead of just calling the <code>printStackTrace()</code> method in the SQLException, but it&#8217;s not enough. I don&#8217;t want to just ignore it as it may cause some serious issue in runtime. However, I don&#8217;t want to re-throw it either because then the caller of this method or &#8220;the caller of the caller&#8221; of the method or in the worst case, all the methods in the method call hierarchy have to deal with the SQLException. Thus I want to create my own unchecked exception (an exception that extends RuntimeException) which wraps the SQLException. It is beneficial not only because the caller of the method doesn&#8217;t need to catch or re-throw it but because it is also understandable by the caller of the method even after I decide not to use JDBC at all so it doesn&#8217;t have any SQLException any more. In this case, if I used SQLException, I would have to change the code in the caller-side as the caller would directly deal with it.</p>
<p>Here is my new Exception for data access.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.exception;

public class DataAccessException extends RuntimeException
{
  private static final long serialVersionUID = 1L;

  public DataAccessException()
  {
  }

  public DataAccessException(final String message, final Throwable cause)
  {
    super(message, cause);
  }

  public DataAccessException(final String message)
  {
    super(message);
  }

  public DataAccessException(final Throwable cause)
  {
    super(cause);
  }
}
</pre>
<p>I also want to have another exception that extends it in order to indicate data access connection failure.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.exception;

public class DataAccessConnectionFailureException extends DataAccessException
{
  private static final long serialVersionUID = 1L;

  public DataAccessConnectionFailureException(final Throwable cause)
  {
    super(cause);
  }
}
</pre>
<p>Finally one for general data access operation problems.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.exception;

public class DataAccessOperationErrorException extends DataAccessException
{
  private static final long serialVersionUID = 1L;

  public DataAccessOperationErrorException()
  {
  }

  public DataAccessOperationErrorException(final String message, final Throwable cause)
  {
    super(message, cause);
  }

  public DataAccessOperationErrorException(final String message)
  {
    super(message);
  }

  public DataAccessOperationErrorException(final Throwable cause)
  {
    super(cause);
  }
}
</pre>
<p>I can replace the old code that prints stack trace with</p>
<pre class="brush: java; title: ; notranslate">
}
catch (final SQLException e)
{
  throw new DataAccessOperationErrorException(e);
}
finally
</pre>
<p>So with all the solutions I mentioned above, my new code now becomes</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
public &lt;T&gt; List&lt;T&gt; select(final String sql,
                          final RowMapper&lt;T&gt; rowMapper,
                          final Object... parameters)
      throws DataAccessException
{
  Connection connection = null;
  PreparedStatement statement = null;
  ResultSet resultSet = null;

  final List&lt;T&gt; result = new ArrayList&lt;T&gt;();
  try
  {
    connection = getConnection();
    statement = connection.prepareStatement(sql);
    setParameters(statement, parameters);
    resultSet = statement.executeQuery();
    while (resultSet.next())
    {
      result.add(rowMapper.map(resultSet));
    }
  }
  catch (final SQLException e)
  {
    throw new DataAccessOperationFailureException(e);
  }
  finally
  {
    closeQuietly(connection, statement, resultSet);
  }
  return result;
}
</pre>
<p>It&#8217;s time to use it. Before using it, I&#8217;ll show my JdbcManager interface and the implementing class.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.jdbc;

import java.util.List;

import com.lckymn.kevin.tutorial.jdbc_better.exception.DataAccessException;

/**
 * @author Lee, SeongHyun (Kevin) / &lt;a href=&quot;http://blog.lckymn.com&quot;&gt;Kevin&amp;#39;s Blog&lt;/a&gt;
 * @version 0.0.1 (2011-09-04)
 */
public interface JdbcManager
{
  &lt;T&gt; List&lt;T&gt; select(String sql, RowMapper&lt;T&gt; rowMapper, Object... parameters) throws DataAccessException;

  int update(final String sql, final Object... parameters) throws DataAccessException;
}
</pre>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.jdbc.impl;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.sql.DataSource;

import com.lckymn.kevin.tutorial.jdbc_better.exception.DataAccessConnectionFailureException;
import com.lckymn.kevin.tutorial.jdbc_better.exception.DataAccessException;
import com.lckymn.kevin.tutorial.jdbc_better.exception.DataAccessOperationErrorException;
import com.lckymn.kevin.tutorial.jdbc_better.jdbc.JdbcManager;
import com.lckymn.kevin.tutorial.jdbc_better.jdbc.RowMapper;

/**
 * @author Lee, SeongHyun (Kevin) / &lt;a href=&quot;http://blog.lckymn.com&quot;&gt;Kevin&amp;#39;s Blog&lt;/a&gt;
 * @version 0.0.1 (2011-09-04)
 */
public class JdbcManagerImpl implements JdbcManager
{
  private final DataSource dataSource;

  public JdbcManagerImpl(final DataSource dataSource)
  {
    this.dataSource = dataSource;
  }

  protected final Connection getConnection()
  {
    try
    {
      return dataSource.getConnection();
    }
    catch (final SQLException e)
    {
      throw new DataAccessConnectionFailureException(e);
    }

  }

  private void closeQuietly(final Connection connection,
                            final PreparedStatement statement,
                            final ResultSet resultSet)
  {
    if (null != resultSet)
      try { resultSet.close(); }
      catch (final SQLException e) { e.printStackTrace(); }

    if (null != statement)
      try { statement.close(); }
      catch (final SQLException e) { e.printStackTrace(); }

    if (null != connection)
      try { connection.close(); }
      catch (final SQLException e) { e.printStackTrace(); }
  }

  private void setParameters(final PreparedStatement statement, final Object... parameters) throws SQLException
  {
    for (int i = 0, length = parameters.length; i &lt; length; i++)
    {
      final Object parameter = parameters[i];
      final int parameterIndex = i + 1;
      if (null == parameter)
      {
        statement.setObject(parameterIndex, null);
      }
      else if (parameter instanceof Boolean)
      {
        statement.setBoolean(parameterIndex, (Boolean) parameter);
      }
      else if (parameter instanceof Character)
      {
        statement.setString(parameterIndex, String.valueOf(parameter));
      }
      else if (parameter instanceof Byte)
      {
        statement.setByte(parameterIndex, (Byte) parameter);
      }
      else if (parameter instanceof Short)
      {
        statement.setShort(parameterIndex, (Short) parameter);
      }
      else if (parameter instanceof Integer)
      {
        statement.setInt(parameterIndex, (Integer) parameter);
      }
      else if (parameter instanceof Long)
      {
        statement.setLong(parameterIndex, (Long) parameter);
      }
      else if (parameter instanceof Float)
      {
        statement.setFloat(parameterIndex, (Float) parameter);
      }
      else if (parameter instanceof Double)
      {
        statement.setDouble(parameterIndex, (Double) parameter);
      }
      else if (parameter instanceof String)
      {
        statement.setString(parameterIndex, (String) parameter);
      }
      else if (parameter instanceof Date)
      {
        statement.setDate(parameterIndex, new java.sql.Date(((Date) parameter).getTime()));
      }
      else if (parameter instanceof Calendar)
      {
        statement.setDate(parameterIndex, new java.sql.Date(((Calendar) parameter).getTimeInMillis()));
      }
      else if (parameter instanceof BigDecimal)
      {
        statement.setBigDecimal(parameterIndex, (BigDecimal) parameter);
      }
      else
      {
        throw new IllegalArgumentException(String.format(
            &quot;Unknown type of the parameter is found. [param: %s, paramIndex: %s]&quot;, parameter, parameterIndex));
      }
    }
  }

  @Override
  public &lt;T&gt; List&lt;T&gt; select(final String sql,
                            final RowMapper&lt;T&gt; rowMapper,
                            final Object... parameters)
      throws DataAccessException
  {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    final List&lt;T&gt; result = new ArrayList&lt;T&gt;();
    try
    {
      connection = getConnection();
      statement = connection.prepareStatement(sql);
      setParameters(statement, parameters);
      resultSet = statement.executeQuery();
      while (resultSet.next())
      {
        result.add(rowMapper.map(resultSet));
      }
    }
    catch (final SQLException e)
    {
      throw new DataAccessOperationErrorException(e);
    }
    finally
    {
      closeQuietly(connection, statement, resultSet);
    }
    return result;
  }

  // the rest code omitted...
}
</pre>
<p>Then my AbstractDao now has the JdbcManager.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.dao;

import com.lckymn.kevin.tutorial.jdbc_better.jdbc.JdbcManager;

/**
 * @author Lee, SeongHyun (Kevin) / &lt;a href=&quot;http://blog.lckymn.com&quot;&gt;Kevin&amp;#39;s Blog&lt;/a&gt;
 * @version 0.0.1 (2011-09-04)
 */
public abstract class AbstractDao
{
  private JdbcManager jdbcManager;

  public AbstractDao(final JdbcManager jdbcManager)
  {
    this.jdbcManager = jdbcManager;
  }

  protected final JdbcManager jdbcManager()
  {
    return jdbcManager;
  }
}
</pre>
<p>So the old DAO methods now look like</p>
<pre class="brush: java; gutter: false; highlight: [10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52]; title: ; notranslate">
@Override
public Person find(final Long id)
{
  final List&lt;Person&gt; result =
    jdbcManager().select(&quot;SELECT * FROM people WHERE person_id = ?&quot;, new RowMapper&lt;Person&gt;() {

      @Override
      public Person map(final ResultSet resultSet) throws SQLException
      {
        final Person person = new Person();
        person.setId(resultSet.getLong(&quot;person_id&quot;));
        person.setSurname(resultSet.getString(&quot;surname&quot;));
        person.setGivenName(resultSet.getString(&quot;given_name&quot;));
        final Address address =
            new Address(resultSet.getString(&quot;street&quot;),
                resultSet.getString(&quot;city&quot;),
                resultSet.getString(&quot;state&quot;),
                resultSet.getString(&quot;country&quot;),
                resultSet.getString(&quot;postcode&quot;));
        person.setAddress(address);
        person.setBirthday(new Date(resultSet
                              .getDate(&quot;birthday&quot;)
                              .getTime()));
        return person;
      }
    }, id);
  return result.isEmpty() ? null : result.get(0);
}

@Override
public List&lt;Person&gt; findPeopleByState(final String state)
{
  return jdbcManager().select(&quot;SELECT * FROM people WHERE state = ?&quot;, new RowMapper&lt;Person&gt;() {

    @Override
    public Person map(final ResultSet resultSet) throws SQLException
    {
      final Person person = new Person();
      person.setId(resultSet.getLong(&quot;person_id&quot;));
      person.setSurname(resultSet.getString(&quot;surname&quot;));
      person.setGivenName(resultSet.getString(&quot;given_name&quot;));
      final Address address =
          new Address(resultSet.getString(&quot;street&quot;),
              resultSet.getString(&quot;city&quot;),
              resultSet.getString(&quot;state&quot;),
              resultSet.getString(&quot;country&quot;),
              resultSet.getString(&quot;postcode&quot;));
      person.setAddress(address);
      person.setBirthday(new Date(resultSet
                            .getDate(&quot;birthday&quot;)
                            .getTime()));
      return person;
    }
  }, state);
}
</pre>
<p>Oh, I can see the RowMapper anonymous classes used in the both methods are the same therefore I can declare constant variable for it and both can just use it.<br />
So my new PersonDaoImpl is</p>
<pre class="brush: java; highlight: [51,52,58,64]; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.lckymn.kevin.tutorial.jdbc_better.beans.Address;
import com.lckymn.kevin.tutorial.jdbc_better.beans.Person;
import com.lckymn.kevin.tutorial.jdbc_better.dao.AbstractDao;
import com.lckymn.kevin.tutorial.jdbc_better.dao.PersonDao;
import com.lckymn.kevin.tutorial.jdbc_better.jdbc.JdbcManager;
import com.lckymn.kevin.tutorial.jdbc_better.jdbc.RowMapper;

/**
 * @author Lee, SeongHyun (Kevin) / &lt;a href=&quot;http://blog.lckymn.com&quot;&gt;Kevin&amp;#39;s Blog&lt;/a&gt;
 * @version 0.0.1 (2011-09-04)
 */
public class PersonDaoImpl extends AbstractDao implements PersonDao
{
  private static final RowMapper&lt;Person&gt; PERSON_MAPPER = new RowMapper&lt;Person&gt;() {
    @Override
    public Person map(final ResultSet resultSet) throws SQLException
    {
      final Person person = new Person();
      person.setId(resultSet.getLong(&quot;person_id&quot;));
      person.setSurname(resultSet.getString(&quot;surname&quot;));
      person.setGivenName(resultSet.getString(&quot;given_name&quot;));
      final Address address =
          new Address(resultSet.getString(&quot;street&quot;),
              resultSet.getString(&quot;city&quot;),
              resultSet.getString(&quot;state&quot;),
              resultSet.getString(&quot;country&quot;),
              resultSet.getString(&quot;postcode&quot;));
      person.setAddress(address);
      person.setBirthday(new Date(resultSet
                            .getDate(&quot;birthday&quot;)
                            .getTime()));
      return person;
    }
  };

  public PersonDaoImpl(final JdbcManager jdbcManager)
  {
    super(jdbcManager);
  }

  @Override
  public Person find(final Long id)
  {
    final List&lt;Person&gt; result = jdbcManager().select(&quot;SELECT * FROM people WHERE person_id = ?&quot;, PERSON_MAPPER, id);
    return result.isEmpty() ? null : result.get(0);
  }

  @Override
  public List&lt;Person&gt; findPeopleByState(final String state)
  {
    return jdbcManager().select(&quot;SELECT * FROM people WHERE state = ?&quot;, PERSON_MAPPER, state);
  }

  @Override
  public List&lt;Person&gt; getAllPeople()
  {
    return jdbcManager().select(&quot;SELECT * FROM people&quot;, PERSON_MAPPER);
  }
}
</pre>
<p>Wow! It&#8217;s really simple now! Just passing an SQL query and parameters with a RowMapper.</p>
<p>OK, it&#8217;s good, but what happens if I want to insert or update or delete data from the database? The JdbcManager interface has the method signature for these but how can I implement it?<br />
It would be simple too.</p>
<pre class="brush: java; title: ; notranslate">
private void rollback(final Connection connection)
{
  if (null != connection)
  {
    try
    {
      connection.rollback();
    }
    catch (final SQLException e)
    {
      e.printStackTrace();
    }
  }
}

@Override
public int update(final String sql, final Object... parameters)
    throws DataAccessException
{
  Connection connection = null;
  PreparedStatement statement = null;

  try
  {
    connection = getConnection();
    connection.setAutoCommit(false);
    statement = connection.prepareStatement(sql);
    setParameters(statement, parameters);
    final int result = statement.executeUpdate();
    connection.commit();
    return result;
  }
  catch (final DataAccessException e)
  {
    rollback(connection);
    throw e;
  }
  catch (final Exception e)
  {
    rollback(connection);
    throw new DataAccessOperationErrorException(e);
  }
  finally
  {
    closeQuietly(connection, statement, null);
  }
}
</pre>
<p>Turn off auto commit so the changes can be rolled back if any Exception is thrown.</p>
<p>There is still room for improvement in JdbcManagerImpl. Instead of having the <code>setParameters()</code> method to set parameter values to the Statement, <a href="http://en.wikipedia.org/wiki/Strategy_pattern">Strategy pattern</a> can be used so that the user of JdbcManager can later inject an object that sets the parameters so how to handle the parameters can be decided by the user of the API.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.tutorial.jdbc_better.jdbc;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Lee, SeongHyun (Kevin) / &lt;a href=&quot;http://blog.lckymn.com&quot;&gt;Kevin&amp;#39;s Blog&lt;/a&gt;
 * @version 0.0.1 (2011-09-04)
 */
public interface PreparedStatementParameterSetter
{
  void setParameters(final PreparedStatement statement, final Object... parameters) throws SQLException;
}
</pre>
<pre class="brush: java; highlight: [29]; title: ; notranslate">
public class JdbcManagerImpl implements JdbcManager
{
  private final DataSource dataSource;
  private final PreparedStatementParameterSetter preparedStatementParameterSetter;

  public JdbcManagerImpl(DataSource dataSource, PreparedStatementParameterSetter preparedStatementParameterSetter)
  {
    this.dataSource = dataSource;
    this.preparedStatementParameterSetter = preparedStatementParameterSetter;
  }

  // code omitted...

  @Override
  public &lt;T&gt; List&lt;T&gt; select(final String sql,
                            final RowMapper&lt;T&gt; rowMapper,
                            final Object... parameters)
      throws DataAccessException
  {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    final List&lt;T&gt; result = new ArrayList&lt;T&gt;();
    try
    {
      connection = getConnection();
      statement = connection.prepareStatement(sql);
      preparedStatementParameterSetter.setParameters(statement, parameters);
      resultSet = statement.executeQuery();
      while (resultSet.next())
      {
        result.add(rowMapper.map(resultSet));
      }
    }
    catch (final SQLException e)
    {
      throw new DataAccessOperationErrorException(e);
    }
    finally
    {
      closeQuietly(connection, statement, resultSet);
    }
    return result;
  }
  
  // ... the rest omitted.
}
</pre>
<p>I think it&#8217;s enough to learn the better way to use JDBC. What I&#8217;ve explained here can be useful for solving other problems too (e.g. reading and writing files).<br />
The code I&#8217;ve posted here is not production-ready. It&#8217;s solely for educational purpose. If you want to use it in practice, I recommend already existing libraries and frameworks which provide what I&#8217;ve explained here. These are well tested so are likely to be better than my in-house JdbcManager. If you use or are willing to use the <a href="http://www.springsource.org/">Spring Framework</a>, you can use its <a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/jdbc.html">JdbcTemplate</a>. If you don&#8217;t or cannot use the Spring Framework, you can choose <a href="http://commons.apache.org/">Apache Commons</a> <a href="http://commons.apache.org/dbutils/">DbUtils</a>.<br />
<br />
<code>=================================================================</code><br />
The source code of &#8220;Easier and Better Way to Use JDBC&#8221; is available <a href="http://goo.gl/HS4ov" target="_blank">-&gt;HERE&lt;-</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2011/09/11/easier-and-better-way-to-use-jdbc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java Uses Call By Sharing</title>
		<link>http://blog.lckymn.com/2010/11/12/java-uses-call-by-sharing/</link>
		<comments>http://blog.lckymn.com/2010/11/12/java-uses-call-by-sharing/#comments</comments>
		<pubDate>Thu, 11 Nov 2010 17:13:38 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[call by reference]]></category>
		<category><![CDATA[call by sharing]]></category>
		<category><![CDATA[call by value]]></category>
		<category><![CDATA[caller]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[Object]]></category>
		<category><![CDATA[parameter]]></category>
		<category><![CDATA[Reference]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=587</guid>
		<description><![CDATA[<p>I just saw [<a href="http://www.jeviathon.com/2010/11/java-it-is-most-certainly-pass-by-value.html">Java: It is most certainly pass by value</a>]. It is very shocking that I can still often see people saying &#8220;Java is call by value&#8221;. I mean, I don&#8217;t really get why it is even controversial. I think it is clear that &#8220;Java is call by value&#8221;. Oh, actually it is more precisely &#8220;<a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing">call by sharing</a>&#8221; (Notice that it is NOT &#8220;<a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference">call by reference</a>&#8220;).</p> <p>Call-by-reference means a reassigned reference to a method parameter variable <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2010/11/12/java-uses-call-by-sharing/">Java Uses Call By Sharing</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>I just saw [<a href="http://www.jeviathon.com/2010/11/java-it-is-most-certainly-pass-by-value.html">Java: It is most certainly pass by value</a>].<br />
It is very shocking that I can still often see people saying &#8220;Java is call by value&#8221;.  I mean, I don&#8217;t really get why it is even controversial.  I think it is clear that &#8220;Java is call by value&#8221;. Oh, actually it is more precisely &#8220;<a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing">call by sharing</a>&#8221; (Notice that it is <b>NOT</b> &#8220;<a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference">call by reference</a>&#8220;).</p>
<p>Call-by-reference means a reassigned reference to a method parameter variable is visible by the caller of the method which means if a new object reference is assigned to the parameter variable in a method then caller will have the newly assigned one after execution of the method whereas call-by-sharing means the new reference is not visible by the caller.  Thus the old reference will still remain after calling the method. That means if a new reference is assigned to the parameter variable, it is visible just within the method thus after execution of the method, the caller will still get the old reference so the same old object.</p>
<p>The people who do not understand the difference between call-by-reference and call-by-sharing do probably not know the difference between assigning a new reference to a variable and changing the state of an object the reference of which is stored in the variable.  I guess, it is presumably caused by their ignorance about a reference of object and the actual object.  They perhaps think a variable is an object itself or that contains an object, yet the variable does not contain an object but the reference of an object. So when we use a variable to change the state of an object or use the methods in it, we are not directly having the actual object but are using the reference of the object stored in the variable in order to access the object.</p>
<p>To sum up, Java uses call-by-sharing NOT call-by-reference. The difference between call-by-reference and call-by-sharing is</p>
<p>call-by-reference: You are able to assign a new reference to a method parameter variable in a method, and it will be visible by the caller of the method so after calling the method, the caller will get the new reference (new object).</p>
<p>call-by-sharing: You are able to assign a new reference to a method parameter variable in a method, BUT it will NOT be visible by the caller of the method so after calling the method, the caller will still get the same old reference which was passed as a method parameter to the method.</p>
<p>In both evaluation strategies, you have access to the reference so are able to change the state of the object the reference of which is stored in the parameter variable if the object is mutable. Therefore it is possible to change the values of the object member variables in the method and these changes are visible by the caller but the caller still see the same old object with a different state from the state it had before calling the method.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2010/11/12/java-uses-call-by-sharing/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Quizzes for Primary Schoolchildren</title>
		<link>http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/</link>
		<comments>http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#comments</comments>
		<pubDate>Thu, 06 May 2010 12:53:40 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[primary schoolchild]]></category>
		<category><![CDATA[primary schoolchildren]]></category>
		<category><![CDATA[quiz]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=548</guid>
		<description><![CDATA[<p>Yesterday (the 5th of May) was the children&#8217;s day, which is an official holiday, in South Korea, (by the way, the day before yesterday was <a href="http://en.wikipedia.org/wiki/Star_Wars_Day" title="Star Wars Day: May the 4th be with you">Star Wars Day</a> <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) and I found that <a href="http://xeraph.com" title="Xeraph">Xeraph</a>, who is the CEO of the IT security company named <a href="http://nchovy.com/" title="NCHOVY Inc.">Nchovy</a>, as well as the creator &#038; core programmer of the OSGi based opensource security platform, <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/">Quizzes for Primary Schoolchildren</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>Yesterday (the 5th of May) was the children&#8217;s day, which is an official holiday, in South Korea, (by the way, the day before yesterday was <a href="http://en.wikipedia.org/wiki/Star_Wars_Day" title="Star Wars Day: May the 4th be with you">Star Wars Day</a> <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) and I found that <a href="http://xeraph.com" title="Xeraph">Xeraph</a>, who is the CEO of the IT security company named <a href="http://nchovy.com/" title="NCHOVY Inc.">Nchovy</a>, as well as the creator &#038; core programmer of the OSGi based opensource security platform, <a href="http://krakenapps.org/" title="Kraken">Kraken</a>, posted <a href="http://xeraph.com/5261697" title="some quiz for kids">some quiz for kids</a>. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  His blog also has <a href="http://xeraph.com/5251248" title="other quizzes for the primary schoolchildren">other quizzes for the primary schoolchildren</a>.</p>
<p>These quizzes remind me of my childhood as these kinds of quizzes are what I used to solve when I was a primary schoolchild. It was approximately 22 years ago. That time, I learned Basic (Not Visual Basic (VB), VB didn&#8217;t exist back then), Fortran, COBOL and C.  When I was learning Basic, those kinds of problems were what I solved. After I graduated from the primary school, I had not touched any computer programming languages at all for 13 years.  I started it again as I came to Sydney and entered the university to study IT. Then I realised that I could remember nothing about what I learned before. Nothing at all. That&#8217;s why my &#8216;<a href="http://blog.lckymn.com/about/" title="About me">about me</a>&#8216; page doesn&#8217;t contain any of Basic, Fortran and COBOL since I&#8217;ve completely forgot about these (it does have Visual Basic though as it&#8217;s my first programming language that I learned at the diploma school, <a href="http://www.insearch.edu.au/" title="UTS:INSEARCH">UTS:INSEARCH</a>). So my point is, doesn&#8217;t matter whether it&#8217;s a programming language or a human language, if you don&#8217;t practice or keep studying constantly, you will lose your skills and fluency of the language.</p>
<p>Anyway, I saw those quizzes and solved it for fun yet feel like I did better when I was a kid. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  Back then, I didn&#8217;t even use a computer to solve it but only pen and paper.<br />
The followings are the quizzes and my answers, yet there can be much better answers of course, so why don&#8217;t you try by yourself before you check out mine.</p>
<p>This is the prompt utility class, used for the other programmes, to get input values. Notice that it doesn&#8217;t check whether the input value is number, integer more precisely, or not although it does check if the given integer is a positive one.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.simplequiz;

import java.util.Scanner;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-05-05)
 */
public final class PromptUtil
{
    private PromptUtil()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }

    public static int askForPositiveInt(String message)
    {
        final Scanner scanner = new Scanner(System.in);
        System.out.print(message);
        int number = Integer.parseInt(scanner.nextLine());

        while (0 &gt;= number)
        {
            System.out.println(&quot;Please enter a position integer.&quot;);
            System.out.print(message);
            number = Integer.parseInt(scanner.nextLine());
        }
        return number;
    }
}
</pre>
<p>&nbsp;</p>
<p>Quiz 1. (taken from <a href="http://xeraph.com/5251248">http://xeraph.com/5251248</a>)</p>
<pre class="brush: plain; title: ; notranslate">
n for diamond? 3
</pre>
<pre class="brush: plain; title: ; notranslate">
  *
 ***
*****
 ***
  *

</pre>
<pre class="brush: plain; title: ; notranslate">
n for diamond? 5
</pre>
<pre class="brush: plain; title: ; notranslate">
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

</pre>
<pre class="brush: plain; title: ; notranslate">
n for diamond? 7
</pre>
<pre class="brush: plain; title: ; notranslate">
      *
     ***
    *****
   *******
  *********
 ***********
*************
 ***********
  *********
   *******
    *****
     ***
      *

</pre>
<pre class="brush: plain; title: ; notranslate">
n for diamond? 9
</pre>
<pre class="brush: plain; title: ; notranslate">
        *
       ***
      *****
     *******
    *********
   ***********
  *************
 ***************
*****************
 ***************
  *************
   ***********
    *********
     *******
      *****
       ***
        *
</pre>
<p>* Kevin&#8217;s Answer1</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_1_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>* Kevin&#8217;s Answer2</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_2_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Quiz 2. (taken from <a href="http://xeraph.com/5251248">http://xeraph.com/5251248</a>)</p>
<pre class="brush: plain; title: ; notranslate">
n for outer box? 4
m for inner box? 2
</pre>
<pre class="brush: plain; title: ; notranslate">
****
*  *
*  *
****

</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer box? 7
m for inner box? 3
</pre>
<pre class="brush: plain; title: ; notranslate">
*******
*******
**   **
**   **
**   **
*******
*******

</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer box? 10
m for inner box? 4
</pre>
<pre class="brush: plain; title: ; notranslate">
**********
**********
**********
***    ***
***    ***
***    ***
***    ***
**********
**********
**********

</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer box? 12
m for inner box? 6
</pre>
<pre class="brush: plain; title: ; notranslate">
************
************
************
***      ***
***      ***
***      ***
***      ***
***      ***
***      ***
************
************
************
</pre>
<p>* Kevin&#8217;s Answer</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_3_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Quiz 3. (taken from <a href="http://xeraph.com/5251248">http://xeraph.com/5251248</a>)</p>
<pre class="brush: plain; title: ; notranslate">
n for outer triangle? 3
m for inner triangle? 1
</pre>
<pre class="brush: plain; title: ; notranslate">
  *
 ***
** **

</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer triangle? 5
m for inner triangle? 3
</pre>
<pre class="brush: plain; title: ; notranslate">
    *
   ***
  ** **
 **   **
**     **

</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer triangle? 8
m for inner triangle? 4
</pre>
<pre class="brush: plain; title: ; notranslate">
       *
      ***
     *****
    *******
   **** ****
  ****   ****
 ****     ****
****       ****

</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer triangle? 10
m for inner triangle? 5
</pre>
<pre class="brush: plain; title: ; notranslate">
         *
        ***
       *****
      *******
     *********
    ***** *****
   *****   *****
  *****     *****
 *****       *****
*****         *****
</pre>
<p>* Kevin&#8217;s Answer</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_4_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Quiz 4. (taken from <a href="http://xeraph.com/5261697">http://xeraph.com/5261697</a>)</p>
<pre class="brush: plain; first-line: 0; title: ; notranslate">
matrix size n? 5
  1   2   3   4   5
 16  17  18  19   6
 15  24  25  20   7
 14  23  22  21   8
 13  12  11  10   9

</pre>
<pre class="brush: plain; first-line: 0; title: ; notranslate">
matrix size n? 6
  1   2   3   4   5   6
 20  21  22  23  24   7
 19  32  33  34  25   8
 18  31  36  35  26   9
 17  30  29  28  27  10
 16  15  14  13  12  11

</pre>
<pre class="brush: plain; first-line: 0; title: ; notranslate">
matrix size n? 7
  1   2   3   4   5   6   7
 24  25  26  27  28  29   8
 23  40  41  42  43  30   9
 22  39  48  49  44  31  10
 21  38  47  46  45  32  11
 20  37  36  35  34  33  12
 19  18  17  16  15  14  13

</pre>
<pre class="brush: plain; first-line: 0; title: ; notranslate">
matrix size n? 8
  1   2   3   4   5   6   7   8
 28  29  30  31  32  33  34   9
 27  48  49  50  51  52  35  10
 26  47  60  61  62  53  36  11
 25  46  59  64  63  54  37  12
 24  45  58  57  56  55  38  13
 23  44  43  42  41  40  39  14
 22  21  20  19  18  17  16  15
</pre>
<p>* Kevin&#8217;s Answer1</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_5_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>* Kevin&#8217;s Answer2</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_6_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Catch-Up 01 May, 2010</title>
		<link>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/</link>
		<comments>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 19:04:16 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Web Application Development]]></category>
		<category><![CDATA[Mine]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Ubuntu Linux]]></category>
		<category><![CDATA[Bug]]></category>
		<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[hashCode]]></category>
		<category><![CDATA[Hudson]]></category>
		<category><![CDATA[Issue Tracking System]]></category>
		<category><![CDATA[Java Reflection]]></category>
		<category><![CDATA[javac]]></category>
		<category><![CDATA[JDK7]]></category>
		<category><![CDATA[Kevin]]></category>
		<category><![CDATA[M2Eclipse]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Maven2]]></category>
		<category><![CDATA[Objects]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Sonatype]]></category>
		<category><![CDATA[Spring MVC]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=496</guid>
		<description><![CDATA[<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);"> Some part of <a href="#3. Shadowing Declarations?">3. Bug in Java compiler?Shadowing Declarations?</a> is <a href="#update1-2010-05-10">updated</a> <a href="#update2-2010-05-10">twice</a> on the 10th of May in 2010. </div> <p>I have been very busy and am still busy so haven&#8217;t written anything for quite a while on my blog except for those entries with only one or two sentences. So I&#8217;m quickly writing what I do these days and some <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/">Catch-Up 01 May, 2010</a>...]</p>]]></description>
				<content:encoded><![CDATA[<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
Some part of <a href="#3. Shadowing Declarations?">3. <span style="text-decoration: line-through;"> Bug in Java compiler?</span>Shadowing Declarations?</a> is <a href="#update1-2010-05-10">updated</a> <a href="#update2-2010-05-10">twice</a> on the 10th of May in 2010.
</div>
<p>I have been very busy and am still busy so haven&#8217;t written anything for quite a while on my blog except for those entries with only one or two sentences. So I&#8217;m quickly writing what I do these days and some issues I have dealt with.</p>
<h3><a name="1. Issue with the new m2eclipse (version: 0.10.0.20100209-0800)">1. Issue with the new m2eclipse (version: 0.10.0.20100209-0800)</a></h3>
<p><a href="http://www.sonatype.com/">Sonatype</a> released the new version of <a href="http://m2eclipse.sonatype.org/">m2eclipse</a> in February 2010. Since I updated with it, I had got some problem with maven build through <a href="http://hudson-ci.org/">Hudson</a>.</p>
<p>The new version of m2eclipse comes with maven3 embedded yet my server uses maven2 so does my Linux on my Desktop PC.  So it was only m2eclipse which uses maven3 (SNAPSHOT version) and I deployed some of my libraries used in one web application development project. Problem was that I deployed the dependency libraries several times with the same version number. With maven2, it&#8217;s OK as it uses time-stamp to distinguish one version from another within the same version, yet with maven3, having the same version is not allowed. Well, I am not 100% sure about this as once I solved the problem I didn&#8217;t really check the details as I didn&#8217;t have enough time. Anyway, so as shown in the following image, the project status icon once became dark rain clouds which mean really bad.<br />
<div id="attachment_501" class="wp-caption alignnone" style="width: 530px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure01.jpg" alt="Build Failure: Project status icon became dark rain clouds" title="00 build failure01" width="520" height="294" class="size-full wp-image-501" /></a><p class="wp-caption-text">Build Failure: Project status icon became dark rain clouds</p></div></p>
<p>My project build failed seven times due to the difference between maven2 and maven3 I described above, or it can be something else yet it is caused by some difference between those two versions.<br />
<div id="attachment_502" class="wp-caption alignnone" style="width: 336px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure02.jpg" alt="Build Failure: It failed seven times due to the difference between maven2 and maven3" title="00 build failure02" width="326" height="446" class="size-full wp-image-502" /></a><p class="wp-caption-text">Build Failure: It failed seven times due to the difference between maven2 and maven3</p></div><br />
(It happened in February. The build number in the image is 108 but it is now 305).</p>
<p>So why did I not just keep the old version of m2eclipse with maven2 embedded? Well, the old one comes with some old version of maven2 which does not support <a href="http://maven.apache.org/guides/mini/guide-encryption.html">password encryption</a> while the maven2 on both my PC and my server does support it as it is a newer version. Thus I updated with the new m2eclipse as soon as it was available yet didn&#8217;t really expect that it comes with maven3. Anyway, It&#8217;s solved by using maven2 installed on my PC when deploying project packages. The other times such as solving dependencies and building package without deployment, I can still use the embedded maven3 in the new m2eclipse without any problems.</p>
<h3><a name="2. I have been working on...">2. I have been working on&#8230;</a></h3>
<p>I founded a start-up company with my friend a few months ago, and we are currently working on a web application development for our own start-up, but it is probably too premature to announce what it is as it&#8217;s still an early stage of development.<br />
The issues listed in the following image is a part of the issues I and my colleague have solved and been working on.<br />
<div id="attachment_503" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_00.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_00.jpg" alt="I&#039;m currently working on this project." title="01 Issue Tracking 00" width="640" height="477" class="size-full wp-image-503" /></a><p class="wp-caption-text">I'm currently working on this project.</p></div></p>
<p>In addition, I have been developing my own Java libraries which can be commonly used in many other projects (and my friend has also been developing reusable JavaScript libraries). However, I did not record all the issues belong to these reusable components and recently felt that I should do it before I go any further. Otherwise, I may later forget what problems I solved and how I did as well as all the issues covered previously. So I wrote all the tickets for those libraries.<br />
<div id="attachment_504" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_01.jpg" alt="Issues of commonly used libraries built by myself" title="01 Issue Tracking 01" width="640" height="335" class="size-full wp-image-504" /></a><p class="wp-caption-text">Issues of commonly used libraries built by myself</p></div></p>
<p>I&#8217;ve also been developing &#8216;Java object to JSON&#8217; library and did the same as what I just explained (that is creating issue tickets).  There are already a number of the libraries which convert Java object into <a href="http://json.org/">JSON</a> so why would I make another?  Well, there can be several reasons but major ones are</p>
<ol>
<li>I need it to convert any <a href="http://en.wikipedia.org/wiki/POJO">POJO</a> with only <a href="http://en.wikipedia.org/wiki/Java_annotation">annotations</a> into <a href="http://json.org/">JSON</a>.</li>
<li>It has to be simple as I do not want to have any complex functions or heavy library for a simple conversion (some libraries are too heavy for such a simple task).</li>
<li>When customisation is required or bug is found in the library, I want to be able to change and fix it however I want so that I do not have to waste my time on waiting for others to solve it.</li>
<li>I want it to work in some environments where using bytecode manipulation is not an option. So if I programme one with bytecode manipulation then it works faster when it&#8217;s available whereas the other one is without it so that it can be used in those enviornments (I currently have only the latter one and will do the former one when I have time later).</li>
</ol>
<p>The following issues are what I have solved for the Java to JSON library.<br />
<div id="attachment_505" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_02.jpg" alt="Issues of my Java object to JSON library" title="01 Issue Tracking 02" width="640" height="451" class="size-full wp-image-505" /></a><p class="wp-caption-text">Issues of my Java object to JSON library</p></div></p>
<p>Finally, I have another project to help Ajax enabled web application development. From my experience, I found that it is sharing the information about the available server-side functions with the client-side developers that causes the most waste of time between the front-end development and the back-end development.  The first time one function is made or whenever the existing ones are changed, I have to write or rewrite the document explaining it and the client-side developer has to find the changed parts in the document.  It is annoying and a non-productive moment in the development so I and my colleague discussed about this issue and came up with the idea of having a library which exposes all the available server-side functions to the front-end (It can understand Spring <code>@MVC</code> controllers).  For now, it has only this, yet I will add more features to help Ajax web application development.<br />
<div id="attachment_506" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_03.jpg" alt="Issues of my web method library" title="01 IssueTracking 03" width="640" height="146" class="size-full wp-image-506" /></a><p class="wp-caption-text">Issues of my web method library</p></div></p>
<p>* As I used more and more reflection to develop those libraries, I realised that Java Reflection has no method to get the names of method parameters. Well, there can be some ways for instance, using -g (generating debugging info) option when compiling or using some libraries such as <a href="http://asm.ow2.org/">ASM</a> or use <a href="http://paranamer.codehaus.org/">ParaNamer</a> (It requires an additional step when compiling to add the constants having the parameter names in the class) but not by just Java reflection.  Anyway, none of these is the solution I want, and unfortunately if I heard right, this problem will remain in JDK 7. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<h3><a name ="3. Shadowing Declarations?">3. <span style="text-decoration: line-through;">Bug in Java compiler?</span> Shadowing Declarations?</a></h3>
<p>I created the Objects utility class based on <a href="http://download.java.net/jdk7/docs/api/java/util/Objects.html">http://download.java.net/jdk7/docs/api/java/util/Objects.html</a>. This will be available in JDK 7 yet I wanted to use it before JDK 7 is released so I made my own one. I can use it now, and it can easily be replaced by the one in JDK when it&#8217;s available.  <span style="text-decoration: line-through;">After I made it, I found some weird bug, I believe, in Java compiler.</span> After I used it, I had some problem and thought it could be a bug in Java compiler yet <a href="#update2-2010-05-10">it looks like &#8216;shadowing declarations&#8217;.</a></p>
<p>This is the part of Objects class I coded.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.common.util;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public final class Objects
{
    private Objects()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }

    // other code omitted ...

    /**
     * Returns the hash code of a non-{@code null} argument and 0 for a {@code null} argument.
     * 
     * @param o
     *            an object
     * @return the hash code of a non-{@code null} argument and 0 for a {@code null} argument
     * @see {@link Object#hashCode()}
     */
    public static int hashCode(final Object o)
    {
        return (null == o ? 0 : o.hashCode());
    }

    // other code omitted ...
}
</pre>
<p>The following code is a POJO in which I want to use the Objects.hashCode(Object) method.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.bean;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public class SomePojo
{
    private final int number;
    private final String name;

    public SomePojo(int number, String name)
    {
        this.number = number;
        this.name = name;
    }

    public int getNumber()
    {
        return number;
    }

    public String getName()
    {
        return name;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (!(obj instanceof SomePojo))
        {
            return false;
        }
        final SomePojo that = (SomePojo) obj;
        return (this.number == that.getNumber())
                &amp;&amp; (this.name == that.getName() || 
                        (null != this.name &amp;&amp; this.name.equals(that.getName())));
    }
}
</pre>
<p>So I changed this code snippet</p>
<pre class="brush: java; gutter: false; highlight: [7]; title: ; notranslate">
@Override
public int hashCode()
{
    final int prime = 31;
    int result = 1;
    result = prime * result + number;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}
</pre>
<p>to this.</p>
<pre class="brush: java; gutter: false; highlight: [3,15]; title: ; notranslate">
package com.lckymn.kevin.test.bean;

import static com.lckymn.kevin.common.util.Objects.*;

public class SomePojo
{
    // ...

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + hashCode(name);
        return result;
    }
}
</pre>
<p>I used static import and hashCode(Object) method in the Objects class. Although, nothing&#8217;s wrong in the code, my Eclipse complains that there is a compile-time error. The following image shows that.<br />
<div id="attachment_511" class="wp-caption alignnone" style="width: 929px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_01.jpg" alt="Objects.hashCode(Object) with static import does not work." title="02 Objects.hashCode 01" width="919" height="837" class="size-full wp-image-511" /></a><p class="wp-caption-text">Objects.hashCode(Object) with static import does not work.</p></div></p>
<p>Yet the same code with no-static import but using class name as the qualifier to use <code>hashCode(Object)</code> method works perfectly. The following code has <code>Objects.hashCode(name)</code> and no compile-time error.</p>
<pre class="brush: java; highlight: [36]; title: ; notranslate">
package com.lckymn.kevin.test.bean;

import com.lckymn.kevin.common.util.Objects;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public class SomePojo
{
    private final int number;
    private final String name;

    public SomePojo(int number, String name)
    {
        this.number = number;
        this.name = name;
    }

    public int getNumber()
    {
        return number;
    }

    public String getName()
    {
        return name;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + Objects.hashCode(name);
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (null == obj)
        {
            return false;
        }
        if (!(obj instanceof SomePojo))
        {
            return false;
        }
        final SomePojo that = (SomePojo) obj;
        return (this.number == that.getNumber())
                &amp;&amp; (this.name == that.getName() || (null != this.name &amp;&amp; this.name.equals(that.getName())));
    }
}
</pre>
<p>The following image shows it has no error in the part where <code>Objects.hashCode(Object)</code> is used..<br />
<div id="attachment_508" class="wp-caption alignnone" style="width: 515px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_02.jpg" alt="Using Class as qualifier to use hashCode works." title="02 Objects.hashCode 02" width="505" height="622" class="size-full wp-image-508" /></a><p class="wp-caption-text">Using Class as qualifier to use hashCode works.</p></div></p>
<p>I wondered if it&#8217;s a bug in the Eclipse or a bug in the Java compiler. So I opened the terminal and tested it.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ javac -version
javac 1.6.0_15


$ javac com/lckymn/kevin/test/bean/SomePojo.java
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>As it shows, the compiler does totally not understand that the hashCode(Object) method from the Objects class is available and valid.</p>
<p>Is a bug only in the SUN JDK in the Ubuntu Linux repository? So I tried with OpenJDK 6 as well.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ /usr/lib/jvm/java-6-openjdk/bin/javac -version
javac 1.6.0_0

$ /usr/lib/jvm/java-6-openjdk/bin/javac com/lckymn/kevin/test/bean/SomePojo.java 
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>The same result&#8230;</p>
<p>OK, it might be a bug in that particular version. Fortunately, the most recent version of SUN JDK 6 was released yesterday. It was officially released before (the 15th of April, 2010) yet the version managed by Ubuntu was not available before yesterday. So I installed it and tested it again with the Java compiler in the new JDK6.<br />
<div id="attachment_509" class="wp-caption alignnone" style="width: 622px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/03_update_jdk.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/03_update_jdk.jpg" alt="New version of SUN JDK6 is available in the Ubuntu repository" title="03 Update JDK" width="612" height="640" class="size-full wp-image-509" /></a><p class="wp-caption-text">New version of SUN JDK6 is available in the Ubuntu repository</p></div></p>
<p>It still has the same problem.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ javac -version
javac 1.6.0_20

$ javac com/lckymn/kevin/test/bean/SomePojo.java
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>I probably need to test with the Java compiler in the JDK6 for Windows but I have no stomach for that now nor do I have time to do that.</p>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
<a name="update1-2010-05-10">* Update1 (2010-05-10)</a><br />
I also tested it with the Java compiler in the JDK 6 (1.6.0_16) for Windows and got the same result. <span style="text-decoration: line-through">It seem like static import cannot handle method overloading. I didn&#8217;t have time to research to find the details but based on my testing, method overloading cannot be used with static import.<br />
If so then there should be a good reason for that, and the only one I can think of right now is that it might have something to do with varargs.</span><br />
Take a look at the following code.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.common.util;

public final class SomeHelper
{
    private SomeHelper()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }
    
    public static void test(Object... object)
    {
        System.out.println(&quot;SomeHelper.test()&quot;);
    }
}
</pre>
<pre class="brush: java; highlight: [3,14,17]; title: ; notranslate">
package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test()
    {
        System.out.println(&quot;Test.test()&quot;);
    }

    public void callTest()
    {
        test();            // no error here.

        Object object = new Object();
        test(object);    // compile-time error
    }
}
</pre>
<p><span style="text-decoration: line-through">Since a method with varargs can take no argument when it&#8217;s called, Test.test() and SomeHelper.test(Object&#8230; object) can be indistinguishable with static import. This is, I think, probably one of the reasons why method overloading is not allowed with static import. Nevertheless, it is still very weird as calling test() does not cause any compile-time error while test(object) does.</span><br />
So the following code has no compile-time error and displays <code>Test.test()</code>.</p>
<pre class="brush: java; highlight: [3]; title: ; notranslate">
package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test()
    {
        System.out.println(&quot;Test.test()&quot;);
    }

    public void callTest()
    {
        test();    // static import of SomeHelper.test has no effect here.
    }
    
    public static void main(String[] args)
    {
        new Test().callTest();
        System.exit(0);
    }
}
</pre>
<p>It displays <code>Test.test()</code>.</p>
<p>What if the helper class has test() method with no arguments and the Test class has test() method with varargs then call <code>test()</code>? The same result! It still calls Test&#8217;s test() method with varargs (<code>Test.test(Object... object)</code>).</p>
<pre class="brush: java; highlight: [10]; title: ; notranslate">
package com.lckymn.kevin.common.util;

public final class SomeHelper
{
    private SomeHelper()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }
    
    public static void test()
    {
        System.out.println(&quot;SomeHelper.test()&quot;);
    }
}
</pre>
<pre class="brush: java; highlight: [3,7]; title: ; notranslate">
package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test(Object... object)
    {
        System.out.println(&quot;Test.test(Object...object)&quot;);
    }

    public void callTest()
    {
        test(); // it calls the Test.test(Object... object) method NOT SomeHelper.test().
    }

    public static void main(String[] args)
    {
        new Test().callTest();
        System.exit(0);
    }
}
</pre>
<p>It displays <code>Test.test(Object...object)</code>
</div>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
<a name="update2-2010-05-10">Update2 (2010-05-10)</a><br />
It is more likely to be <a href="http://java.sun.com/docs/books/jls/third_edition/html/names.html#34133">&#8216;Shadowing Declarations&#8217;</a>. Although, I couldn&#8217;t find the exactly matching case from the <a href="http://java.sun.com/docs/books/jls/">JLS</a> yet, it makes more sense if the method imported by static-import is shadowed.
</div>
<h3><a name="4. Using Objects">4. Using Objects</a></h3>
<p>By the way, the Objects class is simple but very useful.<br />
with it, the highlighted parts of the following code can</p>
<pre class="brush: java; highlight: [53,54,55,56,57,72,73,74,75]; title: ; notranslate">
package com.lckymn.kevin.test.bean;

public class Bank
{
    private Long id;
    private String bankName;
    private String bsbNumber;
    private String address;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getBankName()
    {
        return bankName;
    }

    public void setBankName(String bankName)
    {
        this.bankName = bankName;
    }

    public String getBsbNumber()
    {
        return bsbNumber;
    }

    public void setBsbNumber(String bsbNumber)
    {
        this.bsbNumber = bsbNumber;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((bankName == null) ? 0 : bankName.hashCode());
        result = prime * result + ((bsbNumber == null) ? 0 : bsbNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object bank)
    {
        if (this == bank)
        {
            return true;
        }
        if (!(bank instanceof Bank))
        {
            return false;
        }
        final Bank that = (Bank) bank;
        return (this.bankName == that.getBankName() || 
               (null != this.bankName &amp;&amp; this.bankName.equals(that.getBankName())))
                &amp;&amp; (this.bsbNumber == that.getBsbNumber() || 
                   (null != this.bsbNumber &amp;&amp; this.bsbNumber.equals(that.getBsbNumber())));
    }
}
</pre>
<p>become like this</p>
<pre class="brush: java; highlight: [55,70,71]; title: ; notranslate">
package com.lckymn.kevin.test.bean;

import com.lckymn.kevin.common.util.Objects;

public class Bank
{
    private Long id;
    private String bankName;
    private String bsbNumber;
    private String address;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getBankName()
    {
        return bankName;
    }

    public void setBankName(String bankName)
    {
        this.bankName = bankName;
    }

    public String getBsbNumber()
    {
        return bsbNumber;
    }

    public void setBsbNumber(String bsbNumber)
    {
        this.bsbNumber = bsbNumber;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(bankName, bankName);
    }

    @Override
    public boolean equals(Object bank)
    {
        if (this == bank)
        {
            return true;
        }
        if (!(bank instanceof Bank))
        {
            return false;
        }
        final Bank that = (Bank) bank;
        return Objects.equals(this.bankName, that.getBankName()) 
               &amp;&amp; Objects.equals(this.bsbNumber, that.getBsbNumber());
    }
}
</pre>
<p>So these five lines in the hashCode method</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
final int prime = 31;
int result = 1;
result = prime * result + ((bankName == null) ? 0 : bankName.hashCode());
result = prime * result + ((bsbNumber == null) ? 0 : bsbNumber.hashCode());
return result;
</pre>
<p>become</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return Objects.hash(bankName, bankName);
</pre>
<p>and these four lines in the equals method</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return (this.bankName == that.getBankName() || 
       (null != this.bankName &amp;&amp; this.bankName.equals(that.getBankName())))
        &amp;&amp; (this.bsbNumber == that.getBsbNumber() || 
           (null != this.bsbNumber &amp;&amp; this.bsbNumber.equals(that.getBsbNumber())));
</pre>
<p>become</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return Objects.equals(this.bankName, that.getBankName()) 
       &amp;&amp; Objects.equals(this.bsbNumber, that.getBsbNumber());
</pre>
<p>Although one might say that I can use <a href="http://projectlombok.org/">Lombok</a> instead, I prefer to see what is going on in my code. Those hashCode and equals methods are not additional info of the class. It tells what makes instances of the class equal thus I prefer to have it in there to see and want to freely change it whenever and however I want. Well, in other words, just a matter of personal preference. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
That&#8217;s it.<br />
I perhaps have more to say yet am getting tired (4:55 AM :O). So I&#8217;m calling it a night. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Bubbles &#8211; Cool Java IDE</title>
		<link>http://blog.lckymn.com/2010/03/11/code-bubbles-cool-java-ide/</link>
		<comments>http://blog.lckymn.com/2010/03/11/code-bubbles-cool-java-ide/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 08:26:04 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Development Tools]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Code Bubbles]]></category>
		<category><![CDATA[IDE]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=490</guid>
		<description><![CDATA[<div id="attachment_493" class="wp-caption alignnone" style="width: 970px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/03/CodeBubbles.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/03/CodeBubbles.jpg" alt="Code Bubbles - Cool Java IDE" title="Code Bubbles - Cool Java IDE" width="960" height="720" class="size-full wp-image-493" /></a><p class="wp-caption-text">Code Bubbles - Cool Java IDE</p></div> <p>Seeing is believing so just visit <a href="http://www.andrewbragdon.com/codebubbles_site.asp" target="_blank">http://www.andrewbragdon.com/codebubbles_site.asp</a> and watch the video. What an awesome IDE!!!</p> ]]></description>
				<content:encoded><![CDATA[<div id="attachment_493" class="wp-caption alignnone" style="width: 970px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/03/CodeBubbles.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/03/CodeBubbles.jpg" alt="Code Bubbles - Cool Java IDE" title="Code Bubbles - Cool Java IDE" width="960" height="720" class="size-full wp-image-493" /></a><p class="wp-caption-text">Code Bubbles - Cool Java IDE</p></div>
<p>Seeing is believing so just visit <a href="http://www.andrewbragdon.com/codebubbles_site.asp" target="_blank">http://www.andrewbragdon.com/codebubbles_site.asp</a> and watch the video.<br />
What an awesome IDE!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2010/03/11/code-bubbles-cool-java-ide/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Google Collections Library 1.0 &#8211; FINAL</title>
		<link>http://blog.lckymn.com/2009/12/31/google-collections-library-1-0-final/</link>
		<comments>http://blog.lckymn.com/2009/12/31/google-collections-library-1-0-final/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 09:29:13 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Google Collections Library]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=479</guid>
		<description><![CDATA[<p>Google has eventually released <a href="http://code.google.com/p/google-collections/" target="_blank">Google Collections Library</a> 1.0 Final version. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> Now I can use it for my project. I was actually more looking forward to its release than the release of Spring Framework 3.0. </p> <p>Download Page: <a href="http://code.google.com/p/google-collections/downloads/detail?name=google-collect-1.0.zip" target="_blank">Google Collections Library 1.0 &#8211; FINAL</a></p> <p>Maven users can simply add the following dependency info to use Google Collections Library 1.0 &#8211; FINAL.</p> &#60;dependency&#62; &#60;groupId&#62;com.google.collections&#60;/groupId&#62; &#60;artifactId&#62;google-collections&#60;/artifactId&#62; &#60;version&#62;1.0&#60;/version&#62; &#60;type&#62;jar&#60;/type&#62; &#60;scope&#62;compile&#60;/scope&#62; &#60;/dependency&#62; ]]></description>
				<content:encoded><![CDATA[<p>Google has eventually released <a href="http://code.google.com/p/google-collections/" target="_blank">Google Collections Library</a> 1.0 Final version. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Now I can use it for my project. I was actually more looking forward to its release than the release of Spring Framework 3.0. </p>
<p>Download Page: <a href="http://code.google.com/p/google-collections/downloads/detail?name=google-collect-1.0.zip" target="_blank">Google Collections Library 1.0 &#8211; FINAL</a></p>
<p>Maven users can simply add the following dependency info to use Google Collections Library 1.0 &#8211; FINAL.</p>
<pre class="brush: xml; gutter: false; title: ; notranslate">
&lt;dependency&gt;
	&lt;groupId&gt;com.google.collections&lt;/groupId&gt;
	&lt;artifactId&gt;google-collections&lt;/artifactId&gt;
	&lt;version&gt;1.0&lt;/version&gt;
	&lt;type&gt;jar&lt;/type&gt;
	&lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/12/31/google-collections-library-1-0-final/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Re: Java Challenge: Dropping Balloons in Java</title>
		<link>http://blog.lckymn.com/2009/11/20/java-challenge-dropping-balloons-in-java/</link>
		<comments>http://blog.lckymn.com/2009/11/20/java-challenge-dropping-balloons-in-java/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 10:54:21 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[balloon]]></category>
		<category><![CDATA[building]]></category>
		<category><![CDATA[egg]]></category>
		<category><![CDATA[floor]]></category>
		<category><![CDATA[puzzle]]></category>
		<category><![CDATA[quiz]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=455</guid>
		<description><![CDATA[<p>About a few days ago, I read <a href="http://united-coders.com/nico-heid/java-challenge-dropping-balloons-in-java" target="_blank">this post, Java Challenge: Dropping Balloons in Java</a> having an interesting question.</p> <p>It&#8217;s a question to find an algorithm that gives the highest floor where you can drop a water balloon without breaking it at a 100 story building. You have only two balloons. I had actually seen this problem before and solved it already. It was not balloons but eggs. The solution is simple. Since if you miss two chances <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/11/20/java-challenge-dropping-balloons-in-java/">Re: Java Challenge: Dropping Balloons in Java</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>About a few days ago, I read <a href="http://united-coders.com/nico-heid/java-challenge-dropping-balloons-in-java" target="_blank">this post, Java Challenge: Dropping Balloons in Java</a> having an interesting question.</p>
<p>It&#8217;s a question to find an algorithm that gives <span style="font-weight: bolder;">the highest floor where you can drop a water balloon without breaking it at a 100 story building</span>.  You have <span style="font-weight: bolder;">only two balloons</span>.  I had actually seen this problem before and solved it already.  It was not balloons but eggs.  The solution is simple. Since if you miss two chances then have no balloons available, you need to try from the lowest safe level which means throw it from the first floor then if it does not pop, pick it up and go up to the level 2 and repeat it until the balloon pops.  When you get the level from which the balloon bursts after dropping it, one level below this level is the highest safe level. (e.g. If the balloon first breaks on the 20th floor, the highest safe floor is the 19th).</p>
<p>It&#8217;s easy isn&#8217;t it? Yet the post above has one more condition to make it a little bit more difficult which is that <span style="font-weight: bolder;">you can try only 15 times</span>. This means if I try the solution I&#8217;ve just described, I can test up to only the 15th floor. If the breaking point is the 40th floor or even the 16th floor, I&#8217;ll never know it.  When I first saw it, I tried to solve it for about five minutes yet couldn&#8217;t solve it.  That time, I was too busy to think about it further thus couldn&#8217;t be bothered to do it.  So I saved the URI of the post and forgot about it.  Last night, no actually today morning, at approximately 6 am, I went to bed (yeah, am I a vampire or what? <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).  Although I didn&#8217;t even try to think about the problem yet all of sudden I came up with the answer of that question.  It was just like the &#8216;<a href="http://en.wikipedia.org/wiki/Eureka_(word)" target="_blank">Eureka</a>&#8216; story of <a href="http://en.wikipedia.org/wiki/Archimedes" target="_blank">Archimedes</a>.  Just like he figured out how to assess the purity of a golden crown when he stepped into a bath.  OK, stop flattering myself <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  I figured it out as the question was easy to solve.</p>
<p>Well, an important point here is that I in fact often find solutions to some difficult problems when I am not struggling to solve it yet am doing something irrelevant to the problem such as working out at the gym, washing dishes after a meal, lying on the bed to sleep or even when I&#8217;m dreaming. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  So if you can&#8217;t solve some problem then why don&#8217;t you try something else rather than thinking about the solution all the time.  Your brain may need to relax or when you use the other parts of the brain by doing something else, it might figure it out.</p>
<p>Anyway, here is what my brain told me that time.</p>
<p>Since I have only two balloons, if I choose a wrong floor twice, I lose all the chances.  Then what if I check every second level as I have two balloons. So first, if I drop it from the second level and it breaks then I still have one more balloon so that I can try it from the first level and I can find if the highest safe level is the first or there is no safe level. If the balloon is fine after dropping it from the second level then I can pick it up and try it from the fourth level and so on. However, with this solution I can check at most until the 30th floor which is better than checking up to the 15th one but still not enough to check the 100 stories.  This means that it is not sufficient to check ever second level in order to find the floor and I should focus on not only the two balloons but also the 15 times of attempts.  From the first solution above, I know that I can definitely have 15 times if I try from the lowest safe floor and move up.  It means if the number of floors between the already known highest safe level and the breaking point level found is the same as or fewer than the number of attempts I still have, I can find the very first level where the balloon bursts after dropping it (In order to reduce the number of attempts, of course, I have to make it the same as the number of attempts still left).  Therefore I can tell the highest safe level that is one level below the breaking point level found.  This should be easier to understand with an example.</p>
<p>Let&#8217;s assume that the breaking point is the 17th floor.</p>
<p>At first, I have 15 tries to drop one balloon from the 15th floor.<br />
The balloon&#8217;s still OK and I now have 14 times of attempts. Since the number of attempts I still have is 14 time, I can&#8217;t try it from the 30th floor which is 15 + 15 yet I have to try it from the 29th floor (15 + 14). Because the breaking point is the 17th floor, the balloon breaks on the 29th floor.  Now I have 13 times of attempts and 1 balloon left.  From the first try, I know the 14th floor is fine so I try from the next floor that is floor 15 to see if floor 14 is the highest safe floor.  It turns out the 15th one is fine and now I have 12 times left.  16th -> OK / 11 times left, 17th -> it breaks! / 10 times left<br />
So I can tell the 16th floor is the highest safe floor and I didn&#8217;t even use all the 15 times of attempts.</p>
<p><a href="http://united-coders.com/nico-heid/java-challenge-dropping-balloons-in-java" target="_blank">The post that has the question</a> specifies the floor starts from 0 so let&#8217;s make the first floor is floor 0 and see have it works. I made a table which shows the number of attempts required to find the highest safe floor.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
====================================================
 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15   tries
====================================================
 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14	- 1
15 16 17 18 19 20 21 22 23 24 25 26 27 28		- 2
29 30 31 32 33 34 35 36 37 38 39 40 41			- 3
42 43 44 45 46 47 48 49 50 51 52 53				- 4
54 55 56 57 58 59 60 61 62 63 64				- 5
65 66 67 68 69 70 71 72 73 74					- 6
75 76 77 78 79 80 81 82 83						- 7
84 85 86 87 88 89 90 91							- 8
92 93 94 95 96 97 98							- 9
99												- 10
</pre>
<p>So if the highest safe floor is 73. The first balloon breaks on the floor 74 after 6 times of attempts. After that try from the floor 65 (attempts: 7) through 66 (8), 67 (9), 68 (10), 69 (11), 70 (12), 71 (13), 72 (14) to 73 (15) and the second balloon hasn&#8217;t broken so I can tell the highest safe floor is the floor 73.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
====================================================
 1  2  3  4  5  6  7  8[ 9]10 11 12 13 14 15
====================================================
65 66 67 68 69 70 71 72[73]74					-[6]
</pre>
<p>attempts: 6 times to get the floor 74 + 9 times to check until the floor 73 = 15 times.</p>
<p>Once I found the solution writing code is a piece of cake.<br />
I roughly wrote the main part of the code like this.</p>
<pre class="brush: java; gutter: false; tab-size: 4; title: ; toolbar: true; notranslate">
private static final int MAX_ATTEMPTS = 15;

private int theFloor = (int) (Math.random() * 100);
private int numberOfBalloons = 2;
private int numberOfAttempts = 0;

// ...


public void findHighestSafeFloor()
{
	int previousFloorIndex = -1;
	int floorIndex = MAX_ATTEMPTS - 1;
	int highestSafeFloor = 0;

	while (MAX_ATTEMPTS &gt; numberOfAttempts)
	{
		numberOfAttempts++;
		if (theFloor &lt;= floorIndex)
		{
			numberOfBalloons--;
			highestSafeFloor = findHighestSafeFloor(previousFloorIndex + 1, floorIndex);
			break;
		}
		previousFloorIndex = floorIndex;
		floorIndex += (MAX_ATTEMPTS - numberOfAttempts);
		if (99 &lt; floorIndex)
		{
			floorIndex = 99;
		}
	}
	
	/* print the result. */
}

private int findHighestSafeFloor(final int start, final int end)
{
	for (int i = start; i &lt; end; i++)
	{
		numberOfAttempts++;
		if (theFloor == i)
		{
			numberOfBalloons--;
			return (i - 1);
		}
	}
	return (end - 1);
}
</pre>
<p>I am sure that the <code>findHighestSafeFloor()</code> method above works but I decided to make it recursion. Why? No special reasons. I just like recursion <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  as I haven&#8217;t used it for approximately four years since I last programmed in a functional programming language like <a href="http://haskell.org/" target="_blank">Haskell</a> in my math class thus miss it. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Although the code can be very simple as the following code with recursion, it has to increase the number of attempts and to decrease the number of balloons left, so it would be a bit more verbose as the second code.</p>
<pre class="brush: java; gutter: false; tab-size: 4; title: ; toolbar: true; notranslate">
private int findHighestSafeFloor(final int start, final int end)
{
	return (start &lt; end ? (theFloor == start ? (start - 1) : findHighestSafeFloor((start + 1), end)) : (end - 1));
}
</pre>
<pre class="brush: java; gutter: false; tab-size: 4; title: ; toolbar: true; notranslate">
private int findHighestSafeFloor(final int start, final int end)
{
	if (start &lt; end)
	{
		numberOfAttempts++;
		if (theFloor == start)
		{
			numberOfBalloons--;
			return (start - 1);
		}
		else
		{
			return findHighestSafeFloor((start + 1), end);
		}
	}
	else
	{
		return (end - 1);
	}
}
</pre>
<p>Now it&#8217;s time to code the complete programme and test it.  Well, since it&#8217;s a very small programme, I didn&#8217;t do object-oriented programming. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: java; tab-size: 4; title: ; toolbar: true; notranslate">
package com.lckymn.kevin.findingfloor;

public final class HighestSafeFloorFinder
{
	private static final int TOP_LEVEL = 99;
	private static final int MAX_ATTEMPTS = 15;

	private int theBreakingPointFloor;
	private int numberOfBalloons;
	private int numberOfAttemptsMade;

	public void init(final int theBreakingPointFloor)
	{
		this.theBreakingPointFloor = theBreakingPointFloor;
		System.out.println(&quot;The breaking point: &quot; + theBreakingPointFloor);
		numberOfBalloons = 2;
		numberOfAttemptsMade = 0;
	}

	public void findHighestSafeFloor()
	{
		int previousFloorIndex = -1;
		int floorIndex = MAX_ATTEMPTS - 1;
		int highestSafeFloor = 0;

		while (MAX_ATTEMPTS &gt; numberOfAttemptsMade)
		{
			dropBalloon();
			if (theBreakingPointFloor &lt;= floorIndex)
			{
				breakBalloon();
				highestSafeFloor = findHighestSafeFloor(previousFloorIndex + 1, floorIndex);
				break;
			}
			previousFloorIndex = floorIndex;
			floorIndex += (MAX_ATTEMPTS - numberOfAttemptsMade);
			if (TOP_LEVEL &lt; floorIndex)
			{
				floorIndex = TOP_LEVEL;
			}
		}

		if (0 &gt; highestSafeFloor)
		{
			System.out.println(&quot;There is no floor that you can drop a balloon without breaking it. Even the first floor (floor 0) is not safe.&quot;);
		}
		else
		{
			System.out.println(&quot;The highest safe floor: &quot; + highestSafeFloor);
		}

		System.out.println(&quot;The number of attempts made: &quot; + numberOfAttemptsMade);
	}

	private int findHighestSafeFloor(final int start, final int end)
	{
		if (start &lt; end)
		{
			dropBalloon();
			if (theBreakingPointFloor == start)
			{
				breakBalloon();
				return (start - 1);
			}
			else
			{
				return findHighestSafeFloor((start + 1), end);
			}
		}
		else
		{
			return (end - 1);
		}
	}

	private void dropBalloon()
	{
		if (MAX_ATTEMPTS == numberOfAttemptsMade)
		{
			throw new IllegalStateException(&quot;You've already tried 15 times.&quot;);
		}
		numberOfAttemptsMade++;
	}

	private void breakBalloon()
	{
		if (0 == numberOfBalloons)
		{
			throw new IllegalStateException(&quot;You've already broken all the balloons available.&quot;);
		}
		numberOfBalloons--;
	}

	public static void main(String[] args)
	{
		HighestSafeFloorFinder highestSafeFloorFinder = new HighestSafeFloorFinder();
		for (int i = 0; i &lt; 100; i++)
		{
			System.out.println(&quot;[Test Number: &quot; + i + &quot;]&quot;);
			highestSafeFloorFinder.init(i);
			highestSafeFloorFinder.findHighestSafeFloor();
			System.out.println(&quot;=======================================&quot;);
		}
		System.exit(0);
	}
}
</pre>
<p>Well, the code looks a bit ugly but in my defence, I&#8217;d just like to see the result and am busy so had no stomach for making it pretty. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  (Oh! such a poor excuse / but really busy <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> )</p>
<p>The <code>dropBalloon()</code> and the <code>breakBalloon()</code> are added to increase the number of attempts made and to decrease the number of balloons left respectively.  The <code>dropBalloon()</code> method also checks if the number of attempts already made is 15 and it tries to make another one than throws an exception telling that all the chances have been used.  Similarly the <code>breakBalloon()</code> method checks if all the available balloons have broken if so, it also throws an exception saying there are no available balloons left.  Thus I can see if the programme can find the highest safe floor with 15 times or fewer times of attempts and only two water balloons.  If it cannot, it immediately throws an exception and stop the programme so I can see my programme fails to prove my algorithm.</p>
<p>The <code>init()</code> method is to initialise all the variables so that I can test it many times. It checks all the floors from the first one (floor 0) to the last one (floor 99) so if the programme works fine without any exception thrown then it might prove my answer is correct.</p>
<p>Let&#8217;s check out the result!</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
[Test Number: 0]
The breaking point: 0
There is no floor that you can drop a balloon without breaking it. Even the first floor (floor 0) is not safe.
The number of attempts made: 2
=======================================
[Test Number: 1]
The breaking point: 1
The highest safe floor: 0
The number of attempts made: 3
=======================================
[Test Number: 2]
The breaking point: 2
The highest safe floor: 1
The number of attempts made: 4
=======================================
[Test Number: 3]
The breaking point: 3
The highest safe floor: 2
The number of attempts made: 5
=======================================
[Test Number: 4]
The breaking point: 4
The highest safe floor: 3
The number of attempts made: 6
=======================================
[Test Number: 5]
The breaking point: 5
The highest safe floor: 4
The number of attempts made: 7
=======================================
[Test Number: 6]
The breaking point: 6
The highest safe floor: 5
The number of attempts made: 8
=======================================
[Test Number: 7]
The breaking point: 7
The highest safe floor: 6
The number of attempts made: 9
=======================================
[Test Number: 8]
The breaking point: 8
The highest safe floor: 7
The number of attempts made: 10
=======================================
[Test Number: 9]
The breaking point: 9
The highest safe floor: 8
The number of attempts made: 11
=======================================
[Test Number: 10]
The breaking point: 10
The highest safe floor: 9
The number of attempts made: 12
=======================================
[Test Number: 11]
The breaking point: 11
The highest safe floor: 10
The number of attempts made: 13
=======================================
[Test Number: 12]
The breaking point: 12
The highest safe floor: 11
The number of attempts made: 14
=======================================
[Test Number: 13]
The breaking point: 13
The highest safe floor: 12
The number of attempts made: 15
=======================================
[Test Number: 14]
The breaking point: 14
The highest safe floor: 13
The number of attempts made: 15
=======================================
[Test Number: 15]
The breaking point: 15
The highest safe floor: 14
The number of attempts made: 3
=======================================
[Test Number: 16]
The breaking point: 16
The highest safe floor: 15
The number of attempts made: 4
=======================================
[Test Number: 17]
The breaking point: 17
The highest safe floor: 16
The number of attempts made: 5
=======================================
[Test Number: 18]
The breaking point: 18
The highest safe floor: 17
The number of attempts made: 6
=======================================
[Test Number: 19]
The breaking point: 19
The highest safe floor: 18
The number of attempts made: 7
=======================================
[Test Number: 20]
The breaking point: 20
The highest safe floor: 19
The number of attempts made: 8
=======================================
[Test Number: 21]
The breaking point: 21
The highest safe floor: 20
The number of attempts made: 9
=======================================
[Test Number: 22]
The breaking point: 22
The highest safe floor: 21
The number of attempts made: 10
=======================================
[Test Number: 23]
The breaking point: 23
The highest safe floor: 22
The number of attempts made: 11
=======================================
[Test Number: 24]
The breaking point: 24
The highest safe floor: 23
The number of attempts made: 12
=======================================
[Test Number: 25]
The breaking point: 25
The highest safe floor: 24
The number of attempts made: 13
=======================================
[Test Number: 26]
The breaking point: 26
The highest safe floor: 25
The number of attempts made: 14
=======================================
[Test Number: 27]
The breaking point: 27
The highest safe floor: 26
The number of attempts made: 15
=======================================
[Test Number: 28]
The breaking point: 28
The highest safe floor: 27
The number of attempts made: 15
=======================================
[Test Number: 29]
The breaking point: 29
The highest safe floor: 28
The number of attempts made: 4
=======================================
[Test Number: 30]
The breaking point: 30
The highest safe floor: 29
The number of attempts made: 5
=======================================
[Test Number: 31]
The breaking point: 31
The highest safe floor: 30
The number of attempts made: 6
=======================================
[Test Number: 32]
The breaking point: 32
The highest safe floor: 31
The number of attempts made: 7
=======================================
[Test Number: 33]
The breaking point: 33
The highest safe floor: 32
The number of attempts made: 8
=======================================
[Test Number: 34]
The breaking point: 34
The highest safe floor: 33
The number of attempts made: 9
=======================================
[Test Number: 35]
The breaking point: 35
The highest safe floor: 34
The number of attempts made: 10
=======================================
[Test Number: 36]
The breaking point: 36
The highest safe floor: 35
The number of attempts made: 11
=======================================
[Test Number: 37]
The breaking point: 37
The highest safe floor: 36
The number of attempts made: 12
=======================================
[Test Number: 38]
The breaking point: 38
The highest safe floor: 37
The number of attempts made: 13
=======================================
[Test Number: 39]
The breaking point: 39
The highest safe floor: 38
The number of attempts made: 14
=======================================
[Test Number: 40]
The breaking point: 40
The highest safe floor: 39
The number of attempts made: 15
=======================================
[Test Number: 41]
The breaking point: 41
The highest safe floor: 40
The number of attempts made: 15
=======================================
[Test Number: 42]
The breaking point: 42
The highest safe floor: 41
The number of attempts made: 5
=======================================
[Test Number: 43]
The breaking point: 43
The highest safe floor: 42
The number of attempts made: 6
=======================================
[Test Number: 44]
The breaking point: 44
The highest safe floor: 43
The number of attempts made: 7
=======================================
[Test Number: 45]
The breaking point: 45
The highest safe floor: 44
The number of attempts made: 8
=======================================
[Test Number: 46]
The breaking point: 46
The highest safe floor: 45
The number of attempts made: 9
=======================================
[Test Number: 47]
The breaking point: 47
The highest safe floor: 46
The number of attempts made: 10
=======================================
[Test Number: 48]
The breaking point: 48
The highest safe floor: 47
The number of attempts made: 11
=======================================
[Test Number: 49]
The breaking point: 49
The highest safe floor: 48
The number of attempts made: 12
=======================================
[Test Number: 50]
The breaking point: 50
The highest safe floor: 49
The number of attempts made: 13
=======================================
[Test Number: 51]
The breaking point: 51
The highest safe floor: 50
The number of attempts made: 14
=======================================
[Test Number: 52]
The breaking point: 52
The highest safe floor: 51
The number of attempts made: 15
=======================================
[Test Number: 53]
The breaking point: 53
The highest safe floor: 52
The number of attempts made: 15
=======================================
[Test Number: 54]
The breaking point: 54
The highest safe floor: 53
The number of attempts made: 6
=======================================
[Test Number: 55]
The breaking point: 55
The highest safe floor: 54
The number of attempts made: 7
=======================================
[Test Number: 56]
The breaking point: 56
The highest safe floor: 55
The number of attempts made: 8
=======================================
[Test Number: 57]
The breaking point: 57
The highest safe floor: 56
The number of attempts made: 9
=======================================
[Test Number: 58]
The breaking point: 58
The highest safe floor: 57
The number of attempts made: 10
=======================================
[Test Number: 59]
The breaking point: 59
The highest safe floor: 58
The number of attempts made: 11
=======================================
[Test Number: 60]
The breaking point: 60
The highest safe floor: 59
The number of attempts made: 12
=======================================
[Test Number: 61]
The breaking point: 61
The highest safe floor: 60
The number of attempts made: 13
=======================================
[Test Number: 62]
The breaking point: 62
The highest safe floor: 61
The number of attempts made: 14
=======================================
[Test Number: 63]
The breaking point: 63
The highest safe floor: 62
The number of attempts made: 15
=======================================
[Test Number: 64]
The breaking point: 64
The highest safe floor: 63
The number of attempts made: 15
=======================================
[Test Number: 65]
The breaking point: 65
The highest safe floor: 64
The number of attempts made: 7
=======================================
[Test Number: 66]
The breaking point: 66
The highest safe floor: 65
The number of attempts made: 8
=======================================
[Test Number: 67]
The breaking point: 67
The highest safe floor: 66
The number of attempts made: 9
=======================================
[Test Number: 68]
The breaking point: 68
The highest safe floor: 67
The number of attempts made: 10
=======================================
[Test Number: 69]
The breaking point: 69
The highest safe floor: 68
The number of attempts made: 11
=======================================
[Test Number: 70]
The breaking point: 70
The highest safe floor: 69
The number of attempts made: 12
=======================================
[Test Number: 71]
The breaking point: 71
The highest safe floor: 70
The number of attempts made: 13
=======================================
[Test Number: 72]
The breaking point: 72
The highest safe floor: 71
The number of attempts made: 14
=======================================
[Test Number: 73]
The breaking point: 73
The highest safe floor: 72
The number of attempts made: 15
=======================================
[Test Number: 74]
The breaking point: 74
The highest safe floor: 73
The number of attempts made: 15
=======================================
[Test Number: 75]
The breaking point: 75
The highest safe floor: 74
The number of attempts made: 8
=======================================
[Test Number: 76]
The breaking point: 76
The highest safe floor: 75
The number of attempts made: 9
=======================================
[Test Number: 77]
The breaking point: 77
The highest safe floor: 76
The number of attempts made: 10
=======================================
[Test Number: 78]
The breaking point: 78
The highest safe floor: 77
The number of attempts made: 11
=======================================
[Test Number: 79]
The breaking point: 79
The highest safe floor: 78
The number of attempts made: 12
=======================================
[Test Number: 80]
The breaking point: 80
The highest safe floor: 79
The number of attempts made: 13
=======================================
[Test Number: 81]
The breaking point: 81
The highest safe floor: 80
The number of attempts made: 14
=======================================
[Test Number: 82]
The breaking point: 82
The highest safe floor: 81
The number of attempts made: 15
=======================================
[Test Number: 83]
The breaking point: 83
The highest safe floor: 82
The number of attempts made: 15
=======================================
[Test Number: 84]
The breaking point: 84
The highest safe floor: 83
The number of attempts made: 9
=======================================
[Test Number: 85]
The breaking point: 85
The highest safe floor: 84
The number of attempts made: 10
=======================================
[Test Number: 86]
The breaking point: 86
The highest safe floor: 85
The number of attempts made: 11
=======================================
[Test Number: 87]
The breaking point: 87
The highest safe floor: 86
The number of attempts made: 12
=======================================
[Test Number: 88]
The breaking point: 88
The highest safe floor: 87
The number of attempts made: 13
=======================================
[Test Number: 89]
The breaking point: 89
The highest safe floor: 88
The number of attempts made: 14
=======================================
[Test Number: 90]
The breaking point: 90
The highest safe floor: 89
The number of attempts made: 15
=======================================
[Test Number: 91]
The breaking point: 91
The highest safe floor: 90
The number of attempts made: 15
=======================================
[Test Number: 92]
The breaking point: 92
The highest safe floor: 91
The number of attempts made: 10
=======================================
[Test Number: 93]
The breaking point: 93
The highest safe floor: 92
The number of attempts made: 11
=======================================
[Test Number: 94]
The breaking point: 94
The highest safe floor: 93
The number of attempts made: 12
=======================================
[Test Number: 95]
The breaking point: 95
The highest safe floor: 94
The number of attempts made: 13
=======================================
[Test Number: 96]
The breaking point: 96
The highest safe floor: 95
The number of attempts made: 14
=======================================
[Test Number: 97]
The breaking point: 97
The highest safe floor: 96
The number of attempts made: 15
=======================================
[Test Number: 98]
The breaking point: 98
The highest safe floor: 97
The number of attempts made: 15
=======================================
[Test Number: 99]
The breaking point: 99
The highest safe floor: 98
The number of attempts made: 10
=======================================
</pre>
<p>It works! <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/11/20/java-challenge-dropping-balloons-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Web Service Development using Tomcat and OpenEJB</title>
		<link>http://blog.lckymn.com/2009/11/01/web-service-development-using-tomcat-and-openejb/</link>
		<comments>http://blog.lckymn.com/2009/11/01/web-service-development-using-tomcat-and-openejb/#comments</comments>
		<pubDate>Sun, 01 Nov 2009 05:42:30 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Web Application Development]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[@WebService]]></category>
		<category><![CDATA[Apache Tomcat]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Eclipse Ganymede]]></category>
		<category><![CDATA[Eclipse JEE]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[EJB3]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Java EE 5]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[OpenEJB]]></category>
		<category><![CDATA[OpenJPA]]></category>
		<category><![CDATA[Tomcat]]></category>
		<category><![CDATA[Web Service]]></category>
		<category><![CDATA[Web Service Client]]></category>
		<category><![CDATA[Web Service Development]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=432</guid>
		<description><![CDATA[<p>In addition to the previous post, <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">Java EE Application Development using Tomcat, OpenEJB and Hibernate</a>, this post will demonstrate how to create a web service using Tomcat and OpenEJB. The web service in this blog entry uses the code from <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">the previous post</a>, so if you haven&#8217;t read <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">it</a> yet, better read <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">it</a> first.</p> <p>Firstly, create a web service interface then put the <a href="http://java.sun.com/javase/6/docs/api/javax/jws/WebService.html" target="_blank">@WebService</a> annotation.</p> package com.lckymn.kevin.test.openejb.webservice; import javax.jws.WebService; import <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/11/01/web-service-development-using-tomcat-and-openejb/">Web Service Development using Tomcat and OpenEJB</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>In addition to the previous post, <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">Java EE Application Development using Tomcat, OpenEJB and Hibernate</a>, this post will demonstrate how to create a web service using Tomcat and OpenEJB.  The web service in this blog entry uses the code from <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">the previous post</a>, so if you haven&#8217;t read <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">it</a> yet, better read <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/" target="_blank">it</a> first.</p>
<p>Firstly, create a web service interface then put the <a href="http://java.sun.com/javase/6/docs/api/javax/jws/WebService.html" target="_blank">@WebService</a> annotation.</p>
<pre class="brush: java; tab-size: 4; title: ; toolbar: true; notranslate">
package com.lckymn.kevin.test.openejb.webservice;

import javax.jws.WebService;

import com.lckymn.kevin.test.openejb.domain.User;

@WebService
public interface TestWebService
{
	User getUser(Long id);
}
</pre>
<p>Secondly, create a class implmenting the web service interface with also the <a href="http://java.sun.com/javase/6/docs/api/javax/jws/WebService.html" target="_blank">@WebService</a> annotation then specify the <code>targetNamespace</code> and the <code>serviceName</code> as you wish. In my case, these are<br />
<code><br />
targetNamespace: "http://webservice.webhibernate.test"<br />
serviceName: "testWebService"<br />
</code><br />
To use the UserService EJB, injected by OpenEJB, make the web service class session EJB with the @Stateless annotation.</p>
<pre class="brush: java; tab-size: 4; title: ; toolbar: true; notranslate">
package com.lckymn.kevin.test.openejb.webservice;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.jws.WebService;

import com.lckymn.kevin.test.openejb.domain.User;
import com.lckymn.kevin.test.openejb.service.UserService;

@Local
@Stateless
@WebService(targetNamespace = &quot;http://webservice.webhibernate.test&quot;, serviceName = &quot;testWebService&quot;)
public class TestWebServiceImpl implements TestWebService
{
	@EJB
	private UserService userService;

	@Override
	public User getUser(Long id)
	{
		return userService.getUser(id);
	}
}
</pre>
<p>The class above simply returns a User entity object acquired from the <code>UserService</code> EJB, made in the previous post.</p>
<p>That&#8217;s it. You have just made your web service. When the server starts and the application is deployed, the EJB container (OpenEJB) registers the above EJB as a web service.</p>
<p>Now, let&#8217;s make a web service client. To make a very simple example client, I&#8217;m going to create a servlet in the same web application to which the web service belongs, yet it can of course be another web application, Java desktop application, Java console application and so on.</p>
<p>Here is a simple servlet which gets the user ID from the client-side then accesses the web service to get the User. After that it passes the User entity object through the <code>HttpSession</code> to the JSP page to display.</p>
<pre class="brush: java; tab-size: 4; title: ; toolbar: true; notranslate">
package com.lckymn.kevin.test.openejb.web;

import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.lckymn.kevin.test.openejb.domain.User;
import com.lckymn.kevin.test.openejb.webservice.TestWebService;

public class TestWebServiceClientServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		Service service = Service.create(new URL(&quot;http://localhost:8080/TestWebServiceImpl?wsdl&quot;), new QName(
				&quot;http://webservice.webhibernate.test&quot;, &quot;testWebService&quot;));
		TestWebService testWebService = service.getPort(TestWebService.class);

		String userIdParam = request.getParameter(&quot;userId&quot;);

		HttpSession session = request.getSession();
		if (null == userIdParam || 0 == userIdParam.length())
		{
			session.removeAttribute(&quot;userFound&quot;);
		}
		else
		{
			Long userId = Long.parseLong(userIdParam);
			User user = testWebService.getUser(userId);
			session.setAttribute(&quot;userFound&quot;, user);
		}
		getServletContext().getRequestDispatcher(&quot;/WEB-INF/jsp/webServiceClient.jsp&quot;)
				.forward(request, response);
	}
}
</pre>
<p>This is just a simple example thus I omitted validation (e.g. checking whether the userId is &#8216;long&#8217; type or not) and exception handling. </p>
<p>The WSDL location is the server URI + &#8220;/&#8221; + web service class name + &#8220;?wsdl&#8221;.<br />
<code>http://localhost:8080/TestWebServiceImpl?wsdl</code><br />
The parameters of the <a href="http://java.sun.com/javase/6/docs/api/javax/xml/namespace/QName.html" target="_blank">QName</a> constructor are <code>namespaceURI</code> and <code>localPart</code>, and these are defined in the web service. If you look at the web service code again, these can easily be found from the <a href="http://java.sun.com/javase/6/docs/api/javax/jws/WebService.html" target="_blank">@WebService</a> annotation.</p>
<pre class="brush: java; gutter: false; highlight: [1]; title: ; notranslate">
@WebService(targetNamespace = &quot;http://webservice.webhibernate.test&quot;, serviceName = &quot;testWebService&quot;)
public class TestWebServiceImpl implements TestWebService
{
	...
}
</pre>
<p>The value of the <code>targetNamespace</code> element is the <code>namespaceURI</code> of the <code>QName</code> constructor, and the value of the <code>serviceNmae</code> element is the <code>localPart</code>.</p>
<p>This is web.xml. The information of the new servlet, the web service client just created, is added to the web.xml, made in the previous post.</p>
<pre class="brush: xml; highlight: [14,15,16,17,18,19,20,21,22,23]; tab-size: 4; title: ; toolbar: true; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot; id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
  &lt;display-name&gt;test-web-hibernate&lt;/display-name&gt;
  &lt;servlet&gt;
    &lt;description&gt;&lt;/description&gt;
    &lt;display-name&gt;TestServlet&lt;/display-name&gt;
    &lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.lckymn.kevin.test.openejb.web.TestServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/Test&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  &lt;servlet&gt;
    &lt;description&gt;&lt;/description&gt;
    &lt;display-name&gt;TestWebServiceClientServlet&lt;/display-name&gt;
    &lt;servlet-name&gt;TestWebServiceClientServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.lckymn.kevin.test.openejb.web.TestWebServiceClientServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;TestWebServiceClientServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/TestWebServiceClient&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  &lt;welcome-file-list&gt;
    &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre>
<p>Finally, add a JSP file to enter the userId to search a user and to display the user info.<br />
In my case, I added the file to the <code>application/WebContent/WEB-INF/jsp</code> directory which is the same location that I set in the <code>TestWebServiceClientServlet</code> (look at the TestWebServiceClientServlet code above).<br />
<code>test-web-hibernate/WebContent/WEB-INF/jsp/webServiceClient.jsp</code></p>
<pre class="brush: xml; tab-size: 4; title: ; toolbar: true; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
    pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div&gt;
&lt;form name=&quot;userForm&quot; action=&quot;TestWebServiceClient&quot; method=&quot;post&quot; &gt;
	&lt;input type=&quot;text&quot; name=&quot;userId&quot; value=&quot;&quot; /&gt; &lt;input type=&quot;submit&quot; name=&quot;userIdSubmit&quot; value=&quot;Search&quot; /&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;div&gt;
	&lt;table&gt;
		&lt;tr&gt;
			&lt;td&gt;User ID: &lt;/td&gt;&lt;td&gt;${userFound.id }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Username: &lt;/td&gt;&lt;td&gt;${userFound.username }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Surname: &lt;/td&gt;&lt;td&gt;${userFound.surname }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Given name: &lt;/td&gt;&lt;td&gt;${userFound.givenName }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Email: &lt;/td&gt;&lt;td&gt;${userFound.email }&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>To test it, open the browser and enter the following URI.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">

http://localhost:8080/test-web-hibernate/TestWebServiceClient

</pre>
<p>It displays the screen like below<br />
<div id="attachment_436" class="wp-caption alignnone" style="width: 712px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test01.jpg" alt="Enter userId and click the &#039;Search&#039; button" title="Web Service Client Test 01" width="702" height="268" class="size-full wp-image-436" /></a><p class="wp-caption-text">Enter userId and click the 'Search' button</p></div><br />
-Enter a userId to search then click the &#8216;Search&#8217; button.</p>
<p>It displays the result yet there is one problem. It doesn&#8217;t display the userId.<br />
<div id="attachment_437" class="wp-caption alignnone" style="width: 712px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test02.jpg" alt="The Search Result: userId is not displayed" title="Web Service Client Test 02" width="702" height="268" class="size-full wp-image-437" /></a><p class="wp-caption-text">The Search Result: userId is not displayed</p></div><br />
This is because the id field of the User entity class that I created in the previous blog entry does not have the mutator that is the setId() method so when the entity object is passed through the web service, the id field is not included.</p>
<p>There are two simple ways to solve this problem. Either way works so choose whichever you like.</p>
<p>1. Add the setter method. If there is setId() method, the id field is included when the object is passed through the web service. The reason why I did not write the setter method is that the id is supposed to be set by Hibernate and to avoid any problems caused by setting it manually, I did not write it. However, it is required in order to include the field when passing object through the web service. So adding setter can solve this problem. If you do not like this solution as you do not like to put the setter method due to the reason I explained, you can try the second solution.</p>
<pre class="brush: java; highlight: [19,20,21,22]; tab-size: 4; title: ; toolbar: true; notranslate">
@Entity
@Table(name = &quot;users&quot;)
public class User implements Serializable
{
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = &quot;user_id&quot;)
	private Long id;

	...

	public Long getId()
	{
		return id;
	}

	public void setId(Long id)
	{
		this.id = id;
	}
	
	...
}
</pre>
<p>OR</p>
<p>2. If you add the <a href="http://java.sun.com/javase/6/docs/api/javax/xml/bind/annotation/XmlElement.html" target="_blank">@XmlElement</a> annotation to the id field and set the value of the <code>required</code> element to <code>true</code>, the id field is included even without the setter method.</p>
<pre class="brush: java; highlight: [15]; tab-size: 4; title: ; toolbar: true; notranslate">
...

import javax.xml.bind.annotation.XmlElement;

...
@Entity
@Table(name = &quot;users&quot;)
public class User implements Serializable
{
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = &quot;user_id&quot;)
	@XmlElement(required = true)
	private Long id;

	...

	public Long getId()
	{
		return id;
	}

	// No setId() required
	
	...
}
</pre>
<p>Now, test if it works.<br />
<div id="attachment_436" class="wp-caption alignnone" style="width: 712px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test01.jpg" alt="Enter userId and click the &#039;Search&#039; button" title="Web Service Client Test 01" width="702" height="268" class="size-full wp-image-436" /></a><p class="wp-caption-text">Enter userId and click the 'Search' button</p></div></p>
<p>It works!<br />
<div id="attachment_438" class="wp-caption alignnone" style="width: 712px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/11/01_web_service_client_test03.jpg" alt="The Search Result: userId is displayed correctly" title="Web Service Client Test 03" width="702" height="268" class="size-full wp-image-438" /></a><p class="wp-caption-text">The Search Result: userId is displayed correctly</p></div></p>
<p>There are also other ways and tools to create a web service in Java. I used to use <a href="http://ws.apache.org/axis/" target="_blank">Apache Axis</a> then later moved to <a href="http://xfire.codehaus.org/" target="_blank">XFire</a>. Now, I use <a href="http://cxf.apache.org/" target="_blank">Apache CXF</a> which is considered as XFire 2.0.  It is, as explained here, very easy to create a web service client, yet it can be even easier with <a href="http://ws.apache.org/axis/java/user-guide.html#WSDL2JavaBuildingStubsSkeletonsAndDataTypesFromWSDL" target="_blank">WSDL2Java</a> from <a href="http://ws.apache.org/axis/" target="_blank">Apache Axis</a> or <a href="http://ws.apache.org/axis2/1_3/userguide-creatingclients.html" target="_blank">WSDL2Java</a> from <a href="http://ws.apache.org/axis2/" target="_blank">Apache Axis2</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/11/01/web-service-development-using-tomcat-and-openejb/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Java EE Application Development using Tomcat, OpenEJB and Hibernate</title>
		<link>http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/</link>
		<comments>http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 17:06:59 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Web Application Development]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Apache Tomcat]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Eclipse Ganymede]]></category>
		<category><![CDATA[Eclipse JEE]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[EJB3]]></category>
		<category><![CDATA[Generic DAO]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Java EE 5]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[OpenEJB]]></category>
		<category><![CDATA[OpenJPA]]></category>
		<category><![CDATA[Software Development Environment]]></category>
		<category><![CDATA[Tomcat]]></category>
		<category><![CDATA[Web Application Development]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=380</guid>
		<description><![CDATA[<p>Java EE Application Development using Tomcat, OpenEJB and Hibernate</p> <p>Before I start writing this blog entry, I&#8217;d better point out a few things.</p> This blog entry is not about how to make a good <a href="http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition" target="_blank">Java EE</a> application yet is about how to use <a href="http://openejb.apache.org/" target="_blank">OpenEJB</a> on <a href="http://tomcat.apache.org/" target="_blank">Apache Tomcat server</a> with <a href="https://www.hibernate.org/" target="_blank">Hibernate</a> as an implementation of the <a href="http://en.wikipedia.org/wiki/Java_Persistence_API" target="_blank">JPA</a>. If you are looking for better Java EE development or similar, this one is <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/">Java EE Application Development using Tomcat, OpenEJB and Hibernate</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>Java EE Application Development using Tomcat, OpenEJB and Hibernate</p>
<p>Before I start writing this blog entry, I&#8217;d better point out a few things.</p>
<ul>
<li>This blog entry is not about how to make a good <a href="http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition" target="_blank">Java EE</a> application yet is about how to use <a href="http://openejb.apache.org/" target="_blank">OpenEJB</a> on <a href="http://tomcat.apache.org/" target="_blank">Apache Tomcat server</a> with <a href="https://www.hibernate.org/" target="_blank">Hibernate</a> as an implementation of the <a href="http://en.wikipedia.org/wiki/Java_Persistence_API" target="_blank">JPA</a>.  If you are looking for better Java EE development or similar, this one is not for you. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li> I don&#8217;t have enough time to explain all the details of how to install JDK, Eclipse, Tomcat and so on. So this post doesn&#8217;t have that level of details. I simply assume that you&#8217;ve already known how to install JDK, Eclipse and Tomcat. Well, anyway, installing Eclipse and Tomcat are as easy as extracting a zip or gzip file and JDK installation is also not difficult at all.</li>
<li>This post does not cover how to use those tools and frameworks in the production environment. In other words, it is only for the development. Setting up the environment for development and for the production use have some differences. It is, however not that hard to figure out once you know how to use those in your development environment.</li>
</ul>
<h2>1. Development Environment</h2>
<p>First of all, I&#8217;m going to list the development environment and tools I have for this introductory tutorial post.<br />
(Click each name and it will take you to the download page).</p>
<p>OS: <a href="http://www.ubuntu.com" target="_blank">Ubuntu Linux</a> <a href="http://releases.ubuntu.com/9.04/" target="_blank">Jaunty Jackalope 9.04 Desktop 64bit</a><br />
Java: <a href="http://java.sun.com/javase/downloads" target="_blank">Sun JDK 1.6.0_16 (64 bit)</a> (it&#8217;s from the Ubuntu repository).<br />
Database: <a href="http://dev.mysql.com/downloads/mysql/5.0.html" target="_blank">MySQL Community Server 5.0</a> (it&#8217;s from the Ubuntu repository).<br />
JDBC Driver: <a href="http://dev.mysql.com/downloads/connector/j/5.1.html" target="_blank">MySQL Connector/J 5.1.10</a><br />
Eclipse: <a href="http://eclipse.org/downloads/packages/release/ganymede/sr2" target="_blank">Eclipse IDE for Java EE Developer Ganymede SR2 (Eclipse 3.4.2)</a><br />
Tomcat: <a href="http://tomcat.apache.org/download-60.cgi" target="_blank">Tomcat 6.0.20</a><br />
OpenEJB: <a href="http://tomee.apache.org/openejb-3.1.1.html" target="_blank">OpenEJB 3.1.1 (openejb.war)</a><br />
Hibernate: <a href="http://sourceforge.net/projects/hibernate/files/" target="_blank">Hibernate 3.2.1GA</a> (including hibernate-3.2.1.ga, hibernate-annotations-3.2.1.ga, hibernate-entitymanager-3.2.1.ga) (OR just <a href="http://goo.gl/cFjBt" target="_blank">&gt;&gt;download this&lt;&lt;</a>)</p>
<h2>2. Installing OpenEJB</h2>
<p>Java EE server normally means a Java application server which consists of a <a href="http://en.wikipedia.org/wiki/Java_Servlet" target="_blank">Servlet</a> container and an <a href="http://en.wikipedia.org/wiki/EJB_container" target="_blank">EJB</a> container. Apache Tomcat is a servlet container but not an EJB container so you need to have an EJB container like OpenEJB or use a Java EE server instead of Tomcat in order to use EJB unless you&#8217;re using the frameworks supporting EJB such as Spring framework. &#8220;So if I use Tomcat server and Spring framework, do I not need OpenEJB or other Java EE servers to use EJB?&#8221; No, you don&#8217;t.</p>
<p>Since this post is, as already mentioned, about using using EJB on Tomcat with OpenEJB and Hibernate, I will first show you how to install OpenEJB.</p>
<p>Before installing OpenEJB, don&#8217;t forget to copy JDBC driver that is, in this post, MySQL Connector/J to the $TOMCAT/lib directory.<br />
-Copy the Connector/J jar file to the Tomcat&#8217;s library directory ($TOMCAT_HOME/lib)<br />
<div id="attachment_381" class="wp-caption alignnone" style="width: 727px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/00_copy_connector-j01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/00_copy_connector-j01.jpg" alt="Select Connector/J and Extract to the $TOMCAT/lib directory." title="Extract Connector/J" width="717" height="493" class="size-full wp-image-381" /></a><p class="wp-caption-text">Select Connector/J and Extract to the $TOMCAT/lib directory.</p></div></p>
<div id="attachment_382" class="wp-caption alignnone" style="width: 432px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/00_copy_connector-j02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/00_copy_connector-j02.jpg" alt="Make sure the Connector/J jar file is in the $TOMCAT/lib directory." title="Check Connector/J is in the $TOMCAT/lib directory" width="422" height="395" class="size-full wp-image-382" /></a><p class="wp-caption-text">Make sure the Connector/J jar file is in the $TOMCAT/lib directory.</p></div>
<p>-Run Eclipse and add Tomcat server: Menu &#8211; Window -> Preferences -> Server -> Runtime Environments -> Add</p>
<p>-Download the openejb.war, OpenEJB for Tomcat, and import the file from Eclipse.<br />
-Right click on the project explorer -> Import -> WAR file<br />
<div id="attachment_383" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/02_import_openejb01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/02_import_openejb01.jpg" alt="Right Click on the project explorer -&gt; Import -&gt; WAR File" title="Import OpenEJB 01" width="688" height="509" class="size-full wp-image-383" /></a><p class="wp-caption-text">Right Click on the project explorer -> Import -> WAR File</p></div></p>
<p>-Click the &#8216;Browse&#8217; button and select the openejb.war file -> Select your Tomcat 6.0 as the target runtime. -> Click the &#8216;Finish&#8217; button.<br />
<div id="attachment_384" class="wp-caption alignnone" style="width: 623px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/02_import_openejb02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/02_import_openejb02.jpg" alt="Click the &#039;Browse&#039; button and select the openejb.war file -&gt; Select your Tomcat 6.0 as the target runtime. -&gt; Click the &#039;Finish&#039; button." title="Import OpenEJB 02" width="613" height="408" class="size-full wp-image-384" /></a><p class="wp-caption-text">Click the 'Browse' button and select the openejb.war file -> Select your Tomcat 6.0 as the target runtime. -> Click the 'Finish' button.</p></div></p>
<h2>3. Add OpenEJB project to the Server to deploy</h2>
<p>-Right click on the server name in the &#8216;Server&#8217; view -> Select the &#8216;Add and Remove Projects&#8230;&#8217;<br />
<div id="attachment_385" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server01.jpg" alt="Right click on the server name in the &#039;Server&#039; view -&gt; Select the &#039;Add and Remove Projects...&#039;" title="03 Add to the Server 01" width="688" height="509" class="size-full wp-image-385" /></a><p class="wp-caption-text">Right click on the server name in the 'Server' view -> Select the 'Add and Remove Projects...'</p></div></p>
<p>-Select openejb -> Click the &#8216;Add&#8217; button -> Click the &#8216;Finish&#8217; button<br />
<div id="attachment_386" class="wp-caption alignnone" style="width: 623px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server02.jpg" alt="Select openejb -&gt; Click the &#039;Add&#039; button -&gt; Click the &#039;Finish&#039; button" title="03 Add_to the Server 02" width="613" height="546" class="size-full wp-image-386" /></a><p class="wp-caption-text">Select openejb -> Click the 'Add' button -> Click the 'Finish' button</p></div></p>
<p>-openejb is ready to be deployed.<br />
<div id="attachment_387" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/03_add_to_server03.jpg" alt="openejb is deployed." title="07 Add to the Server 03" width="688" height="509" class="size-full wp-image-387" /></a><p class="wp-caption-text">openejb is deployed.</p></div></p>
<p>-Now run the server to deploy openejb.<br />
<div id="attachment_388" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/04_run_server01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/04_run_server01.jpg" alt="Run the server to deploy openejb" title="08 Run the Server 01" width="688" height="509" class="size-full wp-image-388" /></a><p class="wp-caption-text">Run the server to deploy openejb</p></div></p>
<p>-openejb is successfully deployed.<br />
<div id="attachment_389" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/04_run_server02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/04_run_server02.jpg" alt="the openejb is successfully deployed." title="09 Run the Server 02" width="688" height="509" class="size-full wp-image-389" /></a><p class="wp-caption-text">the openejb is successfully deployed.</p></div></p>
<h2>4. Set up DataSource</h2>
<p>-openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace.<br />
<div id="attachment_390" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file01.jpg" alt="openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace." title="10 Copy openejb.xml file 01" width="688" height="509" class="size-full wp-image-390" /></a><p class="wp-caption-text">openejb.xml has to be copied to the Tomcat configuration folder of the Eclipse workspace.</p></div></p>
<p>If you are using Tomcat without OpenEJB and want to create a DataSource, you might do by putting the DataSource info to Tomcat&#8217;s server.xml file or your application&#8217;s context configuration file (your_app/META-INF/context.xml).  Yet to create the DataSource for JPA, you need to do through <code>openejb.xml</code> file. It is created in the Tomcat folder in the <code>.metadata</code> folder of your Eclipse workspace when the openejb project is deployed. However, it is not copied automatically to the configuration folder of your Eclipse workspace, you should copy the openejb.xml file to the Server configuration folder manually. If the location of the workspace is &#8216;/home/username/workspace&#8217;, the Tomcat is in &#8216;/home/username/test-workspace/.metadata/.plugins/org.eclipse.wst.server.core&#8217; and the openejb.xml file can be found in the &#8216;/home/username/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf&#8217; directory.</p>
<p>-Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace.<br />
<div id="attachment_391" class="wp-caption alignnone" style="width: 625px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file02.jpg" alt="Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace." title="11 Copy openejb.xml file 02" width="615" height="309" class="size-full wp-image-391" /></a><p class="wp-caption-text">Find the openejb.xml file and copy to the Tomcat configuration folder of the Eclipse workspace.</p></div><br />
<div id="attachment_392" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/05_copy_openejb_xml_file03.jpg" alt="Paste the file to the Tomcat configuration folder of the Eclipse workspace." title="12 Copy openejb.xml file 03" width="688" height="509" class="size-full wp-image-392" /></a><p class="wp-caption-text">Paste the file to the Tomcat configuration folder of the Eclipse workspace.</p></div></p>
<p>-Open the &#8216;openejb.xml&#8217; file then you can find the default DataSources.<br />
<div id="attachment_395" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/06_set_up_datasource01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/06_set_up_datasource01.jpg" alt="Open the &#039;openejb.xml&#039; file then you can find the default DataSources" title="13 Set up the datasource 01" width="688" height="509" class="size-full wp-image-395" /></a><p class="wp-caption-text">Open the 'openejb.xml' file then you can find the default DataSources</p></div><br />
One is JTA managed while the other is not. Both use <a href="http://hsqldb.org" title="HSQLDB" target="_blank">HSQLDB</a> which is a Java database. If you don&#8217;t have any database installed on you computer or if you want, you can use it.  As mentioned early, I am going to use MySQL so a new data source set up for MySQL is required.</p>
<p>-Add the following lines and modify for your own database.</p>
<pre class="brush: xml; gutter: false; title: ; notranslate">
&lt;Resource id=&quot;mysqlDataSource&quot; type=&quot;javax.sql.DataSource&quot;&gt;
	JdbcDriver      	com.mysql.jdbc.Driver
	JdbcUrl         	jdbc:mysql://localhost:3306/test_db
	UserName        	test_user
	Password        	1234
	JtaManaged      	true
	DefaultAutoCommit 	true
	InitialSize     	3
	MaxActive       	20
	MinIdle         	20
	MaxIdle         	0
	MaxWait         	50000
	ValidationQuery 	SELECT 1
	TestOnBorrow    	true
	TestOnReturn    	false
	TestWhileIdle   	false
&lt;/Resource&gt;
</pre>
<div id="attachment_396" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/06_set_up_datasource02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/06_set_up_datasource02.jpg" alt="DataSource to access the MySQL database." title="14 Set up the datasource 02" width="688" height="624" class="size-full wp-image-396" /></a><p class="wp-caption-text">DataSource to access the MySQL database.</p></div>
<p>If you want to use OpenJPA as an implmentation of the JPA, you can do now. However, to use Hibernate there is one more step to do.</p>
<h2>5. Install Hibernate</h2>
<p>If you just have the Hibernate jar files in your application directory (e.g. your_app/WEB-INF/lib), the EJB container that is OpenEJB cannot find the hibernate classes as it is the container, it tries to find the hibernate class from the server&#8217;s lib directory. Thus just like you need to copy the JDBC driver, in this post it&#8217;s &#8216;Connector/J&#8217;, to the tomcat&#8217;s lib directory, the hibernate jar files should be placed in the Tomcat&#8217;s lib directory.</p>
<p>Otherwise, you will get an error like this.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
ERROR - Unable to deploy collapsed ear in war /test-web-hibernate: Exception: Creating application failed: /home/username/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/test-web-hibernate: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernatePersistence: org.hibernate.ejb.HibernatePersistence
org.apache.openejb.OpenEJBException: Creating application failed: /home/username/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/test-web-hibernate: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernatePersistence: org.hibernate.ejb.HibernatePersistence
	at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:658)
	at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:442)
	at org.apache.openejb.tomcat.catalina.TomcatWebAppBuilder.start(TomcatWebAppBuilder.java:249)
	at org.apache.openejb.tomcat.catalina.GlobalListenerSupport.lifecycleEvent(GlobalListenerSupport.java:58)
	at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
	at org.apache.catalina.core.StandardContext.start(StandardContext.java:4339)
	at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3190)
	at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:404)
	at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1309)
	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1601)
	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1610)
	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1610)
	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1590)
	at java.lang.Thread.run(Thread.java:619)
Caused by: org.apache.openejb.OpenEJBException: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernatePersistence: org.hibernate.ejb.HibernatePersistence
	at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:487)
	... 13 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernatePersistence
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
	at org.apache.openejb.assembler.classic.PersistenceBuilder.createEntityManagerFactory(PersistenceBuilder.java:177)
	at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:482)
	... 13 more
</pre>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
So you have to copy the hibernate to the Tomcat&#8217;s lib directory. Unfortunately, the latest version of Hibernate (3.4.0GA) does not work on OpenEJB 3.1.1 yet I found the 3.2.1GA version works. However, there is another problem. When you try to use Tomcat, OpenEJB and Hibernate, it may not work well with the dependency libraries required by Hibernate 3.2.1GA so you should carefully choose the dependency files.  This means you need to test and find which ones are working well with OpenEJB and which are not.  Fortunately, here is a good news.  I tested and found the files working well with Tomcat 6 and OpenEJB and zipped the files. Thus you can simply download this file and extract it to the $TOMCAT/lib directory.</p>
<p><a href="http://goo.gl/cFjBt">Click Here to Download the File!</a></p>
<p>After downloading, extract all the files inside to the Tomcat&#8217;s lib directory (<code>$TOMCAT/lib</code>) just like what you did to install JDBC driver, Connector/J.
</div>
<h2>6. Adding logger configuration (Optional)</h2>
<p>By default, OpenEJB creates a log file in the Eclipse&#8217;s $TOMCAT/logs directory. It is very inconvenient as you have to open the file when you want to get information from the log.  However, it is very easy to change this to make it displayed on the Console view of Eclipse.</p>
<p>-Right click on the Tomcat configuration folder -> Select &#8216;New&#8217; -> Select &#8216;File&#8217; -> crated a file with the name &#8216;logging.properties&#8217;.<br />
<div id="attachment_398" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/07_add_logger_config01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/07_add_logger_config01.jpg" alt="Right click on the Tomcat configuration folder -&gt; Select &#039;New&#039; -&gt; Select &#039;File&#039; -&gt; crated a file with the name &#039;logging.properties&#039;." title="15 Add the logger config 01" width="688" height="543" class="size-full wp-image-398" /></a><p class="wp-caption-text">Right click on the Tomcat configuration folder -> Select 'New' -> Select 'File' -> crated a file with the name 'logging.properties'.</p></div></p>
<p>-Open the file and put the following lines</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
log4j.rootLogger                   = fatal,C
log4j.category.OpenEJB             = warn
log4j.category.OpenEJB.options     = info
log4j.category.OpenEJB.server      = info
log4j.category.OpenEJB.startup     = info
log4j.category.OpenEJB.startup.service = warn
log4j.category.OpenEJB.startup.config = info
log4j.category.OpenEJB.hsql        = info
log4j.category.CORBA-Adapter       = info
log4j.category.Transaction         = warn
log4j.category.org.apache.activemq = error
log4j.category.org.apache.geronimo = error
log4j.category.openjpa             = error

log4j.appender.C                   = org.apache.log4j.ConsoleAppender
log4j.appender.C.layout            = org.apache.log4j.SimpleLayout
</pre>
<div id="attachment_399" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/07_add_logger_config02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/07_add_logger_config02.jpg" alt="Put the logger config details" title="16 Add the logger config 02" width="688" height="543" class="size-full wp-image-399" /></a><p class="wp-caption-text">Put the logger config details</p></div>
<h2>7. Create Web Application Project</h2>
<p>Now, you can develop a web application using EJB3 and Hibernate as the implementation of the JPA.</p>
<p>-Right click on the project explorer -> Select &#8216;New&#8217; -> Select &#8216;Dynamic Web Project&#8217;<br />
<div id="attachment_400" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project01.jpg" alt="Right click on the project explorer -&gt; Select &#039;New&#039; -&gt; Select &#039;Dynamic Web Project&#039;" title="17 Create Project 01" width="688" height="543" class="size-full wp-image-400" /></a><p class="wp-caption-text">Right click on the project explorer -> Select 'New' -> Select 'Dynamic Web Project'</p></div></p>
<p>-Put the name you like -> Select the &#8216;Apache Tomcat v6.0&#8242; as the target runtime -> Select &#8217;2.5&#8242; as the version of &#8216;Dynamic Web Module&#8217; -> Select the default Tomcat configuration or your own one -> Click the &#8216;Next&#8217; button.<br />
<div id="attachment_401" class="wp-caption alignnone" style="width: 715px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project02.jpg" alt="Put the name you like -&gt; Select the &#039;Apache Tomcat v6.0&#039; as the target runtime -&gt; Select &#039;2.5&#039; as the version of &#039;Dynamic Web Module&#039; -&gt; Select the default Tomcat configuration or your own one -&gt; Click the &#039;Next&#039; button." title="18 Create Project 02" width="705" height="640" class="size-full wp-image-401" /></a><p class="wp-caption-text">Put the name you like -> Select the 'Apache Tomcat v6.0' as the target runtime -> Select '2.5' as the version of 'Dynamic Web Module' -> Select the default Tomcat configuration or your own one -> Click the 'Next' button.</p></div></p>
<p>-Change the project context root and directory names if you like -> Click the &#8216;Finish&#8217; button.<br />
<div id="attachment_402" class="wp-caption alignnone" style="width: 715px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project03.jpg" alt="Change the project context root and directory names if you like -&gt; Click the &#039;Finish&#039; button." title="19 Create Project 03" width="705" height="640" class="size-full wp-image-402" /></a><p class="wp-caption-text">Change the project context root and directory names if you like -> Click the 'Finish' button.</p></div></p>
<p>-Right click on the Server to add the project -> Select the &#8216;Add and Remove Projects&#8230;&#8217;.<br />
<div id="attachment_403" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project04.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project04.jpg" alt="Right click on the Server to add the project -&gt; Select the &#039;Add and Remove Projects...&#039;." title="20 Create Project 04" width="688" height="543" class="size-full wp-image-403" /></a><p class="wp-caption-text">Right click on the Server to add the project -> Select the 'Add and Remove Projects...'.</p></div></p>
<p>-Select the project you created -> Click the &#8216;Add&#8217; button -> Click the &#8216;Finish&#8217; button.<br />
<div id="attachment_404" class="wp-caption alignnone" style="width: 623px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project05.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project05.jpg" alt="Select the project you created -&gt; Click the &#039;Add&#039; button -&gt; Click the &#039;Finish&#039; button." title="21 Create Project 05" width="613" height="546" class="size-full wp-image-404" /></a><p class="wp-caption-text">Select the project you created -> Click the 'Add' button -> Click the 'Finish' button.</p></div></p>
<p>-Both openejb and your project are added.<br />
<div id="attachment_405" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project06.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/08_create_project06.jpg" alt="Both openejb and your project are added." title="22 Create Project 06" width="688" height="543" class="size-full wp-image-405" /></a><p class="wp-caption-text">Both openejb and your project are added.</p></div></p>
<h2>8. Make JPA Project</h2>
<p>To use the JPA support feature of Eclipse, you need to change the project facet configuration.</p>
<p>-Right click on your project -> Select the &#8216;Properties&#8217;.<br />
<div id="attachment_406" class="wp-caption alignnone" style="width: 702px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project01.jpg" alt="Right click on your project -&gt; Select the &#039;Properties&#039;." title="23 Make JPA Project 01" width="692" height="525" class="size-full wp-image-406" /></a><p class="wp-caption-text">Right click on your project -> Select the 'Properties'.</p></div></p>
<p>-Select the &#8216;Project Facets&#8217; -> Check &#8216;Java Persistence 1.0&#8242; -> Click the &#8216;Further configuration available&#8230;&#8217; link.<br />
<div id="attachment_407" class="wp-caption alignnone" style="width: 666px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project02.jpg" alt="Select the &#039;Project Facets&#039; -&gt; Check &#039;Java Persistence 1.0&#039; -&gt; Click the &#039;Further configuration available...&#039; link." title="24 Make JPA Project 02" width="656" height="574" class="size-full wp-image-407" /></a><p class="wp-caption-text">Select the 'Project Facets' -> Check 'Java Persistence 1.0' -> Click the 'Further configuration available...' link.</p></div></p>
<p>-Select &#8216;Generic&#8217; -> Select &#8216;None&#8217; or your own connection or add a new connection if you wish -> Select &#8216;Use implementation provided by server runtime&#8217; -> Select &#8216;Discover annotated classes automatically&#8217; -> Uncheck &#8216;Create orm.xml&#8217; option -> Click the &#8216;OK&#8217; button.<br />
<div id="attachment_408" class="wp-caption alignnone" style="width: 623px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/09_make_jpa_project03.jpg" alt="Select &#039;Generic&#039; -&gt; Select &#039;None&#039; or your own connection or add a new connection if you wish -&gt; Select &#039;Use implementation provided by server runtime&#039; -&gt; Select &#039;Discover annotated classes automatically&#039; -&gt; Uncheck &#039;Create orm.xml&#039; option -&gt; Click the &#039;OK&#039; button." title="25 Make JPA Project 03" width="613" height="660" class="size-full wp-image-408" /></a><p class="wp-caption-text">Select 'Generic' -> Select 'None' or your own connection or add a new connection if you wish -> Select 'Use implementation provided by server runtime' -> Select 'Discover annotated classes automatically' -> Uncheck 'Create orm.xml' option -> Click the 'OK' button.</p></div><br />
(I do usually not set up the connection yet if you want to generate entity classes from the existing tables, you&#8217;d better set it up).</p>
<h2>9. Add Java EE 5 API library file</h2>
<p>You also need to add the Java EE 5 API library file so you can use all the necessary annotations required for EJB3 and JPA.</p>
<p>-Select &#8216;Java Build Path on the left-hand side menu -> Select the &#8216;Libraries&#8217; tab -> Click the &#8216;Add JARs&#8230;&#8217; button.<br />
<div id="attachment_409" class="wp-caption alignnone" style="width: 914px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api02.jpg" alt="Select &#039;Java Build Path on the left-hand side menu -&gt; Select the &#039;Libraries&#039; tab -&gt; Click the &#039;Add JARs...&#039; button." title="26 Add JavaEE API 02" width="904" height="584" class="size-full wp-image-409" /></a><p class="wp-caption-text">Select 'Java Build Path on the left-hand side menu -> Select the 'Libraries' tab -> Click the 'Add JARs...' button.</p></div></p>
<p>-Select &#8216;javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -> Click the &#8216;OK&#8217; button.<br />
<div id="attachment_410" class="wp-caption alignnone" style="width: 480px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api03.jpg" alt="Select &#039;javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -&gt; Click the &#039;OK&#039; button." title="27 Add JavaEE 5 API 03" width="470" height="761" class="size-full wp-image-410" /></a><p class="wp-caption-text">Select 'javaee-api-5.0-2.jar in the openejb/WebContent/lib directory -> Click the 'OK' button.</p></div></p>
<p>-Click the &#8216;OK&#8217; button.<br />
<div id="attachment_411" class="wp-caption alignnone" style="width: 914px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api04.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/10_add_javaee-api04.jpg" alt="Click the &#039;OK&#039; button." title="28 Add JavaEE 5 API 04" width="904" height="584" class="size-full wp-image-411" /></a><p class="wp-caption-text">Click the 'OK' button.</p></div><br />
-JPA configuration file (persistence.xml) is added.<br />
<div id="attachment_412" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml01.jpg" alt="JPA configuration file (persistence.xml) is added" title="29 Config persistence_xml 01" width="688" height="525" class="size-full wp-image-412" /></a><p class="wp-caption-text">JPA configuration file (persistence.xml) is added</p></div></p>
<h2>10. Configure persistence.xml file</h2>
<p>It&#8217;s the last step before starting to programme the actual application.</p>
<p>-Open the persistence.xml file -> Type &#8216;org.hibernate.ejb.HibernatePersistence&#8217; to the &#8216;Persistence Provider&#8217;.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
org.hibernate.ejb.HibernatePersistence
</pre>
<div id="attachment_413" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml02.jpg" alt="Open the persistence.xml file -&gt; put &#039;org.hibernate.ejb.HibernatePersistence&#039; to the &#039;Persistence Provider&#039;." title="30 Config persistence_xml 02" width="688" height="543" class="size-full wp-image-413" /></a><p class="wp-caption-text">Open the persistence.xml file -> put 'org.hibernate.ejb.HibernatePersistence' to the 'Persistence Provider'.</p></div>
<p>-Click the &#8216;Connection&#8217; tab -> Select the &#8216;JTA&#8217; as the &#8216;Transaction Type&#8217; -> Type &#8216;mysqlDataSource&#8217; or your datasource name added in the previous steps. -> Press &#8216;Ctrl + S&#8217; keys to save the file.<br />
<div id="attachment_414" class="wp-caption alignnone" style="width: 698px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml03.jpg" alt="Click the &#039;Connection&#039; tab -&gt; Select the &#039;JTA&#039; as the &#039;Transaction Type&#039; -&gt; Type &#039;mysqlDataSource&#039; or your datasource name added in the previous steps. -&gt; Press &#039;Ctrl + S&#039; keys to save the file." title="31 Config persistence.xml 03" width="688" height="543" class="size-full wp-image-414" /></a><p class="wp-caption-text">Click the 'Connection' tab -> Select the 'JTA' as the 'Transaction Type' -> Type 'mysqlDataSource' or your datasource name added in the previous steps. -> Press 'Ctrl + S' keys to save the file.</p></div></p>
<p>-If you select the &#8216;Source&#8217; tab, you should see the XML like this.<br />
<div id="attachment_415" class="wp-caption alignnone" style="width: 740px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml04.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/10/12_config_persistence_xml04.jpg" alt="If you select the &#039;Source&#039; tab, you should see the XML like above." title="32 Config persistence.xml 04" width="730" height="537" class="size-full wp-image-415" /></a><p class="wp-caption-text">If you select the 'Source' tab, you should see the XML like above.</p></div></p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;persistence version=&quot;1.0&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd&quot;&gt;
	&lt;persistence-unit name=&quot;test-web-hibernate&quot; transaction-type=&quot;JTA&quot;&gt;
		&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
		&lt;jta-data-source&gt;mysqlDataSource&lt;/jta-data-source&gt;
	&lt;/persistence-unit&gt;
&lt;/persistence&gt;
</pre>
<p>-If you want Hibernate to automatically create the database tables based on your entity classes every time the server is restarted (in other words, the application is re-deployed), You can add Hibernate specific properties.</p>
<pre class="brush: xml; highlight: [9,10,11]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;persistence version=&quot;1.0&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd&quot;&gt;
	&lt;persistence-unit name=&quot;test-web-hibernate&quot; transaction-type=&quot;JTA&quot;&gt;
		&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
		&lt;jta-data-source&gt;mysqlDataSource&lt;/jta-data-source&gt;
		&lt;properties&gt;
			&lt;property name=&quot;hibernate.hbm2ddl.auto&quot; value=&quot;create&quot; /&gt;
		&lt;/properties&gt;
	&lt;/persistence-unit&gt;
&lt;/persistence&gt;
</pre>
<h2>11. Test</h2>
<p>Finally, we have the development environment ready. To test, if I can use EJB3 and JPA with Hibernate on Tomcat, I made a very simple application.  The way I design it is not my usual way yet I used Generic DAO pattern which I usually use.</p>
<h3>11.1. Entity classes</h3>
<p>Here is my only entity class in this test.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = &quot;users&quot;)
public class User implements Serializable
{
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = &quot;user_id&quot;)
	private Long id;

	@Column(name = &quot;username&quot;, nullable = false, length = 30)
	private String username;

	@Column(name = &quot;surname&quot;, nullable = false, length = 50)
	private String surname;

	@Column(name = &quot;given_name&quot;, nullable = false, length = 50)
	private String givenName;

	@Column(name = &quot;email&quot;, nullable = true, length = 255)
	private String email;

	public Long getId()
	{
		return id;
	}

	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public String getSurname()
	{
		return surname;
	}

	public void setSurname(String surname)
	{
		this.surname = surname;
	}

	public String getGivenName()
	{
		return givenName;
	}

	public void setGivenName(String givenName)
	{
		this.givenName = givenName;
	}

	public String getEmail()
	{
		return email;
	}

	public void setEmail(String email)
	{
		this.email = email;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
		{
			return true;
		}

		if (!(obj instanceof User))
		{
			return false;
		}
		User that = (User) obj;
		return (username == that.getUsername() || (null != username &amp;&amp; username.equals(that.getUsername())));
	}

	@Override
	public int hashCode()
	{
		return (null == username ? 0 : username.hashCode());
	}
}
</pre>
<h3>11.2. Generic DAOs</h3>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.dao;

public interface GenericDao&lt;E, K&gt;
{
	E find(K id);

	void persist(E e);

	void remove(E e);
}
</pre>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.dao;

import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public abstract class AbstractGenericDao&lt;E, K&gt; implements GenericDao&lt;E, K&gt;
{
	private Class&lt;E&gt; classType;

	@PersistenceContext(unitName = &quot;test-web-hibernate&quot;)
	private EntityManager entityManager;

	@SuppressWarnings(&quot;unchecked&quot;)
	public AbstractGenericDao()
	{
		ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
		classType = (Class&lt;E&gt;) parameterizedType.getActualTypeArguments()[0];
	}

	protected final EntityManager getEntityManager()
	{
		if (null == entityManager)
		{
			throw new IllegalStateException(&quot;EntityManager is not injected.&quot;);
		}
		return entityManager;
	}

	@Override
	public E find(K id)
	{
		return getEntityManager().find(classType, id);
	}

	@Override
	public void persist(E e)
	{
		getEntityManager().persist(e);
	}

	@Override
	public void remove(E e)
	{
		getEntityManager().remove(e);
	}
}
</pre>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.dao;

import java.util.List;

import javax.ejb.Local;

import com.lckymn.kevin.test.openejb.domain.User;

@Local
public interface UserDao extends GenericDao&lt;User, Long&gt;
{
	List&lt;User&gt; getUsersByGivenName(String givenName);
}
</pre>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.dao;

import java.util.List;

import javax.ejb.Stateless;

import com.lckymn.kevin.test.openejb.domain.User;

@Stateless
public class UserDaoImpl extends AbstractGenericDao&lt;User, Long&gt; implements UserDao
{
	@SuppressWarnings(&quot;unchecked&quot;)
	@Override
	public List&lt;User&gt; getUsersByGivenName(String givenName)
	{
		return getEntityManager().createQuery(&quot;from User where givenName = ?&quot;)
				.setParameter(1, givenName)
				.getResultList();
	}
}
</pre>
<h3>11.3. Services</h3>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.service;

import java.util.List;

import javax.ejb.Local;

import com.lckymn.kevin.test.openejb.domain.User;

@Local
public interface UserService
{
	User getUser(long id);

	void AddUser(User user);

	List&lt;User&gt; getUserByGivenName(String givenName);
}
</pre>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.service;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import com.lckymn.kevin.test.openejb.dao.UserDao;
import com.lckymn.kevin.test.openejb.domain.User;

@Stateless
public class UserServiceBean implements UserService
{
	@EJB
	private UserDao userDao;

	@Override
	public User getUser(long id)
	{
		return userDao.find(id);
	}

	@Override
	public void AddUser(User user)
	{
		userDao.persist(user);
	}

	@Override
	public List&lt;User&gt; getUserByGivenName(String givenName)
	{
		return userDao.getUsersByGivenName(givenName);
	}

}
</pre>
<h3>11. 4. Servlets</h3>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.openejb.web;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lckymn.kevin.test.openejb.domain.User;
import com.lckymn.kevin.test.openejb.service.UserService;

public class TestServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	@EJB
	private UserService userService;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		User user = new User();
		user.setUsername(&quot;kevinlee&quot;);
		user.setSurname(&quot;Lee&quot;);
		user.setGivenName(&quot;Kevin&quot;);
		user.setEmail(&quot;test@test.test&quot;);

		userService.AddUser(user);

		HttpSession session = request.getSession();
		session.setAttribute(&quot;user&quot;, user);

		getServletContext().getRequestDispatcher(&quot;/index.jsp&quot;)
				.forward(request, response);
	}

}
</pre>
<h3>11.5. Deployment Descriptor (web.xml)</h3>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
	&lt;display-name&gt;test-web-hibernate&lt;/display-name&gt;
	&lt;servlet&gt;
		&lt;description&gt;&lt;/description&gt;
		&lt;display-name&gt;TestServlet&lt;/display-name&gt;
		&lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;com.lckymn.kevin.test.openejb.web.TestServlet&lt;/servlet-class&gt;
	&lt;/servlet&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/Test&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
	&lt;welcome-file-list&gt;
		&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
	&lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre>
<h3>11. 6. index.jsp</h3>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
    pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div&gt;
	&lt;table&gt;
		&lt;tr&gt;
			&lt;td&gt;User ID: &lt;/td&gt;&lt;td&gt;${user.id }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Username: &lt;/td&gt;&lt;td&gt;${user.username }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Surname: &lt;/td&gt;&lt;td&gt;${user.surname }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Given name: &lt;/td&gt;&lt;td&gt;${user.givenName }&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Email: &lt;/td&gt;&lt;td&gt;${user.email }&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>12. Run the test application</h2>
<p>Access the application URI</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">

http://localhost:8080/test-web-hibernate/Test

</pre>
<p>It gives me this result.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
User ID: 	1
Username: 	kevinlee
Surname: 	Lee
Given name: 	Kevin
Email: 	test@test.test
</pre>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
*** Important ***<br />
Note: Whenever you make changes in your application, Tomcat restarts the application context so that you don&#8217;t need to restart the server to apply the changes you made.  However, as mentioned several times, you are now using the EJB container so restarting application context is not enough to get your changes applied. Therefore, the EJB container has to be restarted which means you need to restart the Tomcat server to get the changes applied.
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/10/17/java-ee-application-development-using-tomcat-openejb-and-hibernate/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>VMware and SpringSource</title>
		<link>http://blog.lckymn.com/2009/08/11/vmware-and-springsource/</link>
		<comments>http://blog.lckymn.com/2009/08/11/vmware-and-springsource/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 08:10:49 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Acquire]]></category>
		<category><![CDATA[SpringSource]]></category>
		<category><![CDATA[VMware]]></category>
		<category><![CDATA[VMware and SpringSource]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=372</guid>
		<description><![CDATA[<p>I heard very surprising news today morning which is <a href="http://www.springsource.com" target="_blank">SpringSource</a> has agreed to be acquired by <a href="http://www.vmware.com" target="_blank">VMware</a>.</p> <p><a href="http://blog.springsource.com/2009/08/10/springsource-chapter-two/" target="_blank">http://blog.springsource.com/2009/08/10/springsource-chapter-two/</a> <a href="http://www.vmware.com/company/news/releases/springsource.html" target="_blank">http://www.vmware.com/company/news/releases/springsource.html</a> <a href="http://blogs.vmware.com/console/2009/08/vmware-acquires-springsource.html" target="_blank">http://blogs.vmware.com/console/2009/08/vmware-acquires-springsource.html</a> <a href="http://www.earthtimes.org/articles/show/vmware-to-acquire-springsource,921934.shtml" target="_blank">http://www.earthtimes.org/articles/show/vmware-to-acquire-springsource,921934.shtml</a></p> <p>Looks like a good deal for both companies. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p> <p>VMware recently hired <a href="http://www.techcrunch.com/2009/07/13/google-loses-engineering-director-who-once-caused-steve-ballmer-to-melt-down/" target="_blank">Mark Lucovsky</a> from Google and now has SpringSource. I guess VMware is really doing well. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p> ]]></description>
				<content:encoded><![CDATA[<p>I heard very surprising news today morning which is <a href="http://www.springsource.com" target="_blank">SpringSource</a> has agreed to be acquired by <a href="http://www.vmware.com" target="_blank">VMware</a>.</p>
<p><a href="http://blog.springsource.com/2009/08/10/springsource-chapter-two/" target="_blank">http://blog.springsource.com/2009/08/10/springsource-chapter-two/</a><br />
<a href="http://www.vmware.com/company/news/releases/springsource.html" target="_blank">http://www.vmware.com/company/news/releases/springsource.html</a><br />
<a href="http://blogs.vmware.com/console/2009/08/vmware-acquires-springsource.html" target="_blank">http://blogs.vmware.com/console/2009/08/vmware-acquires-springsource.html</a><br />
<a href="http://www.earthtimes.org/articles/show/vmware-to-acquire-springsource,921934.shtml" target="_blank">http://www.earthtimes.org/articles/show/vmware-to-acquire-springsource,921934.shtml</a></p>
<p>Looks like a good deal for both companies. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>VMware recently hired <a href="http://www.techcrunch.com/2009/07/13/google-loses-engineering-director-who-once-caused-steve-ballmer-to-melt-down/" target="_blank">Mark Lucovsky</a> from Google and now has SpringSource. I guess VMware is really doing well. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/08/11/vmware-and-springsource/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Eclipse &#8211; &#8220;Too many open files&#8221; Problem</title>
		<link>http://blog.lckymn.com/2009/08/11/eclipse-too-many-open-files-problem/</link>
		<comments>http://blog.lckymn.com/2009/08/11/eclipse-too-many-open-files-problem/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 07:39:39 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Development Tools]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Ubuntu Linux]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Eclipse Ganymede]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[Ganymede]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Problem]]></category>
		<category><![CDATA[Too many open files]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=365</guid>
		<description><![CDATA[<p>If your OS is Linux and you are using Eclipse, you might possibly see the following error messages or similar after installing lots of plug-ins in Eclipse. In my case, it usually happened after installing <a href="http://www.eclipse.org/tptp/" target="_blank">TPTP</a> (I&#8217;m using Ubuntu Linux 9.04 Jaunty Jackalope Desktop 64bit by the way).</p> Plug-in org.eclipse.jst.server.tomcat.core was unable to load class org.eclipse.jst.server.tomcat.core.internal.TomcatLaunchConfigurationDelegate. /eclipse_installed_path/eclipse/configuration/org.eclipse.osgi/.lazy.15 (Too many open files) <p>or</p> Problems occurred while trying to save the state of the workbench. Could not read master table. <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/08/11/eclipse-too-many-open-files-problem/">Eclipse &#8211; &#8220;Too many open files&#8221; Problem</a>...]</p>]]></description>
				<content:encoded><![CDATA[<p>If your OS is Linux and you are using Eclipse, you might possibly see the following error messages or similar after installing lots of plug-ins in Eclipse. In my case, it usually happened after installing <a href="http://www.eclipse.org/tptp/" target="_blank">TPTP</a> (I&#8217;m using Ubuntu Linux 9.04 Jaunty Jackalope Desktop 64bit by the way).</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Plug-in org.eclipse.jst.server.tomcat.core was unable to load class org.eclipse.jst.server.tomcat.core.internal.TomcatLaunchConfigurationDelegate.
 /eclipse_installed_path/eclipse/configuration/org.eclipse.osgi/.lazy.15 (Too many open files)
</pre>
<p>or</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
Problems occurred while trying to save the state of the workbench.
 Could not read master table.
 /your_workspace/.metadata/.plugins/org.eclipse.core.resources/.safetable/org.eclipse.core.resources (Too many open files)
</pre>
<p>or</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
java.util.zip.ZipException: error in opening zip file
</pre>
<p>This is because there are too many files opened and these are more files than the number of open files allowed . So Eclipse cannot open more files and displays the errors above.</p>
<p>Let&#8217;s see the number of open files.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ lsof | wc -l 
</pre>
<p>e.g.)</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ lsof | wc -l 
8965
</pre>
<p>In my case, it was 8965.</p>
<p>What about the number of files Eclipse opens. To see it, use </p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ lsof | grep eclipse | wc -l 
</pre>
<p>In my case, </p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ lsof | grep eclipse | wc -l 
2094
</pre>
<p>2094 files are opened.</p>
<p>Now check the limitation of open files</p>
<pre class="brush: bash; gutter: false; highlight: [9]; title: ; notranslate">
$ ulimit -a 
core file size          (blocks, -c) #
data seg size           (kbytes, -d) #
scheduling priority             (-e) #
file size               (blocks, -f) #
pending signals                 (-i) #
max locked memory       (kbytes, -l) #
max memory size         (kbytes, -m) #
open files                      (-n) 1024
pipe size            (512 bytes, -p) #
POSIX message queues     (bytes, -q) #
real-time priority              (-r) #
stack size              (kbytes, -s) #
cpu time               (seconds, -t) #
max user processes              (-u) #
virtual memory          (kbytes, -v) #
file locks                      (-x) #
</pre>
<p>or just use</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ ulimit -n 
1024
</pre>
<p>To change it, open the file /etc/security/limits.conf and put a greater number than 1024 depending on the number of open files you checked with <code>lsof | wc -l</code> just before.<br />
For example,<br />
Open the file</p>
<pre class="brush: plain; gutter: false; highlight: [3,4]; title: ; notranslate">
$ gksudo gedit /etc/security/limits.conf 
add these lines
*                soft    nofile          9216
*                hard    nofile          9216
</pre>
<p>I just chose some big number that is 9216 (9 * 1024) as it&#8217;s greater than 8965 </p>
<p>Log out and in then check with ulimit. It should show like this.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ ulimit -n 
9216
</pre>
<p>You may try this</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ ulimit -n 9216 
</pre>
<p>yet I don&#8217;t believe it changes the limit for open files permanently. So you&#8217;d better modify <code>/etc/security/limits.conf</code> file.</p>
<p>If it is still not changed. Restart the computer and check again. <span style="text-decoration: line-through">If it still doesn&#8217;t show the changed value, open /etc/pam.d/common-session file and add <code>session required pam_limits.so</code></span>.</p>
<div style="text-decoration: line-through">
Open the file to edit</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ gksudo gedit /etc/pam.d/common-session 
</pre>
<p>Add the following line</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
session required pam_limits.so
</pre>
<p>Log out and in. Now it should work!</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ ulimit -n 
9216
</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/08/11/eclipse-too-many-open-files-problem/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
