<?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>Code Hangover &#187; java</title>
	<atom:link href="http://blog.codehangover.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.codehangover.com</link>
	<description>Go ahead, have another</description>
	<lastBuildDate>Tue, 22 Mar 2011 15:49:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Track every Build Number with Maven</title>
		<link>http://blog.codehangover.com/track-every-build-number-with-maven/</link>
		<comments>http://blog.codehangover.com/track-every-build-number-with-maven/#comments</comments>
		<pubDate>Sat, 09 Oct 2010 16:42:54 +0000</pubDate>
		<dc:creator>MikeNereson</dc:creator>
				<category><![CDATA[Software Tools]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[build number]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=584</guid>
		<description><![CDATA[Need to differentiate between build numbers? Let Maven do the work for you.]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/track-every-build-number-with-maven/";</script><h4>Problem</h4>
<p>You need to differentiate between build numbers. For example, you&#8217;ve just redeployed your application and need to ensure that the new version is what you are viewing. Or, you need to keep track of how many times you build. There could be many reasons why you want to know the build number that you are on. I use it for reporting bugs against specific builds.</p>
<h4>Solution</h4>
<p><code>maven-buildnumber-plugin</code>. This Maven2 plugin will generate a unique build number each time your build your project. You can even configure which maven phase triggers the increment of the number. This plugin can also fetch data from SVN to ensure that a team of developers all get unique build numbers.</p>
<p>As a bonus, it generates a buildNumber.properties file so that you can read in this build number from anywhere in your project. Here is how I use the plugin.</p>
<p>First, update your <code>pom.xml</code>. You need to setup the build trigger.</p>
<pre class="brush: xml;">

&lt;build&gt;
  &lt;plugins&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
      &lt;artifactId&gt;buildnumber-maven-plugin&lt;/artifactId&gt;
      &lt;version&gt;1.0-beta-3&lt;/version&gt;
      &lt;executions&gt;
        &lt;execution&gt;
          &lt;phase&gt;validate&lt;/phase&gt;
          &lt;goals&gt;
            &lt;goal&gt;create&lt;/goal&gt;
          &lt;/goals&gt;
        &lt;/execution&gt;
      &lt;/executions&gt;
      &lt;configuration&gt;
        &lt;doCheck&gt;true&lt;/doCheck&gt;
        &lt;doUpdate&gt;false&lt;/doUpdate&gt;
        &lt;format&gt;${version}.{0,number}&lt;/format&gt;
        &lt;items&gt;
          &lt;item&gt;buildNumber0&lt;/item&gt;
        &lt;/items&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
  &lt;/plugins&gt;
&lt;/build&gt;
</pre>
<p>Now, you&#8217;ll need the build number and append it to your artifact&#8217;s final name. Add this to your <code>pom.xml</code></p>
<pre class="brush: xml;">
&lt;build&gt;
  &lt;finalName&gt;
    ${project.artifactId}-${project.version}.{buildNumber}
  &lt;/finalName&gt;
&lt;/build&gt;
</pre>
<p>Now you&#8217;re package goal will output a file named</p>
<p><code>projectname-1.0.1.war</code></p>
<p>This is a great start and now you can differentiate each and every build. However, I need to take this a step further.</p>
<p>I need to see the version on my application&#8217;s index page. To do this, I use an ant filter to write the version and timestamp to a version.html file, and then copy it to my project&#8217; web app directory.  Add this to your <code>pom.xm</code>.</p>
<pre class="brush: xml;">
&lt;build&gt;
  &lt;plugins&gt;
    &lt;plugin&gt;
      &lt;artifactId&gt;maven-antrun-plugin&lt;/artifactId&gt;
      &lt;executions&gt;
        &lt;execution&gt;
          &lt;phase&gt;compile&lt;/phase&gt;
          &lt;configuration&gt;
            &lt;tasks&gt;
              &lt;!-- versioning --&gt;
              &lt;echo message=&quot;[build version]&quot;/&gt;
              &lt;delete file=&quot;target/projectname/version.html&quot;/&gt;
              &lt;tstamp&gt;
                &lt;format property=&quot;rightNow&quot; pattern=&quot;d MMM yyyy&quot; locale=&quot;en&quot;/&gt;
              &lt;/tstamp&gt;
              &lt;copy todir=&quot;target/projectname&quot;&gt;
                &lt;fileset dir=&quot;src/main/webapp&quot;&gt;
                  &lt;include name=&quot;version.html&quot;/&gt;
                &lt;/fileset&gt;
                &lt;filterset&gt;
                  &lt;filter token=&quot;VERSION&quot; value=&quot;${buildNumber}&quot;/&gt;
                  &lt;filter token=&quot;BUILTON&quot; value=&quot;${rightNow}&quot;/&gt;
                &lt;/filterset&gt;
              &lt;/copy&gt;
              &lt;echo message=&quot; version is ${buildNumber}&quot;/&gt;
            &lt;/tasks&gt;
          &lt;/configuration&gt;
          &lt;goals&gt;
            &lt;goal&gt;run&lt;/goal&gt;
          &lt;/goals&gt;
        &lt;/execution&gt;
      &lt;/executions&gt;
    &lt;/plugin&gt;
  &lt;/plugins&gt;
&lt;/build&gt;
</pre>
<p><code>Version.html</code> is simple.</p>
<pre class="brush: xml;">
&lt;p class=&quot;version&quot;&gt;Version: @VERSION@&lt;/p&gt;
&lt;p class=&quot;built&quot;&gt;Built on: @BUILTON@&lt;/p&gt;
</pre>
<p>Finally, in my index page&#8230;</p>
<pre class="brush: xml;">
&lt;jsp:include page=&quot;/version.html&quot;/&gt;
</pre>
<p>Almost everything you want to know about this plugin can be found on the plugin&#8217;s site: <a href="http://mojo.codehaus.org/buildnumber-maven-plugin/">http://mojo.codehaus.org/buildnumber-maven-plugin/</a></p>
<h4>Alternatives</h4>
<p>As an alternative to writing and importing <code>version.html</code>, you can read <code>buildNumber.properties</code> in an MVC controller and put the version in your page model. This is what I for my login pages. I use a java class to read the build number, format it, and cache it. I start the first build number at <code>00100</code>, then format that to <code>0.1.0</code>. So the next build is <code>00101</code> which gets displayed as <code>0.1.1</code>.</p>
<h4>Update:Tips</h4>
<p>Here is a usage tip. You can move the create goal into a build profile so that the build number only increments in specific situations. I use a profile for my Continuous Integration builds so that our version increments only when Hudson builds our apps. This also makes it possible to synchronize our Hudson build numbers to our module versions.</p>
<h4>Feedback</h4>
<p>What do you use to track build numbers? How do your format it?<br />
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/new-and-unknown-java-libraries/" title="New and Unknown Java Libraries">New and Unknown Java Libraries</a></li>
<li><a href="http://blog.codehangover.com/propertyplaceholderconfigurer-with-default-values/" title="PropertyPlaceholderConfigurer with Default Values">PropertyPlaceholderConfigurer with Default Values</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Ftrack-every-build-number-with-maven%2F&amp;linkname=Track%20every%20Build%20Number%20with%20Maven"><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/track-every-build-number-with-maven/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Strange Loop 2009 &#8211; Day 2</title>
		<link>http://blog.codehangover.com/strange-loop-2009-day-2/</link>
		<comments>http://blog.codehangover.com/strange-loop-2009-day-2/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 23:09:53 +0000</pubDate>
		<dc:creator>Welzie</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[polyglot]]></category>
		<category><![CDATA[strange loop]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=482</guid>
		<description><![CDATA[My notes and thoughts about day two of strange loop 2009.]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/strange-loop-2009-day-2/";</script><p>My notes and thoughts about day two of <a href="http://thestrangeloop.com/">strange loop 2009</a>.</p>
<p>Also be sure to check out my <a href="http://blog.codehangover.com/strange-loop-2009-day-1/">Day one notes.</a></p>
<h4>jQuery &#8211; Matt Taylor</h4>
<ul>
<li><a href="http://weblog.dangertree.net/">http://weblog.dangertree.net/</a></li>
<li>Showed numerous examples how easy jQuery makes it to select and edit HTML elements. Made me realize I should use jQuery even in small apps.</li>
<li>Also showed examples of the jQuery AJAX functionality</li>
</ul>
<h4>Mobile Development 101</h4>
<ul>
<li><a href="http://www.slideshare.net/michael.galpin">http://www.slideshare.net/michael.galpin</a></li>
<li><a href="http://fupeg.blogspot.com/">http://fupeg.blogspot.com/</a></li>
<li>This session was full which doesn&#8217;t surprise me since mobile development is about to get easier thanks to Android.</li>
<li>Started off going how to develop apps for the iPhone
<ul>
<li>The emulator and development software only run on a Mac</li>
<li>Has to be written in Objective C
<ul>
<li>I wanted to throw up when I saw the <a href="http://en.wikipedia.org/wiki/Objective-C">objective c</a> examples</li>
<li>No garbage collection. Memory is limited on phones so this is an important issue.</li>
<li>Maybe I&#8217;m just to much of a simpleton, but I really don&#8217;t ever want to write any objective C</li>
</ul>
</li>
<li>MVC framework &#8211; cocoa touch</li>
<li>No background processing on iphone</li>
</ul>
</li>
<li>Android
<ul>
<li>Can run any language that is built on the JVM</li>
<li>XML format for UI develoment</li>
<li>Does not use standard MVC pattern.  Uses something called <a href="http://developer.android.com/guide/topics/fundamentals.html#acttask">Activities </a>and <a href="http://developer.android.com/guide/topics/fundamentals.html#ifilters">Intents</a>.</li>
<li>There are multiple android emulators</li>
</ul>
</li>
<li>Mobile dev best practices (not specific to android or iphone)
<ul>
<li>Need lean web services</li>
<li>Limit network traffic</li>
<li>Limit audio/video/images</li>
</ul>
</li>
<li>Mobile Web Application
<ul>
<li>Alternative to writing an iPhone/Android app</li>
<li>A lot of phones have the same browser now</li>
<li>Some mobile browsers leak memory</li>
</ul>
</li>
</ul>
<h4>Entrepreneur Talk &#8211; Panel Discussion</h4>
<ul>
<li>This book was mentioned, <a href="http://www.amazon.com/gp/product/0316017922?ie=UTF8&#038;tag=1410softwarec-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=0316017922">Outliers: The Story of Success</a> </li>
<li>Someone said that you need irrational arrogance to start your own company.</li>
<li>Another person said that start ups are all offense and no defense.  Just keep putting stuff out, early and often</li>
<li>The idea was presented that everyone has risk even the person working for a company because you can be fired at any time</li>
<li>The current work culture is sort of like having one client at a time because developers change jobs so often.</li>
</ul>
<h4>Polyglot Grails &#8211; Jeff Brown</h4>
<ul>
<li><a href="http://www.nofluffjuststuff.com/conference/speaker/jeff_brown">http://www.nofluffjuststuff.com/conference/speaker/jeff_brown</a></li>
<li><a href="http://javajeff.blogspot.com/">http://javajeff.blogspot.com/</a></li>
<li>You can use many languages with Grails.  Jeff even gave an example of Grails with a simple language he created</li>
<li>methodMissing(string name, args) is a very interesting feature of Groovy</li>
</ul>
<h4>Minimalism &#8211; Alex Payne</h4>
<ul>
<li><a href="http://twitter.com/Al3X">http://twitter.com/Al3X</a></li>
<li><a>http://al3x.net/books_talks.html</a></li>
<li>Interesting talk about little m minimalism and how it be applied to code</li>
<li>Alex made a few comments about how programming is a young field</li>
</ul>
<p><a href="http://thestrangeloop.com/sessions/slides">List of slides on strangeloop.com</a><br />
<a href="http://thestrangeloop.com/sessions">Day two sessions<br />
<img style="border: none;" src="http://img18.imageshack.us/img18/6359/strangeloop2.gif" alt="" /></a><br />
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/strange-loop-2009-day-1/" title="Strange Loop 2009 &#8211; Day 1">Strange Loop 2009 &#8211; Day 1</a></li>
<li><a href="http://blog.codehangover.com/strange-loop-2010-early-bird-registration/" title="Strange Loop 2010 &#8211; Early Bird Registration">Strange Loop 2010 &#8211; Early Bird Registration</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Fstrange-loop-2009-day-2%2F&amp;linkname=Strange%20Loop%202009%20%26%238211%3B%20Day%202"><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/strange-loop-2009-day-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Strange Loop 2009 &#8211; Day 1</title>
		<link>http://blog.codehangover.com/strange-loop-2009-day-1/</link>
		<comments>http://blog.codehangover.com/strange-loop-2009-day-1/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 05:27:56 +0000</pubDate>
		<dc:creator>Welzie</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[polyglot]]></category>
		<category><![CDATA[strange loop]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=463</guid>
		<description><![CDATA[Below are my overall topics/themes I took away from the conference and some interesting points from each talk I witnessed along with links to the speaker’s site and slide show if availabe.]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/strange-loop-2009-day-1/";</script><p>A new developer conference has started in St Louis this year named <a href="http://thestrangeloop.com/" target="_blank">Strange Loop</a>.  Normally I don&#8217;t go to developer conferences because they are either in a different country or on the coasts.  This one was close by in St Louis, MO.  And from the quality of speakers and diverse sessions I predict next years conference will sell out very quickly unless they increase the capacity.  Below are my overall topics/themes I took away from the conference and some interesting points from each talk I witnessed along with links to the speaker&#8217;s site and slide show if available.<br />
<br/><br />
<a href="http://blog.codehangover.com/strange-loop-2009-day-2/">Day two</a></p>
<h4>Strange Loop Thoughts Overall</h4>
<ul>
<li>open source, open source, open source</li>
<ul>
<li>every talk envolved open source.  The FUD around open source is finally withering away.</li>
</ul>
<li>DRY constant theme</li>
<li>Mobile development is upon us and will be for maybe ever</li>
<li>Scala, Clojure, Groovy are HOT languages on the JVM</li>
<li>Great conference that covered many relevant topics</li>
<li>All the talks were technical, no boring management oriented sales pitches</li>
</ul>
<h4>Functional Ruby &#8211; Dean Wampler</h4>
<ul>
<li><a href="http://deanwampler.com/" target="_blank">http://deanwampler.com/</a></li>
<li><a href="http://polyglotprogramming.com/papers">Link to slide show</a></li>
<li>I atteneded this talk because I&#8217;m interested in the functional programming line of thought.  And I don&#8217;t get to see much ruby code.</li>
<li>Recommends learning a functiona programming language: Scala, Hascal, Cojure</li>
<ul>
<li>Multiprocessor systems are making it more important to use threads.  Threads and synchronizaton is hard to get right.  So functional languages that have immutable objects/values are easier because immutable objects/values don&#8217;t require synchronization.</li>
</ul>
<li>Try to avoid a bloated domain objects that have numerous properties to fullfill multiple requirements for different use cases.  Have smaller objects for seperate uses.</li>
</ul>
<h4>Polyglot Programming &#8211; Dean Wampler</h4>
<ul>
<li><a href="http://polyglotprogramming.com/papers">Link to slide show</a></li>
<li>polyglot programming: using more than one programming language.  Not like using CSS, JS.  But like using Groovy and Java or Groovy and Clojure.</li>
<li>Dean thinks that Scala could become very popular in the future</li>
<ul>
<li>Hybrid object and functional language</li>
<li>Multiple cpus is driving the need for functional languages</li>
</ul>
<li>Mentioned the famous quote: &#8220;Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.&#8221;<br />
&#8211;  Antoine de Saint-Exuper</li>
</ul>
<h4>Griffon (Swing just got fun again) &#8211; James Williams</h4>
<ul>
<li><a href="http://jameswilliams.be/blog/entry/index">http://jameswilliams.be/blog/entry/index</a></li>
<li><a href="http://groovy.codehaus.org/Griffon">http://groovy.codehaus.org/Griffon</a></li>
<li>Mentioned that the swring application framework is dead</li>
<li>Griffon is the unofficial grails for the desktop</li>
<ul>
<li>It really did looks rails like from the project layout to the build process</li>
</ul>
<li>Suggested Groovy In Action for anyone that wanted to earn Groovy</li>
</ul>
<h4>Future of Java &#8211; Bob Lee</h4>
<ul>
<li><a href="http://crazybob.org">http://crazybob.org</a></li>
<li>Writes his talks in Java. I&#8217;m serious.  Here is the SVN repo for his talks
<ul>
<li><a href="http://crazybobs-talks.googlecode.com/svn/trunk/">http://crazybobs-talks.googlecode.com/svn/trunk/</a></li>
</ul>
</li>
<li>Talked about how/why he wanted better resource management in Java.</li>
<li>Said he searched the JDK and found that 74 out of 110 the JDK has leaks for a certain IO functionality.</li>
<li>Talked about his work on JSR-330 dependency injection in JDK
<ul>
<li>@Inject annotation</li>
</ul>
</li>
<li>New quicksort that was developed for Android JVM (Harmony)</li>
</ul>
<p><br/><br />
<a href="http://blog.codehangover.com/strange-loop-2009-day-2/">Day two</a><br />
<br/><br />
<a href="http://thestrangeloop.com/sessions">Day One Sessions<img style="border: none;" src="http://img16.imageshack.us/img16/1298/strangeloop1.gif" alt="" /></a></ul>
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/strange-loop-2009-day-2/" title="Strange Loop 2009 &#8211; Day 2">Strange Loop 2009 &#8211; Day 2</a></li>
<li><a href="http://blog.codehangover.com/strange-loop-2010-early-bird-registration/" title="Strange Loop 2010 &#8211; Early Bird Registration">Strange Loop 2010 &#8211; Early Bird Registration</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Fstrange-loop-2009-day-1%2F&amp;linkname=Strange%20Loop%202009%20%26%238211%3B%20Day%201"><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/strange-loop-2009-day-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Spring Patterns: Best Practices and Design Strategies Book Review</title>
		<link>http://blog.codehangover.com/spring-patterns-best-practices-and-design-strategies-book-review/</link>
		<comments>http://blog.codehangover.com/spring-patterns-best-practices-and-design-strategies-book-review/#comments</comments>
		<pubDate>Sun, 16 Aug 2009 18:46:03 +0000</pubDate>
		<dc:creator>MikeNereson</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[book review]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=352</guid>
		<description><![CDATA[This is a book review of Pro Java™ EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework by Dhrubojyoti Kayal.]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/spring-patterns-best-practices-and-design-strategies-book-review/";</script><p>This is a book review of <a id="static_txt_preview" href="http://www.amazon.com/gp/product/1430210095?ie=UTF8&amp;tag=72mile-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1430210095">Pro Java™ EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework</a></p>
<h2>About the Book</h2>
<p>Apress describes this book as<br />
<a id="static_txt_preview" href="http://www.amazon.com/gp/product/1430210095?ie=UTF8&amp;tag=72mile-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1430210095"><img src="http://www.apress.com/resource/bookcover/9781430210092?size=medium" style="float: right; padding: 0  0 10px 10px;" border="0" /></a></p>
<blockquote style="padding:12px;"><p><em>Pro Java™ EE Spring Patterns</em> focuses on enterprise patterns, best practices, design strategies, and proven solutions using key Java EE technologies including JSP™, servlets, EJB™, and JMS APIs.<br/><br />
This Java EE patterns resource, catalog, and guide, with it&#8217;s patterns and numerous strategies, documents and promotes best practices for these technologies, implemented in a very pragmatic way using the Spring Framework and it&#8217;s counters.</p>
</blockquote>
<p>The book was written by Dhrubojyoti  Kayal. Dhrubojyoti works as a senior consultant with Capgemini Consulting. He has more than five years of experience developing and designing applications and products leveraging Enterprise Java technologies. His areas of interest include the Spring Framework, ORM, SOA, refactoring, prefactoring, and performance engineering.</p>
<p>In this book the author takes us through the process of refactoring a legacy system built without using patterns or the Spring Framework into a shiny new system leveraging Spring and design patterns. Throughout the book he takes us through this practical, real-word example.</p>
<h2>Introduction to the MVC Pattern</h2>
<p>The first chapter introduces you to the MVC pattern. I think that this book is for a well versed J2EE professional developer, who would probably be familiar with the pattern, so this chapter may have been overkill. However, the basis of this book is to refactor an antiquated web application to use Spring and the Spring MVC, so a clear and thorough understanding of the MVC pattern is necessary. Most readers of this book can probably skip this chapter. On the other hand it is written well enough that it would serve a good resource for any rookie developers that you might be working with who need to learn this pattern.</p>
<h2>Patterns</h2>
<p>Each chapter of this book takes you through the concepts of a common pattern, describes how the Spring Framework is used to implement that pattern, and then replaces the legacy insurance system code with new spring code. Once you get into the patterns, the book is divided into four major sections. These sections are</p>
<ul>
<li>Presentation Tier Design Patterns</li>
<li>Business Tier Design Patterns</li>
<li>Integration Tier Design Patterns</li>
<li>Crosscutting Design Patterns.</li>
</ul>
<p>This division helps to keep the conversation between the author and the reader focused and also makes it easy to find later when you come back to reference this information.<br />
<strong> </strong></p>
<h2>The Best Part</h2>
<p>My favorite part about this book is that it is a patterns book. I like to read books based on patterns more than any other type of book. Patterns books are naturally broken down into small, manageable chunks of information. When written, patterns are usually described using a common, easy to follow template and are small enough to read an entire pattern in one sitting, whether that sitting be while you are eating your lunch or a quick read before hitting the pillow. Because they are written this way, it is easy to read this book very quickly and easy to find what you are looking for when you come back later for specific information. Pattern-based books are great.</p>
<p>I also liked this book because it takes you through all the layers of a real-world system. As developers we all have to work with legacy code. If you don&#8217;t your very lucky. Because this is <em>real world</em> it is very easy to follow along with the author and the project and see the benefits of Spring and refactoring to patterns.</p>
<h2><strong>Needs Refactoring</strong></h2>
<p>It&#8217;s a good, well-written book, but there are some things that I think need to be changed.</p>
<p>First, as with any book with code examples, there is some odd code that should be rewritten or removed. For example, there is a business bean that has a DAO injected into it via a setter. However, this bean also contains a getter for that DAO. This is not common practice and, in my opinion, not recommended.</p>
<p>And second, all of the presentation patterns are in a single chapter, and all of the business and integration patterns are in their own chapters. I think each pattern should have had its own chapter. I just prefer the clearer boundaries between patterns and I think it would make finding these patterns later, when I come to reference the book, a little easier.</p>
<h2>You Should Read this Book</h2>
<p>You should read this book if you are a developer who uses Spring, and especially if you use Spring MVC. This is a great resource and a great way to learn about how Spring utilizes patterns internally to implement its services. Of course it also shows you how to use Spring to add patterns to your current code base. You should read this book if you use an MVC framework that is not Spring MVC and are considering Spring MVC for  your next project or are considering adapting Spring MVC to your current project. While this book deals with more than just the Spring MVC, the entire presentation tier section is based on it.</p>
<h2>Or Not&#8230;</h2>
<p>I do recommend this book to most developers, however you should not read Spring Patterns if you are not well versed with J2EE/JEE and the Spring framework. If you are looking to learn Spring, there are <a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2Fs%3Fie%3DUTF8%26x%3D0%26ref%255F%3Dnb%255Fss%26y%3D0%26field-keywords%3Dspring%2520framework%26url%3Dsearch-alias%253Dstripbooks&amp;tag=72mile-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=390957" target="_blank">other books that might be more suitable</a>.</p>
<p>Here are some last notes, straight from Apress, about this book:</p>
<ul>
<li>What you&#8217;ll Learn:
<ul>
<li>Get an introduction to enterprise Java/Java EE application design patterns.</li>
<li>Simplify enterprise Java design using the popular Spring Framework.</li>
<li>Examine presentation, business, web, and integration tier design patterns and best practices, including cross–cutting design patterns, AOP, etc.</li>
<li>See how the enhanced and up–to–date pattern catalog compares to core J2EE design blueprints.</li>
<li>Learn how to use comprehensive source code and configuration information.</li>
<li>Develop order management system requirements for the first in–depth enterprise application case study.</li>
<li>Design your order management system application using the final case study.</li>
</ul>
</li>
</ul>
<h4>Table of Contents</h4>
<p>Finally, here is the table of contents:</p>
<ul style="list-style:none; margin:0 auto; padding:0;float:left;">
<li style="float:left;display:inline;padding:2px;width: 130px;"><a href="http://farm3.static.flickr.com/2480/3827336608_88bbe2bec6_o.png" rel="lightbox[springpatterns]" style=""><br />
<img src="http://farm3.static.flickr.com/2480/3827336608_df45a303fe_m.jpg" border="0" /><br />
</a></li>
<li style="float:left;display:inline;padding:2px;width: 130px;"><a href="http://farm3.static.flickr.com/2672/3827336568_cf7c1c64aa_o.png" rel="lightbox[springpatterns]" style=""><br />
<img src="http://farm3.static.flickr.com/2672/3827336568_690d3568d1_m.jpg" border="0" /><br />
</a></li>
<li style="float:left;display:inline;padding:2px;width: 130px;"><a href="http://farm4.static.flickr.com/3572/3826538477_4e53339bea_o.png" rel="lightbox[springpatterns]" style=""><br />
<img src="http://farm4.static.flickr.com/3572/3826538477_d2d525f132_m.jpg" border="0" /><br />
</a></li>
<li style="float:left;display:inline;padding:2px;width: 130px;"><a href="http://farm4.static.flickr.com/3563/3827336680_b7c363a876_o.png" rel="lightbox[springpatterns]" style=""><br />
<img src="http://farm4.static.flickr.com/3563/3827336680_79666f704d_m.jpg" border="0" /><br />
</a></li>
<li style="float:left;display:inline;padding:2px;width: 130px;"><a href="http://farm4.static.flickr.com/3505/3826538533_4eb9442f45_o.png" rel="lightbox[springpatterns]" style=""><br />
<img src="http://farm4.static.flickr.com/3505/3826538533_0c78123757_m.jpg" border="0" /><br />
</a></li>
<li style="float:left;display:inline;padding:2px;width: 130px;"><a href="http://farm4.static.flickr.com/3548/3827336762_0414939c27_o.png" rel="lightbox[springpatterns]" style=""><br />
<img src="http://farm4.static.flickr.com/3548/3827336762_2f7a968aaf_m.jpg" border="0" /><br />
</a></li>
</ul>
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/asp-net-mvc-musings-and-book-review/" title="ASP.Net MVC Book Review and musings">ASP.Net MVC Book Review and musings</a></li>
<li><a href="http://blog.codehangover.com/book-review-nhibernate-2-beginners-guide/" title="NHibernate 2 Beginner&#8217;s Guide &#8211; Book Review">NHibernate 2 Beginner&#8217;s Guide &#8211; Book Review</a></li>
<li><a href="http://blog.codehangover.com/outliers-a-non-technical-book-every-freelancerdeveloper-should-read/" title="Outliers &#8211; A non technical book every freelancer/developer should read">Outliers &#8211; A non technical book every freelancer/developer should read</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Fspring-patterns-best-practices-and-design-strategies-book-review%2F&amp;linkname=Spring%20Patterns%3A%20Best%20Practices%20and%20Design%20Strategies%20Book%20Review"><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/spring-patterns-best-practices-and-design-strategies-book-review/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Read HTML with Java &#8211; Then 7 Fun Things to do to It</title>
		<link>http://blog.codehangover.com/read-html-with-java-then-7-fun-things-to-do-to-it/</link>
		<comments>http://blog.codehangover.com/read-html-with-java-then-7-fun-things-to-do-to-it/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 02:57:10 +0000</pubDate>
		<dc:creator>MikeNereson</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[parse]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=214</guid>
		<description><![CDATA[There are several ways to get the HTML content of a URL from Java. There are even more ways to get the HTML using open source java libraries. (read html in java) (java get html source)]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/read-html-with-java-then-7-fun-things-to-do-to-it/";</script><p>There are several ways to get the HTML content of a URL from Java. There are even more ways to get the HTML using open source java libraries. Last week Lars Vogel shared <a href="http://www.vogella.de/articles/JavaNetworking/article.html" target="_blank">how to get the HTML using nothing but the SDK</a>.</p>
<h2>SDK</h2>
<pre class="brush: java;">
final URL url = new URL(&quot;http://blog.codehangover.com&quot;);
final InputStream inputStream = new InputStreamReader(url);
final BufferedReader reader
             = new BufferedReader(inputStream).openStream();

String line;

while ((line = reader.readLine()) != null) {
   System.out.println(line);
}

reader.close();
</pre>
<h2>Apache Commons HttpClient</h2>
<p>You can also use the <a href="http://hc.apache.org/httpclient-3.x/" target="_blank">Apache Commons HttpClient</a> for a slightly easier to use library.</p>
<pre class="brush: java;">
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(&quot;http://blog.codehangover.com&quot;);

try {
 client.executeMethod(method);

 byte[] responseBody = method.getResponseBody();

 System.out.println(new String(responseBody));

} catch (Exception e) {

 e.printStackTrace();

} finally {

 method.releaseConnection();
}
</pre>
<p>But the real fun comes after you get the HTML. Now you get to work with it.</p>
<h2>7 Things to do with HTML Source in Java</h2>
<h4>1. Extract the Text from the Markup</h4>
<p>I worked on a web application that was similar to a feed reader. One of the features that we supported was searching the pages. To do this I needed to extract the text from the markup. I use the <a href="http://nekohtml.sourceforge.net" target="_blank">CyberNeko HTML Parser </a>for this task.</p>
<pre class="brush: java;">
private String getHtmlFilteredString(Reader reader)
{

  // create element remover filter
  ElementRemover remover;
  remover = new ElementRemover();
  remover.removeElement(&quot;script&quot;);
  remover.removeElement(&quot;link&quot;);
  remover.removeElement(&quot;style&quot;);
  remover.removeElement(&quot;CDATA&quot;);
  remover.removeElement(&quot;&lt;!--&quot;);
  remover.removeElement(&quot;meta&quot;);

  OutputStream stream = new ByteArrayOutputStream();

  try
  {
    String encoding = &quot;ISO-8859-1&quot;;
    XMLDocumentFilter writer = new Writer(stream, encoding);

    XMLDocumentFilter[] filters = {remover, writer};

    XMLInputSource source = new XMLInputSource(null, null, null, reader, null);

    XMLParserConfiguration parser = new HTMLConfiguration();
    parser.setProperty(&quot;http://cyberneko.org/html/properties/filters&quot;, filters);

    parser.parse(source);

  } catch (Exception e) {

    e.printStacktrace();
  }

  String content = stream.toString().trim();

  return content;
}
</pre>
<h4>2. Extract Links</h4>
<p>To find all of the links in an HTML fragment, maybe for your own spider, or to extract email addresses, you can use <a href="http://htmlparser.sourceforge.net" target="_blank">HtmlParser</a></p>
<pre class="brush: java;">

Collection&lt;String&gt; links = new ArrayList&lt;String&gt;();

try {

  URI uriLink = new URI(url);
  Parser parser = new Parser();
  parser.setInputHTML(htmlBody);
  NodeList list = parser.extractAllNodesThatMatch(new NodeClassFilter (LinkTag.class));

  for (int i = 0; i &lt; list.size (); i++){
    LinkTag extracted = (LinkTag)list.elementAt(i);
    String extractedLink = extracted.getLink();
    links.add(extractedLink);
  }

} catch (Exception e) {

  e.printStackTrace();
}
</pre>
<h4>3. Change Links</h4>
<p>Using the previous code, instead of calling <tt>getLink</tt>, you can call <tt>setLink</tt> to change the href. For example, this might be used by any type of analytics software that needs to track hits.</p>
<h4>4. Collect Email Addresses</h4>
<p>Using the previous code, before adding the link to the Collection, chech to see if it uses the mailto protocol by calling the <tt>boolean</tt> method <tt>isMailLink()</tt></p>
<pre class="brush: java;">
  for (int i = 0; i &lt; list.size (); i++){

    LinkTag extracted = (LinkTag)list.elementAt(i);

    if (extracted.isMailLink())
    {
      String extractedLink = extracted.getLink();
      links.add(extractedLink);
    }
  }
</pre>
<h4>5. Collect Images</h4>
<p>Still using <a href="http://htmlparser.sourceforge.net/" target="_blank">HtmlParser</a>, you can extract images by filtering on the <tt>ImageTag</tt>.</p>
<pre class="brush: java;">

Collection&lt;String&gt; imageUrls = new ArrayList&lt;String&gt;();

try {

  URI uriLink = new URI(url);
  Parser parser = new Parser();
  parser.setInputHTML(htmlBody);
  NodeList list = parser.extractAllNodesThatMatch(new NodeClassFilter (ImageTag.class));

  for (int i = 0; i &lt; list.size (); i++){
    ImageTag extracted = (ImageTag)list.elementAt(i);
    String extractedImageSrc = extracted.getImageUrl();
    imageUrls.add(extractedImageSrc);
  }

} catch (Exception e) {

  e.printStackTrace();
}
</pre>
<h4>6. Add Syntax Highlighting</h4>
<p>If you&#8217;re going to present the source on screen you <em>have</em> to add syntax highlighting. If you&#8217;re displaying on a web page, I would highly recommend using something like <a href="http://code.google.com/p/syntaxhighlighter/">SyntaxHighligher</a>, which is what we use on this blog. If you are displaying an a Swing app, you can use a tool called  <a href="http://ostermiller.org/syntax/" target="_blank">Syntax</a> which is now several years old.</p>
<pre class="brush: java;">
try {

     ToHTML toHTML = new ToHTML();

     toHTML.setInput(new FileReader(&quot;Source.java&quot;));
     toHTML.setOutput(new FileWriter(&quot;Source.java.html&quot;));
     toHTML.setMimeType(&quot;text/x-java&quot;);
     toHTML.setFileExt(&quot;java&quot;)

     toHTML.writeFullHTML();

 } catch (Exception e){

    e.printStackTrace();
 }
</pre>
<h4>7. Diff Two Sources</h4>
<p>Once you get the HTML source of two URLs, or you have an old version of the HTML stored somewhere, you might want a nicely formatted diff output.</p>
<p><a href="http://stackoverflow.com/users/14160/madlep" target="_blank">Madlep</a> wrote his own method to handle the diff and output the results <a href="http://stackoverflow.com/questions/319479/generate-formatted-diff-output-in-java/319857#319857" target="_blank">over on Stackoverflow.com</a></p>
<p>Given some simple input, his code gives simple output.</p>
<pre class="brush: java;">

String one = &quot;&quot; +
    &quot;&lt;ul&gt;&quot; +
    &quot;  &lt;li&gt;item 1&lt;/li&gt;&quot; +
    &quot;  &lt;li&gt;item 2&lt;/li&gt;&quot; +
    &quot;&lt;/ul&gt;&quot;;

String two = &quot;&quot; +
    &quot;&lt;p&gt;This is text&lt;/p&gt;&quot; +
    &quot;&lt;ul&gt;&quot; +
    &quot;  &lt;li&gt;item 1&lt;/li&gt;&quot; +
    &quot;  &lt;li&gt;item 2&lt;/li&gt;&quot; +
    &quot;  &lt;li&gt;item 3&lt;/li&gt;&quot; +
    &quot;&lt;/ul&gt;&quot;;

System.out.println(diffSideBySide(one, two));
</pre>
<p>Outputs</p>
<pre>                     <strong>&gt;</strong>  &lt;p&gt;This is text&lt;/p&gt;
&lt;ul&gt;                    &lt;ul&gt;
 &lt;li&gt;item 1&lt;/li&gt;          &lt;li&gt;item 1&lt;/li&gt;
 &lt;li&gt;item 2&lt;/li&gt;          &lt;li&gt;item 2&lt;/li&gt;
                     <strong>&gt;</strong>    &lt;li&gt;item 3&lt;/li&gt;
&lt;/ul&gt;                   &lt;/ul&gt;</pre>
<h2>3 More Things to do with the HTML</h2>
<p>This list sure feels incomplete at only 7 of a nice even 10 things. What else could you you do with the HTML? Ill pick the top three from the comments and finish this blog post with them.</p>
<p>(read html in java) (java get html source)<br />
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/php-framework-comparison/" title="PHP Framework Comparison">PHP Framework Comparison</a></li>
<li><a href="http://blog.codehangover.com/read-html-with-java-then-7-fun-things-to-do-to-it/" title="Read HTML with Java &#8211; Then 7 Fun Things to do to It">Read HTML with Java &#8211; Then 7 Fun Things to do to It</a></li>
<li><a href="http://blog.codehangover.com/list-of-version-control-web-sites/" title="List of Version Control Web Sites">List of Version Control Web Sites</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Fread-html-with-java-then-7-fun-things-to-do-to-it%2F&amp;linkname=Read%20HTML%20with%20Java%20%26%238211%3B%20Then%207%20Fun%20Things%20to%20do%20to%20It"><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/read-html-with-java-then-7-fun-things-to-do-to-it/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Getting friendly with Spring, JUnit and EasyMock.</title>
		<link>http://blog.codehangover.com/getting-friendly-with-spring-junit-and-easymock/</link>
		<comments>http://blog.codehangover.com/getting-friendly-with-spring-junit-and-easymock/#comments</comments>
		<pubDate>Sun, 02 Aug 2009 00:31:43 +0000</pubDate>
		<dc:creator>DanEngland</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=240</guid>
		<description><![CDATA[Here are some steps that can get you using Spring, JUnit and EasyMock all together in some Test Driven Development hotness.]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/getting-friendly-with-spring-junit-and-easymock/";</script><p>Here are some steps that can get you using Spring, JUnit and EasyMock all together in some Test Driven Development hotness.</p>
<p>Start by adding the following lines to the top of your unit test.  Specifying Autowire by name ensures you get the injection you want and will stop those Spring errors that there are more than one of the same type of mock objects in your <tt>mock-applicationContext.xml</tt>.  When you specify the Spring Junit runner you must provide one ore more context configurations with @ContextConfiguration.</p>
<p><strong>MyClassUnitTest.java</strong></p>
<pre class="brush: java;">
...
@Configurable(autowire = Autowire.BY_NAME)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {&quot;classpath:com/some/domain/someproject/resources/mock-applicationContext.xml&quot;})
public class MyClassUnitTest {
...
     @Autowired private Collaborator mockCollaborator;

     @Before
     public void setup() throws Exception {
     ...
     }

     @After
     public void teardown() throws Exception {
     ...
     }

     @Test
     public void testMyClass() throws Exception {

          //Set your mock behavior here
          ....

          EasyMock.replay(mockCollaborator);

          MyClass myClass = new MyClass(mockCollaborator);
          myClass.run();
          EasyMock.verify(mockCollaborator);

          // Other JUnit assertions
          ...
     }
 }
</pre>
<p>Then add your mocks to your <tt>mock-applicationContext.xml</tt> (an applicationContext in your test resources just for providing your unit tests with spring injection dependencies):</p>
<p><strong>mock-applicationContext.xml</strong></p>
<pre class="brush: xml;">
...
&lt;bean id=&quot;mockCollaborator&quot; name=&quot;mockCollaborator&quot; class=&quot;org.easymock.EasyMock&quot; factory-method=&quot;createStrictMock&quot;&gt;
     &lt;constructor-arg value=&quot;com.some.domain.someproject.Collaborator&quot;/&gt;
&lt;/bean&gt;

&lt;bean id=&quot;mockOtherCollaborator&quot; name=&quot;mockOtherCollaborator&quot; class=&quot;org.easymock.EasyMock&quot; factory-method=&quot;createStrictMock&quot;&gt;
     &lt;constructor-arg value=&quot;com.some.domain.someproject.OtherCollaborator&quot;/&gt;
&lt;/bean&gt;
...
</pre>
<p>Ensure your maven pom has the following test-scoped dependency:</p>
<p><strong>pom.xml</strong></p>
<pre class="brush: xml;">
...
&lt;dependency&gt;
     &lt;groupId&gt;org.springframework&lt;/groupId&gt;
     &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
     &lt;version&gt;2.5.6&lt;/version&gt;
     &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
...
</pre>
<p>Then use your mocks as normal. Make sure you call <tt>EasyMock.reset(mock)</tt> in your @After <tt>teardown()</tt> method so that each of your mocks are reset for each test.  You can also tell Spring to reset the context after a test if needed with @DirtiesContext.</p>
<p>For official documentation and tutorials check out these links.</p>
<h4>Spring</h4>
<p><a href="http://www.springsource.org/documentation">http://www.springsource.org/documentation</a></p>
<h4>JUnit</h4>
<p><a href="http://www.springsource.org/documentation">http://www.junit.org</a></p>
<h4>EasyMock</h4>
<p><a href="http://easymock.org/Documentation.html">http://easymock.org/Documentation.html</a><br />
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/spring-patterns-best-practices-and-design-strategies-book-review/" title="Spring Patterns: Best Practices and Design Strategies Book Review">Spring Patterns: Best Practices and Design Strategies Book Review</a></li>
<li><a href="http://blog.codehangover.com/load-multiple-contexts-into-spring/" title="Load Multiple Contexts into Spring">Load Multiple Contexts into Spring</a></li>
<li><a href="http://blog.codehangover.com/choose-many-spring-contexts-over-a-single-context/" title="Choose many Spring contexts over a single context">Choose many Spring contexts over a single context</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Fgetting-friendly-with-spring-junit-and-easymock%2F&amp;linkname=Getting%20friendly%20with%20Spring%2C%20JUnit%20and%20EasyMock."><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/getting-friendly-with-spring-junit-and-easymock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Load Multiple Contexts into Spring</title>
		<link>http://blog.codehangover.com/load-multiple-contexts-into-spring/</link>
		<comments>http://blog.codehangover.com/load-multiple-contexts-into-spring/#comments</comments>
		<pubDate>Sun, 26 Jul 2009 13:32:47 +0000</pubDate>
		<dc:creator>MikeNereson</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[applicationContext]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=168</guid>
		<description><![CDATA[How do you load more than one Spring application context? There are a couple of ways to do this.]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/load-multiple-contexts-into-spring/";</script><p>I have  already argued that <a href="http://blog.codehangover.com/choose-many-spring-contexts-over-a-single-context/" target="_blank">many application contexts are better than a single application context</a>. But how do you load more than one context?</p>
<p>There are a couple of ways to do this.</p>
<h2>web.xml contextConfigLocation</h2>
<p>Your first option is to load them all into your Web application context via the ContextConfigLocation element. You’re already going to have your primary applicationContext here, assuming you’re writing a web application. All you need to do is put some white space between the declaration of the next context.</p>
<pre class="brush: xml;">
&lt;context-param&gt;
    &lt;param-name&gt;
        contextConfigLocation
    &lt;/param-name&gt;
    &lt;param-value&gt;
        applicationContext1.xml
        applicationContext2.xml
    &lt;/param-value&gt;
&lt;/context-param&gt;

&lt;listener&gt;
    &lt;listener-class&gt;
        org.springframework.web.context.ContextLoaderListener
    &lt;/listener-class&gt;
&lt;/listener&gt;
</pre>
<p>The above uses carriage returns. Alternatively, yo could just put in a space.</p>
<pre class="brush: xml;">
&lt;context-param&gt;
    &lt;param-name&gt;
        contextConfigLocation
    &lt;/param-name&gt;
    &lt;param-value&gt;
        applicationContext1.xml applicationContext2.xml
    &lt;/param-value&gt;
&lt;/context-param&gt;

&lt;listener&gt;
    &lt;listener-class&gt;
        org.springframework.web.context.ContextLoaderListener
    &lt;/listener-class&gt;
&lt;/listener&gt;
</pre>
<h2>applicationContext.xm import resourcel</h2>
<p>Your other option is to just add your primary applicationContext.xml to the web.xml and then use import statements in that primary context.</p>
<p>In applicationContext.xml you might have…</p>
<pre class="brush: xml;">
&lt;!-- hibernate configuration and mappings --&gt;
&lt;import resource=&quot;applicationContext-hibernate.xml&quot;/&gt;

&lt;!-- ldap --&gt;
&lt;import resource=&quot;applicationContext-ldap.xml&quot;/&gt;

&lt;!-- aspects --&gt;
&lt;import resource=&quot;applicationContext-aspects.xml&quot;/&gt;
</pre>
<h2>Which strategy should you use?</h2>
<p>I always prefer to load up via web.xml This allows me to keep all contexts isolated from each other. With tests, we can load just the contexts that we need to run those tests. This makes development more modular too as components stay loosely coupled, so that in the future I can extract a package or vertical layer and move it to its own module.</p>
<p>If you are loading contexts into a non-web application, I would use the import resource.</p>
<p>Any benefits to going with the application context import method over the web.xml contextConfigLocation?<br />
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/spring-patterns-best-practices-and-design-strategies-book-review/" title="Spring Patterns: Best Practices and Design Strategies Book Review">Spring Patterns: Best Practices and Design Strategies Book Review</a></li>
<li><a href="http://blog.codehangover.com/getting-friendly-with-spring-junit-and-easymock/" title="Getting friendly with Spring, JUnit and EasyMock.">Getting friendly with Spring, JUnit and EasyMock.</a></li>
<li><a href="http://blog.codehangover.com/choose-many-spring-contexts-over-a-single-context/" title="Choose many Spring contexts over a single context">Choose many Spring contexts over a single context</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Fload-multiple-contexts-into-spring%2F&amp;linkname=Load%20Multiple%20Contexts%20into%20Spring"><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/load-multiple-contexts-into-spring/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Choose many Spring contexts over a single context</title>
		<link>http://blog.codehangover.com/choose-many-spring-contexts-over-a-single-context/</link>
		<comments>http://blog.codehangover.com/choose-many-spring-contexts-over-a-single-context/#comments</comments>
		<pubDate>Sun, 26 Jul 2009 13:29:40 +0000</pubDate>
		<dc:creator>MikeNereson</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=176</guid>
		<description><![CDATA[This is a short introduction to splitting up your bean definitions from one single Spring application context, to many application contexts. That is, from one XML file to many XML files. The general idea is to have one single primary application context, usually titled applicationContext.xml, and then many other application contexts with are named what they contain.]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/choose-many-spring-contexts-over-a-single-context/";</script><p>This is a short introduction to splitting up your bean definitions from one single Spring application context, to many application contexts. That is, from one XML file to many XML files. The general idea is to have one single primary application context, usually titled applicationContext.xml, and then many other application contexts with are named what they contain.</p>
<h2>Example</h2>
<p>For example, a single web project might contain the following contexts.</p>
<ul>
<li> applicationContext.xml</li>
<li> applicationContext-dao.xml</li>
<li>applicationContext-dao-datasource.xml</li>
<li>applicationContext-ldap.xml</li>
<li> applicationContext-aspects.xml</li>
<li>applicationContext-web.xml</li>
</ul>
<h2>Breakdown</h2>
<p>In this example, your DAO definitions, transaction managers, and DAO or integration interceptors are defined in applicationContext-dao.xml. We have further broken the DAO application context to a dao-datasource which contains our data sources. LDAP configuration, beans, and DAOs are in their own applicationContext-ldap.xml.</p>
<h2>Benefits</h2>
<p>Why so many? There have been a few benefits so far.</p>
<h4>Responsibility</h4>
<p>The <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principal</a> is widely accepted and states that</p>
<blockquote><p>&#8230; every object should have a single responsibility, and that all its services should be narrowly aligned with that responsibility.states that every object should have a single responsibility, and that all its services should be narrowly aligned with that responsibility.</p></blockquote>
<p>The same holds true for XML contexts.  The general ides is to make our contexts more robust and to be able to isolate a context&#8217;s tasks and capabilities. And clearly, working with a smaller XML file is easier than working with one enormous file. It is easier to maintain and easier to read.</p>
<h4>Testing</h4>
<p>When I wrote my tests for LDAP, I had my LDAP configuration in applicationContext.xml, but then every time I ran an LDAP test, I would get the WebApplicationContext, which would import applicationContext-hibernate, which would connect to the database. Tests took forever and needless resources were used. Now I just get applicationContext-ldap.xml which only contains LDAP configurations, so no needless resources are loaded and tests remain quick.</p>
<h4>Inclusion and Exclusion</h4>
<p>Finally, its really easy to comment out a line like</p>
<pre class="brush: xml;">&lt;import resource=&quot;applicationContext-aspects.xml&quot;/&gt;</pre>
<p>and quickly have all my aspects, which for me only write logs, disabled. Or easy to add a line like</p>
<pre class="brush: xml;">&lt;import resource=&quot;applicationContext-dao-mock.xml&quot;/&gt;</pre>
<p>which overrides all of your DAO implementations with mock DAOs. This would be for testing.</p>
<p>Does anyone else use multiple application context files? See any other benefits? Or problems?<br />
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/spring-patterns-best-practices-and-design-strategies-book-review/" title="Spring Patterns: Best Practices and Design Strategies Book Review">Spring Patterns: Best Practices and Design Strategies Book Review</a></li>
<li><a href="http://blog.codehangover.com/getting-friendly-with-spring-junit-and-easymock/" title="Getting friendly with Spring, JUnit and EasyMock.">Getting friendly with Spring, JUnit and EasyMock.</a></li>
<li><a href="http://blog.codehangover.com/load-multiple-contexts-into-spring/" title="Load Multiple Contexts into Spring">Load Multiple Contexts into Spring</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Fchoose-many-spring-contexts-over-a-single-context%2F&amp;linkname=Choose%20many%20Spring%20contexts%20over%20a%20single%20context"><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/choose-many-spring-contexts-over-a-single-context/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PropertyPlaceholderConfigurer with Default Values</title>
		<link>http://blog.codehangover.com/propertyplaceholderconfigurer-with-default-values/</link>
		<comments>http://blog.codehangover.com/propertyplaceholderconfigurer-with-default-values/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 01:22:26 +0000</pubDate>
		<dc:creator>MikeNereson</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.codehangover.com/?p=26</guid>
		<description><![CDATA[My current project relies heavily on Spring. We use the PropertyPlaceholderConfigurer so that our application contexts can <em>pull</em> values from the properties files and inject them into our beans. This is all very common. This means when the beans are being created and a value like ${someproperty} shows up, the BeanFactory visits the configred properties files to find the value for someproperty and injects that value into the bean.

The problem arises when a bean is configured using such a placeholder but the requested property is not found. This causes our application to fail to start.]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://blog.codehangover.com/propertyplaceholderconfigurer-with-default-values/";</script><p>My current project relies heavily on Spring. We use the <a href="http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html"><tt>PropertyPlaceholderConfigurer</tt></a> so that our application contexts can <em>pull</em> values from the properties files and inject them into our beans. This is all very common. This means when the beans are being created and a value like <tt>${someproperty}</tt> shows up, the BeanFactory visits the configured properties files to find the value for <tt>someproperty</tt> and injects that value into the bean.</p>
<p>The problem arises when a bean is configured using such a placeholder but the requested property is not found. This causes our application to fail to start.</p>
<p>Our solution was to extend <tt>PropertyPlaceholderConfigurer</tt> to provide default values. These default values are loaded before loading any properties files.  Firs well glance over the java class.</p>
<pre class="brush: java;">
import java.io.IOException;
import java.util.Properties;
import java.util.Map;
import java.util.HashMap;

public class DefaultPropertyPlaceholderConfigurer
        extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
{
  private Map&lt;String, String&gt; startingProperties = new HashMap&lt;String, String&gt;();

  public void setStartingProperties(Map&lt;String, String&gt; startingProperties)
  {
     this.startingProperties = startingProperties;
  }

  public DefaultPropertyPlaceholderConfigurer()
  {
      try
      {
          loadDefaultProperties();
      }
      catch (IOException e)
      {
          logger.warn(&quot;failed to load default properties&quot;, e);
      }
  }
   private void loadDefaultProperties()
          throws IOException
  {
      final Properties defaultProperties = new Properties();
       for(Map.Entry&lt;String,String&gt; entry : startingProperties.entrySet())
      {
          defaultProperties.put(entry.getKey(), entry.getValue());
      }
       this.setPropertiesArray(new Properties[]{defaultProperties});
  }
}
</pre>
<p>And the XML bean definition for our new <tt>PropertyPlaceholderConfigurer</tt>.</p>
<pre class="brush: xml; highlight: [4,5,6,7,8];">
  &lt;bean id=&quot;propertyConfigurer&quot;
        class=&quot;app.factory.config.DefaultPropertyPlaceholderConfigurer&quot;&gt;
      &lt;property name=&quot;ignoreUnresolvablePlaceholders&quot; value=&quot;true&quot; /&gt;
      &lt;property name=&quot;startingProperties&quot;&gt;
          &lt;map&gt;
              &lt;entry key=&quot;one.two.three&quot; value=&quot;123&quot; /&gt;
          &lt;/map&gt;
      &lt;/property&gt;
      &lt;property name=&quot;locations&quot;&gt;
          &lt;list&gt;
              &lt;value&gt;/WEB-INF/classes/preferences.properties&lt;/value&gt;
          &lt;/list&gt;
      &lt;/property&gt;
  &lt;/bean&gt;
</pre>
<p>So now, when <tt>one.two.three</tt> is not included in the properties file <tt>preferences.properties</tt> the value will be initialized to 123. The value is defined in the properties file, the default value of 123 is overridden with the custom value.</p>
<h4>Use Case</h4>
<p>Here are the details on our specific use case. We release updates that add new properties, however, in order for the user to run the updates, the application has to start first (it is a web application). If the property is not set then the BeanFactory fails to start the application because it can not resolve the placeholder. So the software can&#8217;t start without running the updates first, but the updates can not be run until the application is started. </p>
<p>Now the web application starts and uses the default value, the administrator can run the updates which add the custom values to the preferences.properties file, and the user is prompted to restart the software after the updates are complete. The restart is required to read the new values into the bean.</p>
<h4>Oops</h4>
<p>While I was writing this post I realized that there was a much simpler way to provide default properties without extending the base class. </p>
<p>Any ideas as to how I could have done it?<br />
<h3>Related Posts</h3>
<ul class="related_post">
<li><a href="http://blog.codehangover.com/track-every-build-number-with-maven/" title="Track every Build Number with Maven">Track every Build Number with Maven</a></li>
<li><a href="http://blog.codehangover.com/spring-patterns-best-practices-and-design-strategies-book-review/" title="Spring Patterns: Best Practices and Design Strategies Book Review">Spring Patterns: Best Practices and Design Strategies Book Review</a></li>
<li><a href="http://blog.codehangover.com/getting-friendly-with-spring-junit-and-easymock/" title="Getting friendly with Spring, JUnit and EasyMock.">Getting friendly with Spring, JUnit and EasyMock.</a></li>
</ul>
<script>var dzone_style="2";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.codehangover.com%2Fpropertyplaceholderconfigurer-with-default-values%2F&amp;linkname=PropertyPlaceholderConfigurer%20with%20Default%20Values"><img src="http://blog.codehangover.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.codehangover.com/propertyplaceholderconfigurer-with-default-values/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

