<?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>SolitaryGeek &#187; James</title>
	<atom:link href="http://solitarygeek.com/author/James/feed" rel="self" type="application/rss+xml" />
	<link>http://solitarygeek.com</link>
	<description>James Selvakumar&#039;s Blog</description>
	<lastBuildDate>Tue, 21 Dec 2010 04:35:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Wicket: Serving static files</title>
		<link>http://solitarygeek.com/java/wicket-serving-static-files</link>
		<comments>http://solitarygeek.com/java/wicket-serving-static-files#comments</comments>
		<pubDate>Mon, 06 Dec 2010 08:07:00 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Wicket]]></category>

		<guid isPermaLink="false">http://solitarygeek.com/uncategorized/wicket-serving-static-files</guid>
		<description><![CDATA[<p>I recently came across a situation where I have to serve some static html files in a wicket application. Though it&#8217;s pretty simple, thanks to the ultra easy way wicket offers to write components, things can get tricky especially with the request path.</p> <p>So I thought of documenting this for my own future reference and for the sake of the community.</p> <p>Without wasting time, let me quickly explain how to serve static files with wicket (blatantly copied from wicket-examples).</p> <p>Assumptions</p> <p>I assume that you are using wicket 1.4.x as that&#8217;s the latest stable version at the time of writing this <span style="color:#777"> . . . &#8594; Read More: <a href="http://solitarygeek.com/java/wicket-serving-static-files">Wicket: Serving static files</a></span>]]></description>
			<content:encoded><![CDATA[<p>I recently came across a situation where I have to serve some static html files in a <a href="http://wicket.apache.org">wicket</a> application. Though it&#8217;s pretty simple, thanks to the ultra easy way wicket offers to write components, things can get tricky especially with the request path.</p>
<p>So I thought of documenting this for my own future reference and for the sake of the community.</p>
<p>Without wasting time, let me quickly explain how to serve static files with wicket (blatantly copied from <a href="http://wicketstuff.org/wicket14/staticpages/">wicket-examples</a>).</p>
<p><strong>Assumptions</strong></p>
<p>I assume that you are using wicket 1.4.x as that&#8217;s the latest stable version at the time of writing this post.</p>
<p><strong>Component</strong></p>
<p>First let us write a reusable component class called &#8220;StaticLink&#8221;.</p>
<pre class="brush: java; title: ; notranslate">
private class StaticLink extends WebMarkupContainer {
public StaticLink(String id, IModel model) {
super(id, model);
add(new AttributeModifier(&quot;href&quot;, true, model));
}
}
</pre>
<p><strong>Html</strong></p>
<p>In the html file where you want to put this link, add something like this:</p>
<pre class="brush: xml; title: ; notranslate">&lt;a&gt; My static link&lt;/a&gt;</pre>
<p><strong>Java</strong></p>
<p>In the respective java file, all you need to do is this:</p>
<pre class="brush: java; title: ; notranslate">
String contextPath = RequestUtils.toAbsolutePath(RequestCycle.get().
     getRequest().getRelativePathPrefixToWicketHandler());
add(new StaticLink(&quot;myStaticLink&quot;, new Model(contextPath + &quot;docs/index.html&quot;)));
</pre>
<p>Here were are resolving the absolute url of the static page which will free you from the <a href="http://stackoverflow.com/questions/2619833/wicket-relative-to-absolute-url-or-get-base-url">hassles of using a relative url</a> especially for static pages. The &#8220;contextPath&#8221; which we are constructing here will have the trailing &#8220;/&#8221; so you need not add it.</p>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/java/wicket-serving-static-files/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Extracting only date part of a date time column using JPA/Hibernate</title>
		<link>http://solitarygeek.com/java/extracting-only-date-part-of-a-date-time-column-using-jpa-hibernate</link>
		<comments>http://solitarygeek.com/java/extracting-only-date-part-of-a-date-time-column-using-jpa-hibernate#comments</comments>
		<pubDate>Mon, 11 Oct 2010 10:41:00 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cast]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[mssql]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sqlserver]]></category>

		<guid isPermaLink="false">http://solitarygeek.com/java/extracting-only-date-part-of-a-date-time-column-using-hibernate</guid>
		<description><![CDATA[I recently had a need where I had to get only the date portion from a column whose data type is "timestamp" (which is mapped using @TimeStamp annotation). After hours of investigation, I found a way to do that using standard jpa/hql queries and hence thought of documenting it in this post. MySQL has a simple "date() function" that would just give the date part from a date time expression. Microsoft SQL Server offers a couple of ways to achieve the same. Unfortunately, I couldn't find any standard ways provided by jpa/hibernate to achieve this. Interestingly, the closest thing that can be considered as "standard" is the "cast function" which many databases seem to support. This prompted me to go for this solution because I felt this might be clean, as the syntax across different databases are pretty much similar. <span style="color:#777"> . . . &#8594; Read More: <a href="http://solitarygeek.com/java/extracting-only-date-part-of-a-date-time-column-using-jpa-hibernate">Extracting only date part of a date time column using JPA/Hibernate</a></span>]]></description>
			<content:encoded><![CDATA[<p>I recently came across a situation where I have to get only the date portion from a column whose data type is &#8220;timestamp&#8221; (which is mapped using @TimeStamp annotation). After hours of investigation, I found a way to do that using standard jpa/hql queries and hence thought of documenting it in this post.</p>
<p>MySQL has a simple &#8220;<a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date">date() function</a>&#8221; that would just give the date part from a date time expression. Microsoft SQL Server offers a <a href="http://stackoverflow.com/questions/566998/get-only-the-date-part-of-datetime-in-mssql">couple of ways</a> to achieve the same. Unfortunately, I couldn&#8217;t find any standard ways provided by jpa/hibernate to achieve this.</p>
<p>Interestingly, the closest thing that can be considered as &#8220;standard&#8221; is the &#8220;cast function&#8221; which <a href="http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast">many</a> databases seem to <a href="http://msdn.microsoft.com/en-us/library/aa226054%28SQL.80%29.aspx">support</a>. This prompted me to go for this solution because I felt this might be clean, as the syntax across different databases are pretty much similar.</p>
<p>So I came up with a query something similar to this:</p>
<pre class="brush: sql; title: ; notranslate">

select cast(myDateTimeColumn as date) from MyTable
</pre>
<p>This worked flawlessly on MySQL! Great..!</p>
<p>But, I quickly ran into problem when hibernate executed the same jpl/hql query against Microsoft SQL Server. Hibernate acted a bit smart and generated the following query (trimmed for clarification):</p>
<pre class="brush: sql; title: ; notranslate">

select cast(myDateTimeColumn as dateTime) from MyTable
</pre>
<p>That&#8217;s not what I expected! That defeats the purpose of the &#8220;cast&#8221; function itself <img src='http://solitarygeek.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Why the heck Hibernate does this weird stuff? I thought of digging deep to learn more about this behaviour of Hibernate.</p>
<p>Hibernate uses the &#8220;<a href="http://www.javadocexamples.com/org/hibernate/dialect/function/org.hibernate.dialect.function.CastFunction-source.html">CastFunction</a>&#8221; class to handle &#8220;cast&#8221; functions you write in your queries. Upon exploring the class, you will find that this is how the &#8220;cast&#8221; functions are interpreted,</p>
<pre class="brush: java; title: ; notranslate">
 return &quot;cast(&quot; + args.get(0) + &quot; as &quot; + sqlType + ')';
 </pre>
<p>Where the &#8220;sqlType&#8221; is determined as follows:</p>
<pre class="brush: java; title: ; notranslate">
 String sqlType = factory.getDialect().getCastTypeName( sqlTypeCodes[0] );
 </pre>
<p>Hibernate <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.hibernate/hibernate/3.2.7.ga/org/hibernate/dialect/Dialect.java?av=f">stores</a> the type names in a <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.hibernate/hibernate/3.2.7.ga/org/hibernate/dialect/TypeNames.java?av=f">hash map</a> and by default, <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.hibernate/hibernate/3.2.7.ga/org/hibernate/dialect/AbstractTransactSQLDialect.java">registers</a> the &#8220;Date&#8221; type as &#8220;datetime&#8221; like this:</p>
<pre class="brush: java; title: ; notranslate">
 registerColumnType( Types.DATE, &quot;datetime&quot; );
 </pre>
<p>And that is exactly the reason for the weird behaviour I mentioned in the SQLServerDialect.</p>
<p>Fortunately, hibernate provides <a href="https://forum.hibernate.org/viewtopic.php?p=2436442">hooks</a> to <a href="http://community.jboss.org/wiki/Customsequences">tweak</a> the dialects to support the features that are not otherwise available by default. All we need to do this is to write a custom dialect class by subclassing the appropriate dialect. This is the custom sql server dialect class that I came with:</p>
<pre class="brush: java; title: ; notranslate">
 package org.hibernate.dialect;

import java.sql.Types;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;

/**
 *
 * @author James Selvakumar
 */
 public class CustomSQLServerDialect extends SQLServerDialect
 {
 private static final Logger logger = LoggerFactory.getLogger(CustomSQLServerDialect.class);

@Override
 public String getCastTypeName(int code)
 {
 String castTypeName = &quot;&quot;;
 if (code == Types.DATE) {
 castTypeName = &quot;date&quot;;
 } else {
 castTypeName = super.getCastTypeName(code);
 }
 logger.debug(&quot;Code: {}, cast type name: {}&quot;, code, castTypeName);
 return castTypeName;
 }
 }
 </pre>
<p>That&#8217;s pretty simple, wasn&#8217;t it? We are playing safe here by overriding only the &#8220;<a href="http://grepcode.com/file/repo1.maven.org/maven2/org.hibernate/hibernate/3.2.7.ga/org/hibernate/dialect/Dialect.java?av=f">getCastTypeName</a>&#8221; method and returning the cast type name as &#8220;date&#8221; when the type is Types.DATE. We are delegating the responsibility to the super class for &#8220;getCastTypeName&#8221; requests other than Types.DATE.</p>
<p>Just update your hibernate configuration to make use of this dialect for sql server datasource.</p>
<p>Fortunately, this solution worked flawlessly for me on both MySQL 5.1 and Microsoft SQL Server 2008 databases. It didn&#8217;t work though with HSQLDB 1.8.</p>
<p>I hope this helps some of you. If you find any issues in this article or have any other great idea, consider sharing that in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/java/extracting-only-date-part-of-a-date-time-column-using-jpa-hibernate/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NetBeans and Maven &#8211; A quick start guide</title>
		<link>http://solitarygeek.com/java/netbeans-and-maven-a-quick-start-guide</link>
		<comments>http://solitarygeek.com/java/netbeans-and-maven-a-quick-start-guide#comments</comments>
		<pubDate>Sun, 26 Sep 2010 07:30:22 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[logback]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[pom]]></category>
		<category><![CDATA[quick start]]></category>
		<category><![CDATA[slf4j]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://solitarygeek.com/?p=551</guid>
		<description><![CDATA[<p>A few months ago, I was reading the book &#8220;Wicket in Action&#8221;. I was new to Wicket and Maven then. I followed the instructions given in the book to create a maven project. The book went one step further and explained how to create eclipse and idea projects from the pom, but nothing was mentioned about NetBeans. I felt sad that there is no maven plugin out there to create projects that NetBeans can understand.</p> <p>But later when I realized that there is no such need to create Netbeans projects from Maven pom, I was thrilled. Maven, is a first <span style="color:#777"> . . . &#8594; Read More: <a href="http://solitarygeek.com/java/netbeans-and-maven-a-quick-start-guide">NetBeans and Maven &#8211; A quick start guide</a></span>]]></description>
			<content:encoded><![CDATA[<p>A few months ago, I was reading the book &#8220;Wicket in Action&#8221;. I was new to Wicket and Maven then. I followed the instructions given in the book to create a maven project. The book went one step further and explained how to create eclipse and idea projects from the pom, but nothing was mentioned about NetBeans. I felt sad that there is no maven plugin out there to create projects that NetBeans can understand.</p>
<p>But later when I realized that there is no such need to create Netbeans projects from Maven pom, I was thrilled. Maven, is a first class citizen in NetBeans. Any Maven project &#8220;<strong>is a</strong>&#8221; NetBeans project.</p>
<p>Over the months, as I continued to learn and use Maven, NetBeans made the the learning curve easy. So I thought of putting up this post to benefit new Maven users.</p>
<p><strong>Setup</strong></p>
<p>If you are using Maven for the first time, you may want to download and install it on your machine.</p>
<p>Though NetBeans comes with an embedded Maven instance (version 3.0-SNAPSHOT in NetBeans 6.9 at the time of writing this post), it&#8217;s still a good idea to have your own Maven instance, so that you can use it outside the IDE as well.</p>
<p>Installing Maven is quite easy. Download the latest Maven distribution (version 2.2.1 at the time of writing) and follow the installation instructions for your operating system.</p>
<p>Now, let&#8217;s quickly dive into action by firing up the IDE and create a new Maven project.</p>
<p><strong>Creating a new Maven project</strong></p>
<p>Open NetBeans IDE and click &#8220;File -&gt; New Project&#8221; and then choose &#8220;Maven&#8221; as the category and &#8220;Maven Project&#8221; as the project type.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-1.png" alt="NetBeans Maven Project - Step 1" width="747" height="506" /></p>
<p>In the next step, select &#8220;Maven Quickstart Archetype&#8221; as the maven archetype.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-2.png" alt="NetBeans Maven Project - Step 2" width="747" height="506" /></p>
<p>Finally, enter other details of your project and finish the wizard.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-3.png" alt="NetBeans Maven Project - Step 3" width="747" height="506" /></p>
<p>That should leave you with a new Maven project with a structure similar to this:</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-4.png" alt="NetBeans Maven Project - Step 4" width="286" height="261" /></p>
<p>One thing I like about NetBeans is that it always gives you some workable defaults whether it&#8217;s a web project or a simple java project.</p>
<p>No difference here. Just right click the java source file the IDE generated for you to watch your Maven project in action.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-5.png" alt="" width="668" height="313" /></p>
<p>And this is the default &#8220;pom.xml&#8221; the IDE generated for you:</p>
<pre class="brush: xml; title: ; notranslate">

&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;

&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;examples.maven&lt;/groupId&gt;
&lt;artifactId&gt;hellomaven&lt;/artifactId&gt;
&lt;packaging&gt;jar&lt;/packaging&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
&lt;name&gt;hellomaven&lt;/name&gt;
&lt;url&gt;http://maven.apache.org&lt;/url&gt;

&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;3.8.1&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;

&lt;/project&gt;
</pre>
<p>If you know Maven already, you know what&#8217;s happening. Even if you are new to Maven, there is nothing to worry. Every Maven project needs a few mandatory definitions and that&#8217;s what you are seeing now.</p>

<p><strong>Improving the default project</strong></p>
<p>There are a couple of things we can improve in this project. First let us cleanup the &#8220;pom.xml&#8221;. As you can see, a depedency to junit 3.8.1 has been declared in the pom. That&#8217;s pretty archaic and let us change the junit version to the latest available version.</p>
<p>You need not scratch your head to figure out what&#8217;s the latest version of junit. The IDE is right there to help you. Keep the cursor near the version element and invoke the code completion by pressing the appropriate key. (In my case it&#8217;s CTRL + SPACE). Now, the IDE should give you a list of available junit versions in the default Maven remote repository.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-61.png" alt="" width="357" height="343" /></p>
<p>Choose the latest available junit version and save the details.</p>
<p>Let us rewrite the test case making use of the recent junit enhancements. Delete the existing unit test class and create a new one by right clicking the java source file and then selecting &#8220;Tools -&gt; Create Junit Tests&#8221;. You should see the IDE displaying a dialog saying that it cannot create junit 4.x tests.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-7.png" alt="" width="351" height="180" /></p>
<p>There is nothing wrong with the IDE here. Because JUnit 4.x makes use of annotations and hence need a Java source level of 1.5 or above. By default, Maven doesn&#8217;t assume your source files to be 1.5 compatible, so you need to tell Maven exactly what Java source version you would be using in your projects. Doing that is quite simple. Open the project&#8217;s &#8220;pom.xml&#8221; in the editor and define the Java source level like this.</p>
<pre class="brush: xml; title: ; notranslate">

&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;

&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;examples.maven&lt;/groupId&gt;
&lt;artifactId&gt;hellomaven&lt;/artifactId&gt;
&lt;packaging&gt;jar&lt;/packaging&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
&lt;name&gt;hellomaven&lt;/name&gt;
&lt;url&gt;http://maven.apache.org&lt;/url&gt;

&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;4.8.1&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;

&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;source&gt;1.6&lt;/source&gt;
&lt;target&gt;1.6&lt;/target&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;

&lt;/project&gt;
</pre>
<p>You should be able to create JUnit 4.x tests from the IDE now.</p>
<p>Applying &#8220;Test Driven Development&#8221; to our project, let us create an unit test for an non-existent method in the java source.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-8.png" alt="" width="398" height="155" /></p>
<p>And now write the actual method in the java source so that the IDE doesn&#8217;t complain about the errors in our unit test.</p>
<pre class="brush: java; title: ; notranslate">

protected String sayHello(String input)
{
String output = &quot;Hello &quot; + input;
return output;
}
</pre>
<p>Go back to the unit test and run it.(I usually type CTRL + F6 to run the unit tests). Congrats! Your Maven project is seriously ready for prime time.</p>
<p>Do not take me wrong but it&#8217;s really a good practice to write unit tests for everything and that&#8217;s why I bothered you with this stuff.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-9.png" alt="" width="396" height="107" /></p>
<p><strong>Don&#8217;t use System.out.println!<br />
</strong></p>
<p>Though we are already familiar with dependencies, we only used JUnit which is a test dependency. And this is a good time to dive into the dependency hell by introducing our next dependency to this little project, &#8220;slf4j&#8221; or &#8220;Simple Logging Facade for Java&#8221;.</p>
<p>It&#8217;s hard to imagine any project without &#8220;logging&#8221; and our example project is no exception. (Heck, what&#8217;s there to log in this project???)</p>
<p>And with &#8220;slf4j&#8221; gaining wide spread adoption, let us make use of it. &#8220;slf4j&#8221; doesn&#8217;t tie our application to any logging framework (other than itself <img src='http://solitarygeek.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> ). It&#8217;s something like &#8220;jpa&#8221;. It gives you the freedom to choose your own logging provider. (My current favourite is logback)</p>
<p>Enough talking, let us starting using logging in our project.</p>
<p>To justify the use of logging, let us create some opportunity by updating our &#8220;main&#8221; method.</p>
<pre class="brush: java; title: ; notranslate">

public static void main(String[] args)
{
if(args != null &amp;&amp; args.length &gt; 0)
{
System.out.println(new App().sayHello(args[0]));
}else{
System.out.println(&quot;You have to pass atleast one argument to get a warm response from me!&quot;);
}
}
</pre>
<p>Time to fix those &#8220;System.out.println&#8221; calls by using slf4j. Create a slf4j Logger instance.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-10.png" alt="" width="652" height="23" /></p>
<p>That&#8217;s obvious. By no way the IDE can figure out what is happening here apart from resolving the &#8220;Logger&#8221; to java.util.logging which is not our objective.</p>
<p>Now click the edison&#8217;s bulb in the gutter to see what magic the IDE has under it&#8217;s hat.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-11.png" alt="" width="650" height="167" /></p>
<p>Select the option &#8220;Search Dependency at Maven Repositories&#8230;&#8221;. The IDE should popup a window with the possible matching artifacts.</p>
<p>Scroll to the bottom and locate &#8220;slf4j-api&#8221; and click &#8220;Add&#8221;. This will add the latest version of slf4j-api as a dependency. If you want to be more specific on the version, you can expand the slf4j-api node and choose the appropriate version.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-12.png" alt="" width="456" height="396" /></p>
<p>Go back to your &#8220;pom.xml&#8221; and see a new dependency for &#8220;slf4j-api&#8221; has been added. If you don&#8217;t want all this hassle, you can straight away add the following snippet in your pom.xml to add a dependency for slf4j-api.</p>
<pre class="brush: xml; title: ; notranslate">

&lt;dependency&gt;
&lt;groupId&gt;org.slf4j&lt;/groupId&gt;
&lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
&lt;version&gt;1.6.1&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;/dependency&gt;
</pre>
<p>Fix your imports in the source file and you are set to use slf4j.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-13.png" alt="" width="636" height="207" /></p>
<p>Now change the reference to &#8220;System.out.println&#8221; with appropriate logging calls.</p>
<pre class="brush: java; title: ; notranslate">

public static void main(String[] args)
{
if(args != null &amp;&amp; args.length &gt; 0)
{
logger.info(new App().sayHello(args[0]));
}else{
logger.warn(&quot;You have to pass atleast one argument to get a warm response from me!&quot;);
}
}
</pre>
<p>Run your main class to ensure that everything is fine.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/Screenshot-14.png" alt="" /></p>
<p>That&#8217;s not we expected. Nothing is logged! There is nothing wrong with this phenomenon as we haven&#8217;t defined any logging provider yet. Remember, slf4j is just a specification.</p>
<p>Okay, it&#8217;s time to add a logging provider and with all the bias let us choose &#8220;logback&#8221; for this purpose. (Please feel free to use your preferred logging provider.)</p>
<p>Slf4j has a bunch of adapters for popular logging frameworks like &#8220;log4j&#8221; and &#8220;jul&#8221; (java.util.logging). (Please don&#8217;t raise flame wars by asking whether &#8220;jul&#8221; is really popular!)</p>
<p>If log4j is your cup of tea or coffee, please go ahead and check the slf4j manuals for further reference. <img src='http://solitarygeek.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>I&#8217;ll use &#8220;logback&#8221; for this example and let us add the dependencies for that now. Right click the &#8220;Libraries&#8221; node of your project and click &#8220;Add Dependency&#8221;.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-15.png" alt="" width="454" height="318" /></p>
<p>The IDE should popup a window now where you can search the dependencies you want to add by typing the respective name in the &#8220;Query&#8221; field.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-16.png" alt="" width="516" height="553" /></p>
<p>To use logback in your project, you need to add the dependency &#8220;logback-classic&#8221;. (This will automatically add the transitive dependency &#8220;logback-core&#8221;)</p>
<p>Expand the respective node, choose the version you want and click &#8220;OK&#8221; to add them to the project.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-17.png" alt="" width="516" height="553" /></p>
<p>You can see the added dependencies in the &#8220;Libraries&#8221; node of the project.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-18.png" alt="" width="266" height="285" /></p>
<p>Again, if you are not a big fan of wizards, you can drop in the following snippet in the pom.xml straight away.</p>
<pre class="brush: xml; title: ; notranslate">

&lt;dependency&gt;
&lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
&lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
&lt;version&gt;0.9.24&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>That&#8217;s it. If you run the main class now, the logging calls should be negotiated properly.</p>
<p><img src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/screenshot-20.png" alt="" /></p>
<p>To remove a dependency, you can either right click the respective dependency in the &#8220;Libraries&#8221; node and then click &#8220;Remove dependency&#8221; or edit your pom.xml and delete the respective reference to the dependency. It&#8217;s upto you.</p>
<p>To keep this post live up to it&#8217;s title, I&#8217;ll not discuss the tons of other Maven related stuffs NetBeans has. I&#8217;ll probably cover some of them in a later post.</p>
<p>For the sake of completeness, here is the final pom.xml:</p>
<pre class="brush: xml; title: ; notranslate">

&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;

&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;examples.maven&lt;/groupId&gt;
&lt;artifactId&gt;hellomaven&lt;/artifactId&gt;
&lt;packaging&gt;jar&lt;/packaging&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
&lt;name&gt;hellomaven&lt;/name&gt;
&lt;url&gt;http://maven.apache.org&lt;/url&gt;

&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;4.8.1&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
&lt;groupId&gt;org.slf4j&lt;/groupId&gt;
&lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
&lt;version&gt;1.6.1&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
&lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
&lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
&lt;version&gt;0.9.24&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;

&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;source&gt;1.6&lt;/source&gt;
&lt;target&gt;1.6&lt;/target&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;

&lt;/project&gt;
</pre>
<p>And the java source file:</p>
<pre class="brush: java; title: ; notranslate">

package examples.maven.hellomaven;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Hello world!
*
*/
public class App
{
private static final Logger logger = LoggerFactory.getLogger(App.class);

public static void main(String[] args)
{
if(args != null &amp;&amp; args.length &gt; 0)
{
logger.info(new App().sayHello(args[0]));
}else{
logger.warn(&quot;You have to pass atleast one argument to get a warm response from me!&quot;);
}
}

protected String sayHello(String input)
{
String output = &quot;Hello &quot; + input;
return output;
}
}
</pre>
<p>The Junit test class:</p>
<pre class="brush: java; title: ; notranslate">
package examples.maven.hellomaven;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author james
 */
public class AppTest
{
 public AppTest()
 {
 }

 @Test
 public void testSayHello()
 {
 App app = new App();
 String input = &quot;Maven&quot;;
 String expected = &quot;Hello &quot; + input;
 String result = app.sayHello(input);
 assertEquals(expected, result);
 }
}
</pre>
<p>As you have seen above, NetBeans offers great support out-of-the-box for  Maven. No plugins required. If you are not a NetBeans user but use  Maven, I recommend you to give it a try. You&#8217;ll not be disappointed.</p>
<p>Thanks for reading patiently and please leave your comments if you have any.</p>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/java/netbeans-and-maven-a-quick-start-guide/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Book Review: NetBeans Platform 6.9 Developers Guide</title>
		<link>http://solitarygeek.com/netbeans/book-review-netbeans-platform-6-9-developers-guide</link>
		<comments>http://solitarygeek.com/netbeans/book-review-netbeans-platform-6-9-developers-guide#comments</comments>
		<pubDate>Fri, 10 Sep 2010 09:26:02 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[book]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[netbeans platform]]></category>
		<category><![CDATA[rcp]]></category>
		<category><![CDATA[review]]></category>
		<category><![CDATA[swing]]></category>

		<guid isPermaLink="false">http://solitarygeek.com/?p=536</guid>
		<description><![CDATA[<p>NetBeans has been my IDE of choice for the past few years and to my pleasure, I recently received a copy of NetBeans Platform 6.9 Developers Guide from Packt. So, I thought of coming out with a review of this book.</p> <p></p> <p>A bit about the NetBeans Platform</p> <p>&#8220;The NetBeans Platform is a generic framework for Swing applications. It provides the &#8220;plumbing&#8221; that, before, every developer had to write themselves—saving state, connecting actions to menu items, toolbar items and keyboard shortcuts; window management, and so on. The NetBeans Platform provides all of these out of the box. You don&#8217;t need <span style="color:#777"> . . . &#8594; Read More: <a href="http://solitarygeek.com/netbeans/book-review-netbeans-platform-6-9-developers-guide">Book Review: NetBeans Platform 6.9 Developers Guide</a></span>]]></description>
			<content:encoded><![CDATA[<p>NetBeans has been my <a href="../../category/java/netbeans-java">IDE of choice</a> for the past few years and to my pleasure, I recently received a copy of <a href="http://bit.ly/cLBtb2">NetBeans Platform 6.9 Developers Guide</a> from <a href="http://www.packtpub.com/">Packt</a>. So, I thought of coming out with a review of this book.</p>
<p><a href="https://www.packtpub.com/netbeans-platform-6-9-developers-guide/book?utm_source=jamesselvakumar.wordpress.com&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_004524"><img class="alignnone" title="NetBeans 6.9 Platform Developer's Guide" src="https://www.packtpub.com/sites/default/files/imagecache/productview/bookimages/1766_MockupCover_0.jpg" alt="NetBeans 6.9 Platform Developer's Guide" width="125" height="152" /></a></p>
<p><strong>A bit about the NetBeans Platform</strong></p>
<p>&#8220;<em>The NetBeans Platform is a generic framework for Swing applications.             It provides the &#8220;plumbing&#8221; that, before, every developer             had to write themselves—saving state, connecting             actions to menu items, toolbar items and keyboard shortcuts;  window             management, and so on. The NetBeans Platform             provides all of these out of the box. You don&#8217;t need             to manually code these or other basic features, yourself, anymore.</em>&#8221; &#8211; from the <a href="http://netbeans.org/features/platform/index.html">NetBeans Platform site</a>.</p>
<p><a href="http://platform.netbeans.org/"><img class="alignnone" title="NetBeans Platform" src="http://netbeans.org/images_www/collateral/69/netbeans-ide-110x32.png" alt="NetBeans Platform" width="110" height="32" /></a></p>
<p>And from Boeing to governments, <a href="http://netbeans.org/features/platform/showcase.html">lot of applications</a> are being built on top of the NetBeans platform.</p>
<p><strong>Do I need a technical book to learn about the NetBeans Platform?</strong></p>
<p>Though the <a href="http://netbeans.org/features/platform/index.html">NetBeans Platform</a> has a <a href="http://netbeans.org/features/platform/all-docs.html">rich set of online documentation</a>, readers&#8217; taste can differ and books are great at delivering the right content to the right audience.</p>
<p>Some might prefer a book to get started with a particular topic, some might want to read a book with in-depth technical content.</p>
<p>And it&#8217;s great to see <a href="http://netbeans.org/books/rcp.html">more</a> and <a href="http://www.amazon.com/Definitive-Guide-NetBeans-trade-Platform/dp/1430224177/ref=pd_bxgy_b_text_b">more</a> books are targeted at the NetBeans Platform.</p>
<p><strong>Who can benefit from this book?</strong></p>
<p>Are you planning to develop any desktop application? Why not develop your application on top of the NetBeans Platform, which gives you a <a href="http://netbeans.org/features/platform/features.html">lot of must have features</a> in every desktop application? Why re-invent the wheel?</p>
<p>Even if you have an existing desktop application, it&#8217;s a great idea to port it to NetBeans Platform. Just remember the &#8220;DRY&#8221; (Don&#8217;t repeat yourself) principle.</p>
<p>Do you use the NetBeans IDE to create web or mobile applications but miss your favourite feature in the IDE? Why not write some plugins yourself?</p>
<p>What ever may be your case, this book can give you a good start at NetBeans Platform.</p>
<p><strong>What&#8217;s so special about this book?</strong></p>
<p>As I started reading a couple of chapters, I got impressed with the way the content is delivered.</p>
<p>The book starts with the traditional &#8220;Hello World&#8221; module and takes the reader to the advanced topics in an elegant and seamless manner.<br />
The author makes good use of screenshots which will help the beginners a lot.</p>
<p>Like many other popular titles, this book takes an application (in this case, a Task Manager) and attempts to build it through every chapter.<br />
This undoubtedly will help the readers master the platform concepts quickly.</p>
<p><a href="http://solitarygeek.com/blog/wp-content/uploads/2010/09/book.png"><img class="alignnone size-full wp-image-538" title="book" src="http://solitarygeek.com/blog/wp-content/uploads/2010/09/book.png" alt="" width="737" height="577" /></a></p>
<p>Right from the basic form components, the book covers virtually every aspect of the NetBeans Platform like the Window System, Data System, Branding etc.<br />
There&#8217;s even an chapter to help you create installers for your application.</p>
<p>The most noticeable feature I found in this book is the friendly language and the clear explanation of topics having beginners in mind.<br />
I haven&#8217;t finished reading all the chapters yet, but I hope to complete it shortly. My objective is to write a couple of plugins for the <a href="http://netbeans.org/features/index.html">NetBeans IDE</a> and I hope this book will help me achieve that pretty quickly.</p>
<p>You can get this book from <a href="http://bit.ly/9kUklw">Packt</a> and <a href="http://www.amazon.com/NetBeans-Platform-6-9-Developers-Guide/dp/1849511764">Amazon</a>.</p>
<p><a href="https://www.packtpub.com/netbeans-platform-6-9-developers-guide/book?utm_source=jamesselvakumar.wordpress.com&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_004524"><img title="NetBeans 6.9 Platform Developer's Guide" src="https://www.packtpub.com/sites/default/files/imagecache/productview/bookimages/1766_MockupCover_0.jpg" alt="NetBeans 6.9 Platform Developer's Guide" width="125" height="152" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/netbeans/book-review-netbeans-platform-6-9-developers-guide/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Switched the hosting provider</title>
		<link>http://solitarygeek.com/general/switched-the-hosting-provider</link>
		<comments>http://solitarygeek.com/general/switched-the-hosting-provider#comments</comments>
		<pubDate>Mon, 28 Jun 2010 03:45:15 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://solitarygeek.com/?p=532</guid>
		<description><![CDATA[<p>Dear readers, Thanks for your patience. I&#8217;ve successfully moved my blog from my old hosting provider.</p> <p>Still something might be broken. I&#8217;m working them out one by one. Thanks for your support.</p> ]]></description>
			<content:encoded><![CDATA[<p>Dear readers,<br />
Thanks for your patience. I&#8217;ve successfully moved my blog from my old hosting provider.</p>
<p>Still something might be broken. I&#8217;m working them out one by one. Thanks for your support.</p>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/general/switched-the-hosting-provider/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Changing the hosting provider</title>
		<link>http://solitarygeek.com/uncategorized/hello-world</link>
		<comments>http://solitarygeek.com/uncategorized/hello-world#comments</comments>
		<pubDate>Fri, 25 Jun 2010 01:49:33 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://solitarygeek.com/blog/?p=1</guid>
		<description><![CDATA[<p>Dear readers,</p> <p>Sorry for the down time. I&#8217;m in the process of changing to a different hosting provider. The blog should be up in a couple of days. </p> ]]></description>
			<content:encoded><![CDATA[<p>Dear readers,</p>
<p>Sorry for the down time. I&#8217;m in the process of changing to a different hosting provider. The blog should be up in a couple of days. <img src='http://solitarygeek.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/uncategorized/hello-world/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Windows 7 RC Expiration</title>
		<link>http://solitarygeek.com/general/windows-7-rc-expiration</link>
		<comments>http://solitarygeek.com/general/windows-7-rc-expiration#comments</comments>
		<pubDate>Wed, 17 Feb 2010 02:01:59 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.solitarygeek.com/?p=525</guid>
		<description><![CDATA[<p>I received a mail from Microsoft today morning about Windows 7 expiration. Here is the essence of the mail:</p> <p>It’s time to upgrade from the Windows 7 Release Candidate</p> <p>While most people who tested Windows 7 have now moved to the final version, some are still running the Release Candidate. If you haven’t moved yet, it’s time to replace the RC.</p> <p>Starting on March 1, 2010 your PC will begin shutting down every two hours. Your work will not be saved during the shutdown.</p> <p>The Windows 7 RC will fully expire on June 1, 2010. Your PC running the Windows <span style="color:#777"> . . . &#8594; Read More: <a href="http://solitarygeek.com/general/windows-7-rc-expiration">Windows 7 RC Expiration</a></span>]]></description>
			<content:encoded><![CDATA[<p>I received a mail from Microsoft today morning about Windows 7 expiration. Here is the essence of the mail:</p>
<p><em><strong>It’s time to upgrade from the Windows 7 Release Candidate</strong></em></p>
<p><em>While most people who tested Windows 7 have now moved to the final version, some are still running the Release Candidate. If you haven’t moved yet, it’s time to replace the RC.</em></p>
<p><em>Starting on March 1, 2010 your PC will begin shutting down every two hours. Your work will not be saved during the shutdown.</em></p>
<p><em>The Windows 7 RC will fully expire on June 1, 2010. Your PC running the Windows 7 RC will continue shutting down every two hours and your files won’t be saved during shutdown. In addition, your wallpaper will change to a solid black background with a persistent message on your desktop. You’ll also get periodic notifications that Windows isn’t genuine. That means your PC may no longer be able to obtain optional updates or downloads requiring genuine Windows validation.</em></p>
<p><em>To avoid interruption, please reinstall a prior version of Windows or move to Windows 7. In either case, you’ll need to do a custom (clean) install to replace the RC. As with any clean installation, you’ll need to back up your data then reinstall your applications and restore the data. For more details about replacing the RC, see the Knowledge Base article KB 971767. For more information, visit the Window 7 Forum.</em></p>
<p><em>Thanks again for helping us test Windows 7.</em></p>
<p><em>The Windows 7 Team</em></p>
<p>This sounds very unprofessional and disappointing. Why shutdown the operating system every 2 hours? Why change the wall paper to &#8220;a solid black background with a persistent message on your desktop&#8221;?. Why display &#8220;periodic notifications that Windows isn’t genuine&#8221;?. Did we cheat Microsoft by running Windows 7 RC? Why not just expire gracefully with some friendly reminders.</p>
<p>What do you think about this?</p>
<p>You can get more information about Windows 7 RC expiration from <a href="http://support.microsoft.com/kb/971767">Microsoft Knowledge Base</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/general/windows-7-rc-expiration/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What Java Look and Feel do you use?</title>
		<link>http://solitarygeek.com/java/what-java-look-and-feel-do-you-use</link>
		<comments>http://solitarygeek.com/java/what-java-look-and-feel-do-you-use#comments</comments>
		<pubDate>Mon, 09 Nov 2009 15:10:32 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Polls]]></category>
		<category><![CDATA[look and feel]]></category>
		<category><![CDATA[swing]]></category>
		<category><![CDATA[themes]]></category>

		<guid isPermaLink="false">http://www.solitarygeek.com/?p=519</guid>
		<description><![CDATA[<p>Quite some time back, I read an article titled &#8220;20+ Free Look and Feel Libraries For Java Swing&#8220;. I have evaluated most of the libraries mentioned in that article. Personally, I  prefer the System look and feel that is bundled in the JRE. However, I like Substance, PGS and JGoodies as well. Which one do you use? Curious to know.</p> Note: There is a poll embedded within this post, please visit the site to participate in this post's poll. ]]></description>
			<content:encoded><![CDATA[<p>Quite some time back, I read an article titled &#8220;<a href="http://javabyexample.wisdomplug.com/web-programming/37-core-java/65-20-free-look-and-feel-libraries-for-java-swings.html">20+ Free Look and Feel Libraries For Java Swing</a>&#8220;. I have evaluated most of the libraries mentioned in that article. Personally, I  prefer the System look and feel that is bundled in the JRE. However, I like Substance, PGS and JGoodies as well. Which one do you use? Curious to know.</p>
Note: There is a poll embedded within this post, please visit the site to participate in this post's poll.
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/java/what-java-look-and-feel-do-you-use/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Developing A Simple Java Application With Spring</title>
		<link>http://solitarygeek.com/java/developing-a-simple-java-application-with-spring</link>
		<comments>http://solitarygeek.com/java/developing-a-simple-java-application-with-spring#comments</comments>
		<pubDate>Tue, 03 Nov 2009 16:12:23 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.solitarygeek.com/java/java-spring/</guid>
		<description><![CDATA[<p>Introduction Spring is a powerful application framework that can be used across any layer in your application. For example, you can use Spring to manage only your data access layer or you can use Spring to provide remote services for your swing client. In this article, I will explain how to get started with Spring by developing a simple java application.</p> <p>Requirements 1. Your favorite IDE 2. Latest Spring framework.</p> <p>(Note: This article makes use of Spring framework 2.5.6 which is the current production release)</p> <p>The Application We are going to develop a simple application that fetches and display the <span style="color:#777"> . . . &#8594; Read More: <a href="http://solitarygeek.com/java/developing-a-simple-java-application-with-spring">Developing A Simple Java Application With Spring</a></span>]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong><br />
Spring is a powerful application framework that can be used across any layer in your application. For example, you can use Spring to manage only your data access layer or you can use Spring to provide remote services for your swing client. In this article, I will explain how to get started with Spring by developing a simple java application.</p>
<p><strong>Requirements</strong><br />
1. Your favorite IDE<br />
2. <a href="http://www.springsource.org/download">Latest Spring framework</a>.</p>
<p>(Note: This article makes use of Spring framework 2.5.6 which is the current production release)</p>
<p><strong>The Application</strong><br />
We are going to develop a simple application that fetches and display the list of registered users. The application consists of just two interfaces, their implementation.</p>
<p><strong>The DAO layer</strong><br />
Let us now develop the DAO layer of the application. This layer consists of just one interface &#8220;UserDao&#8221; and it&#8217;s implementation &#8220;UserDaoImpl&#8221;. The interface consists of just one method named &#8220;getUsers()&#8221;. Let us quickly develop them.</p>
<p>Listing 1. UserDao</p>
<pre class="brush: java; title: ; notranslate">
package com.springapp.dao;
import java.util.Iterator;

/**
 *
 * @author James
 */
public interface UserDao
{
    Iterator&lt;String&gt; getUsers();
}
</pre>
<p>Listing 2. UserDaoImpl</p>
<pre class="brush: java; title: ; notranslate">

package com.springapp.dao;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author James
 */
public class UserDaoImpl implements UserDao
{
    public Iterator&lt;String&gt; getUsers()
    {
        List&lt;String&gt; users = new ArrayList&lt;String&gt;();
        users.add(&quot;Gavin King&quot;);
        users.add(&quot;Geertjan&quot;);
        users.add(&quot;Mike Keith&quot;);
        users.add(&quot;James&quot;);
        return users.iterator();
    }
}
</pre>
<p>Nothing fancy here. The implementation is pretty straight forward, though in a real environment you might fetch those details from the database using ORM frameworks like JPA.</p>
<p><strong>The Service Layer</strong></p>
<p>We will encapsulate the service layer from the dao implementaion by writing code against the interface UserDao. We will follow the same pattern we used in developing the dao layer and write the interface UserService and it&#8217;s implementation UserServiceImpl.</p>
<p>Listing 3. UserService</p>
<pre class="brush: java; title: ; notranslate">

package com.springapp.service;

import java.util.Iterator;

/**
 *
 * @author James
 */
public interface UserService
{
    Iterator&lt;String&gt; getUsers();
}
</pre>
<p>Listing 4. UserServiceImpl</p>
<pre class="brush: java; title: ; notranslate">

package com.springapp.service;

import com.springapp.dao.UserDao;
import java.util.Iterator;

/**
 *
 * @author James
 */
public class UserServiceImpl implements UserService
{
    private UserDao userDao;

    public Iterator&lt;String&gt; getUsers()
    {
        return userDao.getUsers();
    }

    public void setUserDao(UserDao userDao)
    {
        this.userDao = userDao;
    }
}
</pre>
<p>Kindly notice that both the service layer classes and dao layer classes are Spring agnostic. That&#8217;s the beauty of Spring. Spring is less invasive. Most of the application code can be developed without knowing anything about Spring.</p>

<p><strong>The Client</strong></p>
<p>Now we need someone to make use of our service layer and we will waste no time in developing the client for our service. We can just write a junit test class to invoke our service but I prefer to write a simple java class to be the client. Though our client will be a simple POJO class, you can easily replace it with a Swing or Web front end. Enough talking, let us dive into action! We will first develop our client as a normal java class without using Spring.</p>
<p><em>Standard Client</em></p>
<p>Listing 5. StandardUserServiceClient</p>
<pre class="brush: java; title: ; notranslate">

package com.springapp;

import com.springapp.dao.UserDao;
import com.springapp.dao.UserDaoImpl;
import com.springapp.service.UserServiceImpl;
import java.util.Iterator;

/**
 *
 * @author James
 */
public class StandardUserServiceClient
{

    private UserServiceImpl userService;

    public StandardUserServiceClient()
    {
        userService = new UserServiceImpl();
        UserDao userDao = new UserDaoImpl();
        userService.setUserDao(userDao);
    }

    private void fetchUsers()
    {
        Iterator&lt;String&gt; users = userService.getUsers();
        while (users.hasNext())
        {
            System.out.println(users.next());
        }
    }

    public static void main(String[] args)
    {
        StandardUserServiceClient client = new StandardUserServiceClient();
        client.fetchUsers();
    }
}
</pre>
<p>Hmm, there you can see our client code is &#8220;coupled&#8221; tightly with the service and dao implementations. That&#8217;s where Spring comes to our rescue. Spring will dynamically &#8220;inject&#8221; the implemenations so our application will remain &#8220;loosely&#8221; coupled.</p>
<p><em>Spring Client</em></p>
<p>But how will Spring know about our implementations? We need to inform Spring a little about our application and define the &#8220;hotspots&#8221; where it can dynamically &#8220;inject&#8221; the dependencies or implementations. Spring expects these details in a configuration file and let us quickly write that. Create a package called &#8220;resources&#8221; and create a xml file called &#8220;applicationContext.xm&#8221; inside it.</p>
<p>Listing 6. applicationContext.xml</p>
<pre class="brush: xml; title: ; notranslate">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
 xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
 xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&quot;&gt;

 &lt;bean id=&quot;userDao&quot; class=&quot;com.springapp.dao.UserDaoImpl&quot;&gt;
 &lt;/bean&gt;

 &lt;bean id=&quot;userService&quot; class=&quot;com.springapp.service.UserServiceImpl&quot;&gt;
     &lt;property name=&quot;userDao&quot; ref=&quot;userDao&quot;/&gt;
 &lt;/bean&gt;
&lt;/beans&gt;
</pre>
<p>In the &#8220;applicationContext.xml&#8221; file we defiend two beans named &#8220;userDao&#8221; and &#8220;userService&#8221;. We also specified their implementations using the &#8220;class&#8221; attribute. Also notice that we are setting the property &#8220;userDao&#8221;  in the &#8220;UserServiceImpl&#8221; class with &#8220;UserDaoImpl&#8221; by referencing it&#8217;s name &#8220;userDao&#8221;. Pretty straighforward!</p>
<p>Now it&#8217;s time to churn out our Spring client.</p>
<p>Listing 7. SpringUserServiceClient</p>
<pre class="brush: java; title: ; notranslate">

package com.springapp;

import com.springapp.service.UserService;
import java.util.Iterator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author James
 */
public class SpringUserServiceClient
{
    private UserService userService;

    public SpringUserServiceClient()
    {
        //initialize the spring container
        ApplicationContext context = new ClassPathXmlApplicationContext(&quot;resources/applicationContext.xml&quot;);
        userService = (UserService) context.getBean(&quot;userService&quot;);
    }

    private void fetchUsers()
    {
        Iterator&lt;String&gt; users = userService.getUsers();
        while(users.hasNext())
        {
            System.out.println(users.next());
        }
    }

    public static void main(String[] args)
    {
        SpringUserServiceClient client = new SpringUserServiceClient();
        client.fetchUsers();
    }
}
</pre>
<p>A couple of details about this class:</p>
<ul>
<li>The ApplicationContext interface helps us to plug into the Spring container and lookup the classes we need by using the name we defined in the xml file.</li>
<li>There are many implementataions of ApplicationContext available in Spring. One of the most widely used implementation is &#8220;ClassPathXmlApplicationContext&#8221;. It is used to load Spring configuration files found in classpath.</li>
</ul>
<p>As seen from Listing 7, Spring helps us to program to interfaces and develop loosely coupled applications. As a result, applications become more testable as there are no external dependencies like application server. It is also very easy to switch the implementations effortlessly. For example, in our sample application you can easily write a UserDaoMockImpl and use it in your test cases effortlessly.</p>
<p><strong>Project Structure</strong></p>
<p>Here is the complete application looks like:</p>
<p><strong><img class="alignnone size-full wp-image-515" title="screenshot1" src="http://solitarygeek.com/blog/wp-content/uploads/2009/11/screenshot1.png" alt="screenshot1" width="302" height="310" /><br />
</strong></p>
<div class="zemanta-pixie"><img class="zemanta-pixie-img" src="http://img.zemanta.com/pixy.gif?x-id=d7d85c06-7c20-8a72-ae33-ec6bc5f32317" alt="" /></div>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/java/developing-a-simple-java-application-with-spring/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Developing A Simple Pluggable Java Application</title>
		<link>http://solitarygeek.com/java/a-simple-pluggable-java-application</link>
		<comments>http://solitarygeek.com/java/a-simple-pluggable-java-application#comments</comments>
		<pubDate>Sun, 20 Sep 2009 15:23:12 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[pluggable]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://www.solitarygeek.com/java/a-simple-pluggable-java-application/</guid>
		<description><![CDATA[<p>Most of the applications we use on daily basis are pluggable. Popular applications like Firefox, Eclipse, NetBeans, JEdit, WordPress, Hudson are all pluggable. In fact, pluggability has played a major part in the success of most of these applications. Why not make the Java applications we develop pluggable as well? Yes, we get pluggability out of the box, if our applications are based on a rich client platform like NetBeans or Eclipse. But for some reasons if you decide not to use those platforms, it doesn&#8217;t mean that they should not be pluggable. In this article, we will learn how <span style="color:#777"> . . . &#8594; Read More: <a href="http://solitarygeek.com/java/a-simple-pluggable-java-application">Developing A Simple Pluggable Java Application</a></span>]]></description>
			<content:encoded><![CDATA[<p>Most of the applications we use on daily basis are pluggable. Popular applications like Firefox, Eclipse, NetBeans, JEdit, WordPress, Hudson are all pluggable. In fact, pluggability has played a major part in the success of most of these applications. Why not make the Java applications we develop pluggable as well? Yes, we get pluggability out of the box, if our applications are based on a rich client platform like NetBeans or Eclipse. But for some reasons if you decide not to use those platforms, it doesn&#8217;t mean that they should not be pluggable. In this article, we will learn how to write a simple pluggable application that will load it&#8217;s plugins dynamically.</p>
<p><strong>The API<br />
</strong>First, let us define a plugin interface that should be implemented by all the plugins of our application. We are going to keep it very simple. Create a project called &#8220;plugin-api&#8221; in your favorite IDE and create the interface &#8220;ApplicationPlugin&#8221;.</p>
<p><img style="max-width: 800px;" src="http://solitarygeek.com/blog/wp-content/uploads/2009/09/screenshot1-p2.png" alt="" /></p>
<pre class="brush: java; title: ; notranslate">

package com.pluggableapp.plugins.api;

public interface ApplicationPlugin
{
    String getName();
    void init();
}
</pre>
<p><span id="more-464"></span></p>
<p><strong>The Plugins</strong></p>
<p>Writing the plugins now is very easy. Our plugins need to implement the plugin interface and follow a simple convention to make it easy for our applications to find them later. Create a project called &#8220;plugin-a&#8221; and develop our first plugin.</p>
<pre class="brush: java; title: ; notranslate">

package com.pluggableapp.plugins;

import com.pluggableapp.plugins.api.ApplicationPlugin;
import java.util.logging.Logger;

public class PluginA implements ApplicationPlugin
{
    private static Logger logger = Logger.getLogger(PluginA.class.getName());

    public String getName()
    {
        return &quot;Plugin A&quot;;
    }

    public void init()
    {
        logger.info(getName() + &quot; initialized!&quot;);
    }
}
</pre>
<p>Now create a directory called &#8220;META-INF/services&#8221; inside the source directory and create a file with the name &#8220;com.pluggableapp.plugins.api.ApplicationPlugin&#8221; (This is the fully qualified name of the plugin interface). The file should contain the name of the actual plugin inside it. In our case, the text is &#8220;com.pluggableapp.plugins.PluginA&#8221;.</p>
<p><img style="max-width: 800px;" src="http://solitarygeek.com/blog/wp-content/uploads/2009/09/screenshot4-p.png" alt="" /></p>
<p>Repeat these steps to create PluginB.</p>

<p><strong>The Application</strong></p>
<p>It&#8217;s time to create the application that will consume the plugins we created. First let us create a class to add the plugin jars to the classpath dynamically.</p>
<pre class="brush: java; title: ; notranslate">

package com.pluggableapp;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.logging.Logger;

public class ClasspathUtils
{

 private static Logger logger = Logger.getLogger(ClasspathUtils.class.getName());
 // Parameters
 private static final Class[] parameters = new Class[]
 {
     URL.class
 };

 /**
 * Adds the jars in the given directory to classpath
 * @param directory
 * @throws IOException
 */
 public static void addDirToClasspath(File directory) throws IOException
 {
     if (directory.exists())
     {
         File[] files = directory.listFiles();
         for (int i = 0; i &lt; files.length; i++)
         {
             File file = files[i];
             addURL(file.toURI().toURL());
         }
     }
     else
     {
         logger.warning(&quot;The directory \&quot;&quot; + directory + &quot;\&quot; does not exist!&quot;);
     }
}

 /**
 * Add URL to CLASSPATH
 * @param u URL
 * @throws IOException IOException
 */
 public static void addURL(URL u) throws IOException
 {
     URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
     URL urls[] = sysLoader.getURLs();
     for (int i = 0; i &lt; urls.length; i++)
     {
         if (urls[i].toString().equalsIgnoreCase(u.toString()))
         {
             logger.info(&quot;URL &quot; + u + &quot; is already in the CLASSPATH&quot;);
             return;
         }
     }
     Class sysclass = URLClassLoader.class;
     try
     {
         Method method = sysclass.getDeclaredMethod(&quot;addURL&quot;, parameters);
         method.setAccessible(true);
         method.invoke(sysLoader, new Object[]
         {
             u
         });
     } catch (Throwable t)
     {
         t.printStackTrace();
         throw new IOException(&quot;Error, could not add URL to system classloader&quot;);
     }
  }
}
</pre>
<p>Now create an interface called &#8220;PluginService&#8221; to define the methods needed to load and initialize the plugins.</p>
<pre class="brush: java; title: ; notranslate">

package com.pluggableapp;

import com.pluggableapp.plugins.api.ApplicationPlugin;
import java.util.Iterator;

public interface PluginService
{
    Iterator&lt;ApplicationPlugin&gt; getPlugins();
    void initPlugins();
}
</pre>
<p>As of version 1.6, the Java runtime ships with a class called &#8220;ServiceLoader&#8221; to easily find and load plugins. Let us now write a implementation called &#8220;StandardPluginService&#8221; and make use of the facilities built into the java runtime.</p>
<pre class="brush: java; title: ; notranslate">

package com.pluggableapp;

import com.pluggableapp.PluginService;
import com.pluggableapp.plugins.api.ApplicationPlugin;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.logging.Logger;

public class StandardPluginService implements PluginService
{
    private static StandardPluginService pluginService;
    private ServiceLoader&lt;ApplicationPlugin&gt; serviceLoader;
    private Logger logger = Logger.getLogger(getClass().getName());

    private StandardPluginService()
    {
        //load all the classes in the classpath that have implemented the interface
        serviceLoader = ServiceLoader.load(ApplicationPlugin.class);
    }

    public static StandardPluginService getInstance()
    {
        if(pluginService == null)
        {
            pluginService = new StandardPluginService();
        }
        return pluginService;
    }

    public Iterator&lt;ApplicationPlugin&gt; getPlugins()
    {
        return serviceLoader.iterator();
    }

    public void initPlugins()
    {
        Iterator&lt;ApplicationPlugin&gt; iterator = getPlugins();
        if(!iterator.hasNext())
        {
            logger.info(&quot;No plugins were found!&quot;);
        }
        while(iterator.hasNext())
        {
            ApplicationPlugin plugin = iterator.next();
            logger.info(&quot;Initializing the plugin &quot; + plugin.getName());
            plugin.init();
        }
    }
}
</pre>
<p>Feel free to write your own implementation if needed. For example you can easily write an implementation based on the NetBeans API.</p>
<p>Write a factory class named &#8220;PluginServiceFactory&#8221; to create &#8220;PluginService&#8221; objects.</p>
<pre class="brush: java; title: ; notranslate">

package com.pluggableapp;

import com.pluggableapp.*;
import com.pluggableapp.StandardPluginService;
import com.pluggableapp.PluginService;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PluginServiceFactory
{
    public static PluginService createPluginService()
    {
        addPluginJarsToClasspath();
        return StandardPluginService.getInstance();
    }

    private static void addPluginJarsToClasspath()
    {
        try
        {
            //add the plugin directory to classpath
            ClasspathUtils.addDirToClasspath(new File(&quot;plugins&quot;));
        } catch (IOException ex)
        {
            Logger.getLogger(PluginServiceFactory.class.getName()).log(
                Level.SEVERE, null, ex);
        }
    }
}
</pre>
<p>That&#8217;s it. All we need to do now is to write a class that will invoke the &#8220;PluginServiceFactory&#8221;.</p>
<pre class="brush: java; title: ; notranslate">

package com.pluggableapp;

import com.pluggableapp.plugins.api.ApplicationPlugin;
import java.util.Iterator;
import java.util.logging.Logger;

public class Main
{

    private static Logger logger = Logger.getLogger(Main.class.getName());

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args)
    {
        loadPlugins();
    }

    private static void loadPlugins()
    {
        PluginService pluginService = PluginServiceFactory.createPluginService();
        pluginService.initPlugins();
    }
}
</pre>
<p>Before we build and see the application in action, create a directory called &#8220;plugins&#8221; and put all plugin jars there.</p>
<p><img style="max-width: 800px;" src="http://solitarygeek.com/blog/wp-content/uploads/2009/09/screenshot3-p1.png" alt="" /></p>
<p>And this is what you might see when you run our pluggable application.</p>
<p><img style="max-width: 800px;" src="http://solitarygeek.com/blog/wp-content/uploads/2009/09/screenshot2-p1.png" alt="" /></p>
<p>Now feel free to create as many plugins you want to write and just drop them in the &#8220;plugins&#8221; directory and restart the &#8220;pluggable&#8221; application to see your &#8220;home grown&#8221; plugins in action!</p>
<p><strong>Resources</strong></p>
<p><a href="http://java.sun.com/developer/technicalArticles/javase/extensible/index.html">Creating Extensible Applications With the Java Platform</a> &#8211; <em>John O&#8217;Conner</em></p>
<p><a href="http://twit88.com/blog/2007/10/07/develop-a-java-plugin-framework/">Developing a Java Plugin Framework </a></p>
<p><a href="http://java.dzone.com/news/how-create-pluggable-photo-alb">How to Create a Pluggable Photo Album in Java</a> &#8211; <em>Geertjan</em></p>
<div class="zemanta-pixie"><img class="zemanta-pixie-img" src="http://img.zemanta.com/pixy.gif?x-id=d7d85c06-7c20-8a72-ae33-ec6bc5f32317" alt="" /></div>
]]></content:encoded>
			<wfw:commentRss>http://solitarygeek.com/java/a-simple-pluggable-java-application/feed</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
	</channel>
</rss>

