<?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>Carbon Five Community &#187; Java</title>
	<atom:link href="http://blog.carbonfive.com/category/java/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.carbonfive.com</link>
	<description></description>
	<lastBuildDate>Fri, 27 Aug 2010 00:24:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Intro to Spring MVC Talk at SD Forum</title>
		<link>http://blog.carbonfive.com/2010/04/java/intro-to-spring-mvc-talk-at-sd-forum</link>
		<comments>http://blog.carbonfive.com/2010/04/java/intro-to-spring-mvc-talk-at-sd-forum#comments</comments>
		<pubDate>Wed, 28 Apr 2010 05:12:18 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Speaking]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=986</guid>
		<description><![CDATA[I&#8217;ll be speaking next Tuesday evening for SD Forum in Palo Atlo about Spring MVC. It&#8217;s mostly an introductory talk, but I&#8217;ll weave in some opinions and lessons learned from real projects. I&#8217;ll cover many of the MVC features, including those introduced in 3.0, by walking through code for a running application. Event Page Networking [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ll be speaking next Tuesday evening for SD Forum in Palo Atlo about Spring MVC.  It&#8217;s mostly an introductory talk, but I&#8217;ll weave in some opinions and lessons learned from real projects.  I&#8217;ll cover many of the MVC features, including those introduced in 3.0, by walking through code for a running application.</p>
<p><strong><a href="http://www.sdforum.org/index.cfm?fuseaction=Calendar.eventDetail&#038;eventID=13694">Event Page</a></strong></p>
<p>Networking (and pizza) starts at 6:30 and we&#8217;ll get down to business at 7:00.  The night starts with a short talk about Agile Java by Bjorn Freeman-Benson, of New Relic fame.</p>
<p>If you&#8217;re still doing Java and you&#8217;re curious about Spring MVC, come join in the fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2010/04/java/intro-to-spring-mvc-talk-at-sd-forum/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Screw.Unit JS Testing in Maven: javascript-test-maven-plugin</title>
		<link>http://blog.carbonfive.com/2010/02/testing/screw-unit-js-testing-in-maven-javascript-test-maven-plugin</link>
		<comments>http://blog.carbonfive.com/2010/02/testing/screw-unit-js-testing-in-maven-javascript-test-maven-plugin#comments</comments>
		<pubDate>Thu, 25 Feb 2010 03:29:31 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript / AJAX]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=878</guid>
		<description><![CDATA[I&#8217;ve written a maven plugin to integrate Screw.Unit javascript tests into a maven build. The project is inspired by the Blue Ridge testing framework for Rails, but it&#8217;s a bit more light-weight by design. To use the plugin you should start by downloading Screw.Unit and implement your tests according to their instructions. Once you have [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve written a <a href="http://code.google.com/p/javascript-test-maven-plugin/">maven plugin</a> to integrate <a href="http://github.com/nkallen/screw-unit">Screw.Unit</a> javascript tests into a maven build.  The project is inspired by the <a href="http://blog.thinkrelevance.com/2009/5/12/blue-ridge-1-0-javascript-unit-testing-for-rails-scandalous">Blue Ridge</a> testing framework for Rails, but it&#8217;s a bit more light-weight by design.<br />
<span id="more-878"></span><br />
To use the plugin you should start by downloading Screw.Unit and implement your tests according to their instructions.  Once you have some tests implemented in html files, add the plugin to your maven pom file:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;executions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;execution<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;goals<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;goal<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>javascript-test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/goal<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/goals<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/execution<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/executions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.carbonfive.javascript-test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>javascript-test-maven-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.0-beta1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;includes<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;include<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>src/test/javascript/suite*.html<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/include<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/includes<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>You will probably also need to add Carbon Five&#8217;s public repository so that maven will know where to grab the plugin:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pluginRepositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pluginRepository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>c5-public-repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Carbon Five Public Repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://mvn.carbonfive.com/public<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pluginRepository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pluginRepositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The &lt;configuration&gt; section contains <a href="http://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html">standard</a> maven &lt;include&gt; and &lt;exclude&gt; tags to allow you to specify any Screw.Unit test suite html files you would like to include in your build.</p>
<p>Now when maven executes its test phase, it will include your javascript tests as well. Any test that fails will halt the build. When the test phase is complete the target directory will contain a &#8216;screw-unit&#8217; directory that contains the test reports. There will be two files for every file included in the test execution The first is an XML file named TEST-dir1.dir2.dir3.filename.html.xml that contains the test results for that file in a reasonable approximation of JUnit&#8217;s xml format. The other file will be named dir1.dir2.dir3.filename.html and will contain a sort of snapshot of the test suite&#8217;s html at the time the tests completed (the javascript will be removed and the css will be baked in).</p>
<p>Like Blue Ridge, the javascript-test-maven-plugin relies on the excellent <a href="http://ejohn.org/blog/bringing-the-browser-to-the-server/">env.js</a> project and the less-excellent <a href="http://www.mozilla.org/rhino/">Rhino</a> project to emulate a browser in Java.   Unfortunately this combination creates the possibility of discrepancies between the browser and build results, and the probability of relatively slow test execution.  To keep the simulation as realistic as possible, javascript-test-maven-plugin recreates the test environment for each Screw.Unit html file, so the more tests you can cram into a single file the faster your builds will run.</p>
<p>There are a few directions for future work.  I&#8217;d like for the plugin to handle other browser-based javascript testing frameworks.  Screw.Unit is popular, but seems suboptimal in many respects.  The only limiting factor here is the plugin&#8217;s ability to interpret the results.  If env.js could run in javascript interpreters other than Rhino, I&#8217;d like to give the the plugin the capability to fork out to <a href="http://www.mozilla.org/js/spidermonkey/">spidermonkey</a> for better compatibility and performance.  Modifying the plugin would be relatively easy, but env.js appears to have some significant dependencies on Java.</p>
<p>Check it out if you have a need for this kind of thing and let us know if you have any problems or suggestions.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2010/02/testing/screw-unit-js-testing-in-maven-javascript-test-maven-plugin/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Database Migrations: Fail when database is out of date</title>
		<link>http://blog.carbonfive.com/2010/01/java/database-migrations-fail-when-database-is-out-of-date</link>
		<comments>http://blog.carbonfive.com/2010/01/java/database-migrations-fail-when-database-is-out-of-date#comments</comments>
		<pubDate>Thu, 21 Jan 2010 05:41:15 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=811</guid>
		<description><![CDATA[The latest release of the Carbon Five Database Migration maven plugin supports a new goal: check. The check goal fails the build if the database isn&#8217;t up to date. That is, if there are pending migrations the plugin produces a clear message explaining that the database is out of date and lists the pending migrations. [...]]]></description>
			<content:encoded><![CDATA[<p>The latest release of the <a href="http://code.google.com/p/c5-db-migration/">Carbon Five Database Migration maven plugin</a> supports a new goal: check.  The check goal fails the build if the database isn&#8217;t up to date.  That is, if there are pending migrations the plugin produces a clear message explaining that the database is out of date and lists the pending migrations.  Run <code>mvn test</code> and see something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="console" style="font-family:monospace;">[INFO] ------------------------------------------------------------------------
[INFO] Building Gearlist - Data Access
[INFO]    task-segment: [test]
[INFO] ------------------------------------------------------------------------
[INFO] [db-migration:check {execution: default}]
[INFO] Checking jdbc:mysql://localhost/gearlist_test using migrations at src/main/db/migrations/.
[INFO] Loaded JDBC driver: com.mysql.jdbc.Driver
[WARNING] There are 2 pending migrations: 
&nbsp;
    20100116010256_audit_tracking.sql
    20100121052539_add_daily_reports.sql
&nbsp;
    Execute db-migration:migrate to apply pending migrations.
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] There are 2 pending migrations, migrate your db and try again.</pre></div></div>

<p>It&#8217;s very easy to include the check goal in your build lifecycle if you&#8217;re already using the db-migration-maven-plugin.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;build<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugins<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.carbonfive.db-support<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>db-migration-maven-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0.9.9-m2<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;executions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;execution<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;phase<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>validate<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/phase<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;goals<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;goal<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>check<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/goal<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/goals<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/execution<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/executions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jdbc:mysql://${db.host}/${db.name}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>${db.username}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>${db.password}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugins<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/build<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Check out the <a href="http://code.google.com/p/c5-db-migration/">project home</a> for additional documentation and details.  There&#8217;s also a simple, complete <a href="http://svn.carbonfive.com/public/christian/migration-sample1/trunk/">example application</a> showing off this configuration.</p>
<p>Enjoy!<br />
Christian</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2010/01/java/database-migrations-fail-when-database-is-out-of-date/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Secure Email with Spring&#8217;s JavaMailServer and Gmail</title>
		<link>http://blog.carbonfive.com/2009/11/java/secure-email-with-springs-javamailserver-and-gmail</link>
		<comments>http://blog.carbonfive.com/2009/11/java/secure-email-with-springs-javamailserver-and-gmail#comments</comments>
		<pubDate>Thu, 12 Nov 2009 21:38:16 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=737</guid>
		<description><![CDATA[Both Carbon Five and my ISP have moved email management over to Gmail.  While this has been a net improvement for me as an end user, it&#8217;s made it a bit more difficult to configure my applications to send outgoing mail.  It isn&#8217;t hard to find examples online that explain how to configure Spring&#8217;s JavaMailSender [...]]]></description>
			<content:encoded><![CDATA[<p>Both Carbon Five and my ISP have moved email management over to <a href="http://gmail.com">Gmail</a>.  While this has been a net improvement for me as an end user, it&#8217;s made it a bit more difficult to configure my applications to send outgoing mail.  It isn&#8217;t hard to find <a href="http://www.codinglabs.com/blog/?p=4">examples</a> <a href="http://stackoverflow.com/questions/854493/problem-configuring-springs-mailsender-for-our-smtp-server-but-gmail-works">online</a> that explain how to configure Spring&#8217;s <a href="http://static.springsource.org/spring/docs/1.1.x/api/org/springframework/mail/javamail/JavaMailSender.html">JavaMailSender</a> to work with Gmail.  But none of the examples I&#8217;ve found provide a configuration that can be switched between Gmail and an open SMTP server with a few reasonable external properties (an important feature in an application that needs to be deployed in varied environments).  What&#8217;s worse, the configurations tend to differ with no rational provided for the necessary parameters.  So I spent some time with the source and a debugger and came up with a simplified solution:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;color: blue;">&quot;mailSender&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.mail.javamail.JavaMailSenderImpl&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;defaultEncoding&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;host&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${mail.host}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;port&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${mail.port}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;protocol&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${mail.protocol}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;username&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${mail.username}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${mail.password}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;javaMailProperties&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;mail.debug&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>${mail.debug}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;mail.${mail.protocol}.auth&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>${mail.smtp-auth}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The properties for an open server look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">mail.host       = localhost
mail.port       = 25
mail.protocol   = smtp
mail.smtp-auth  = false
mail.username   =
mail.password   =
mail.debug      = false</pre></div></div>

<p>And the properties for gmail look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">mail.host       = smtp.gmail.com
mail.port       = 465
mail.protocol   = smtps
mail.smtp-auth  = true
mail.username   = my.email@address.com
mail.password   = mypassword
mail.debug      = true</pre></div></div>

<p>The host, port, username, password and debug properties should be obvious.  The key is to change the protocol between &#8216;smtp&#8217; and &#8216;smpts&#8217;.  The only real difference between smtp and smtps is that the later causes JavaMail&#8217;s SMTPTransport object to open an SSL socket to the server.  Gmail only accepts SSL connections on port 465.  After figuring this out, I was glad to see that Gmail was accepting my connections, but immediately frustrated to find that JavaMail was no longer attempting to authenticate before sending mail.  The trick is that JavaMail checks its transport related parameters under &#8216;mail.[protocol].[parameter]&#8216;.  This appears to be an entirely <a href="http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html">undocumented</a> feature of JavaMail.  Fortunately, we can substitute the protocol name into the parameter key as well, so our auth parameter still works with either &#8216;smtp&#8217; or &#8216;smtps&#8217;.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2009/11/java/secure-email-with-springs-javamailserver-and-gmail/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C5 Test Support new addition: FunctionalTestRunner</title>
		<link>http://blog.carbonfive.com/2009/10/testing/c5-test-support-new-addition-functionaltestrunner</link>
		<comments>http://blog.carbonfive.com/2009/10/testing/c5-test-support-new-addition-functionaltestrunner#comments</comments>
		<pubDate>Thu, 29 Oct 2009 01:54:03 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=702</guid>
		<description><![CDATA[We&#8217;re always looking for new ways to test our applications and we&#8217;ve been trying a few new things on our projects. One of the recent additions is a JUnit test runner designed to help make writing and running functional tests easier. In Javaland, we use Selenium and/or HtmlUnit for our functional tests. These are the [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re always looking for new ways to test our applications and we&#8217;ve been trying a few new things on our projects.  One of the recent additions is a JUnit test runner designed to help make writing and running functional tests easier.  In Javaland, we use Selenium and/or HtmlUnit for our functional tests.  These are the tests that run against a deployed application over the wire using a real or simulated browser.  Most of our functional tests work the application in the same way a real user would, testing sequences of realistic activity and often touching a number of pages.  Since our functional tests use either a real browser or a simulated one, Javascript is executed and assertions made on the results.  This gives us greater confidence that our app is really working, end to end.</p>
<p>Here&#8217;s the high-level flow that the functional test runner provides:</p>
<ol>
<li>Load fixture data from a DBUnit dataset.</li>
<li>Download and install the application server (if necessary).</li>
<li>Start the application server (using Cargo).</li>
<li>Deploy the application, waiting until it&#8217;s completely started.</li>
<li>Run one or more functional tests (using your preferred testing framework &#8211; Selenium, HTMLUnit, etc)&#8230;<br />
If a test dirties the database in a manner that must be reset, the test class can be marked with the @DirtiesDatabase annotation.  This will reload the database fixture and optionally restart the application.</li>
<li>Shutdown the application server.</li>
</ol>
<p><span id="more-702"></span><br />
It&#8217;s easy to use&#8230;  First add the maven dependency:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">  ...
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;repositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;repository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>c5-public-repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Carbon Five Public Repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://mvn.carbonfive.com/public<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/repository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/repositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  ...
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.carbonfive.test-support<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test-support<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0.9.2-m1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;scope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/scope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  ...</pre></div></div>

<p>And then write your first functional test:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@RunWith<span style="color: #009900;">&#40;</span>FunctionalTestRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FunctionalTestRunnerTest
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// This field is automatically injected by the test runner and references</span>
    <span style="color: #666666; font-style: italic;">// the functional test properties (see below).</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">Properties</span> properties<span style="color: #339933;">;</span>
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> propertiesShouldBeSetByRunner<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        assertThat<span style="color: #009900;">&#40;</span>properties, not<span style="color: #009900;">&#40;</span>nullValue<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>properties.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, greaterThan<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> applicationShouldBeDeployed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// Test using your preferred framework... just using URL as an example.</span>
        <span style="color: #003399; font-weight: bold;">URL</span> root = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399; font-weight: bold;">URL</span><span style="color: #009900;">&#40;</span>format<span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;http://localhost:%s/&quot;</span>, properties.<span style="color: #006633;">getProperty</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;appserver.port&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399; font-weight: bold;">String</span> content = IOUtils.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span>root.<span style="color: #006633;">openStream</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>content, containsString<span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Orange&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Lastly, create the  configuration file that goes along with it.  By default, it&#8217;s called functional-test.properties and lives at the root of the classpath (src/test/resources/ for maven users).  Here&#8217;s an example:</p>

<div class="wp_syntax"><div class="code"><pre class="properties" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># Application server</span>
<span style="color: #000080; font-weight:bold;">appserver.container</span>         <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> tomcat6x</span>
<span style="color: #000080; font-weight:bold;">appserver.installer</span>         <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> http://www.apache.org/dist/tomcat/tomcat-<span style="">6</span>/v6.0.20/bin/apache-tomcat-6.0.20.zip</span>
<span style="color: #000080; font-weight:bold;">appserver.port</span>              <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> 8080</span>
<span style="color: #000080; font-weight:bold;">appserver.logging</span>           <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> false</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Application configuration</span>
<span style="color: #000080; font-weight:bold;">app.war</span>                     <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> ./gearlist-webapp/target/gearlist-webapp-<span style="">1.0</span>-SNAPSHOT.war</span>
<span style="color: #000080; font-weight:bold;">app.context</span>                 <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> ROOT</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Database fixtures</span>
<span style="color: #000080; font-weight:bold;">fixture.restart_application</span> <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> false</span>
<span style="color: #000080; font-weight:bold;">fixture.file</span>                <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> classpath:/database-fixture.xml</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;"># Application configuration (not used by the functional test runner)</span>
<span style="color: #000080; font-weight:bold;">db.driver</span>                   <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> com.mysql.jdbc.Driver</span>
<span style="color: #000080; font-weight:bold;">db.host</span>                     <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> localhost</span>
<span style="color: #000080; font-weight:bold;">db.name</span>                     <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> gearlist_func_test</span>
<span style="color: #000080; font-weight:bold;">db.url</span>                      <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> jdbc:mysql://$<span style="">&#123;</span>db.host<span style="">&#125;</span>/$<span style="">&#123;</span>db.name<span style="">&#125;</span></span>
<span style="color: #000080; font-weight:bold;">db.username</span>                 <span style="color: #000000;">=</span><span style="color: #008000; font-weight:bold;"> root</span>
<span style="color: #000080; font-weight:bold;">db.password</span>                 <span style="color: #000000;">=</span></pre></div></div>

<p>Property values can reference other properties (e.g. db.url) and they&#8217;re all set as system properties so it&#8217;s easy to override your application properties for functional testing.</p>
<p>Both the database fixture loading and the application server steps can be customized by plugging in a new <a href="http://code.google.com/p/c5-test-support/source/browse/trunk/src/main/java/com/carbonfive/test/functional/DatabaseFixtureLoader.java">DatabaseFixtureLoader</a> or <a href="http://code.google.com/p/c5-test-support/source/browse/trunk/src/main/java/com/carbonfive/test/functional/ApplicationServerManager.java">ApplicationServerManager</a>, respectively.</p>
<p>Since it&#8217;s a JUnit extension, functional tests run exactly the same whether they&#8217;re triggered from the IDE or the command line.  This approach is a response to how clunky it felt using Maven to launch the application server before running the tests.  Also, with only one master orchestrator, it&#8217;s easier to handle redeploying the application if necessary.</p>
<p>Want to see a real example?  I&#8217;ve written a sample application called &#8220;gearlist&#8221; that&#8217;s available via <a href="http://svn.carbonfive.com/public/christian/gearlist/trunk">public svn</a> (press cancel if asked for authentication credentials).  It includes several HtmlUnit and Selenium functional tests, as well as other types of tests using some of the other test utils I&#8217;ve written.  Look for the readme for details.</p>
<p><a href="http://code.google.com/p/c5-test-support/">Carbon Five Test Support</a> is hosted on google code, where you can read what documentation there is and peruse the source.</p>
<p>There are a few things to work on, including better exception handling during initialization and some flexibility around the Cargo configuration, however, it&#8217;s pretty stable and there&#8217;s no reason not to use it now.  Give it it try and give me your feedback.  The plan is to tighten it up and write some documentation for the 0.9.2 release.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2009/10/testing/c5-test-support-new-addition-functionaltestrunner/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Web Application Testing @ SDForum October 6th</title>
		<link>http://blog.carbonfive.com/2009/09/testing/web-application-testing-sdforum-october-6th</link>
		<comments>http://blog.carbonfive.com/2009/09/testing/web-application-testing-sdforum-october-6th#comments</comments>
		<pubDate>Sat, 26 Sep 2009 18:20:07 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=675</guid>
		<description><![CDATA[Updated: Added links to presentation and source code. I&#8217;ll be down in Palo Alto speaking about Automated Web Application Testing Tuesday October 6th. If you&#8217;re interest in getting a peek at the typical Carbon Five Java web architecture along with a variety of strategies and techniques for testing, c&#8217;mon down and join us. The session [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Updated: Added links to presentation and source code.</strong></p>
<p>I&#8217;ll be down in Palo Alto speaking about Automated Web Application Testing Tuesday October 6th.  If you&#8217;re interest in getting a peek at the typical Carbon Five Java web architecture along with a variety of strategies and techniques for testing, c&#8217;mon down and join us.  The session will be primarily code-driven.  I&#8217;ll implement a few features along with unit, integration and functional tests and show off some of the techniques and custom tools that help keep things simple and easy during development.  Some of the topics include:</p>
<ul>
<li>Brief overview of our typical web architecture and tools stack</li>
<li>Differences between Unit, Integration and Functional Tests</li>
<li>Dealing with the database (schema and fixtures)</li>
<li>Where does test coverage pay off the most?</li>
<li>In-browser and out-of-browser functional testing</li>
<li>Carbon Five best practices, custom tools and techniques</li>
<li>And more&#8230;</li>
</ul>
<p>You can find the gritty details on the <a href="http://www.sdforum.org/index.cfm?fuseaction=Calendar.eventDetail&#038;eventID=13525">SDForum site</a>.</p>
<p>Doors at 6:30 and the show begins at 7:00.  Hope to see you there!</p>
<h3>Here are the artifacts from the presentation:</h3>
<ul>
<li><a href="http://svn.carbonfive.com/public/christian/gearlist/branches/sdforum/docs/Web%20Application%20Testing.pdf">Presentation (.pdf)</a></li>
<li><a href="http://svn.carbonfive.com/public/christian/gearlist/branches/sdforum/">Source Code (svn)</a></li>
<li><a href="http://svn.carbonfive.com/public/christian/gearlist/branches/sdforum/docs/readme.txt">Build and Run Instructions (readme.txt)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2009/09/testing/web-application-testing-sdforum-october-6th/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SmartyCard Launches!</title>
		<link>http://blog.carbonfive.com/2009/03/flexflash/smartycard-launches</link>
		<comments>http://blog.carbonfive.com/2009/03/flexflash/smartycard-launches#comments</comments>
		<pubDate>Wed, 18 Mar 2009 23:49:46 +0000</pubDate>
		<dc:creator>don</dc:creator>
				<category><![CDATA[Clients]]></category>
		<category><![CDATA[Flex/Flash]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=564</guid>
		<description><![CDATA[Our client SmartyCard launched in early March at the DEMO conference picking up the People&#8217;s Choice Award.  SmartyCard is a learning site that offers kids rewards for completing a variety of interactive learning games.  Kids are able to &#8216;learn, earn and play&#8217; grade-appropriate games while earning real and virtual rewards.]]></description>
			<content:encoded><![CDATA[<p>Our client <a href="http://www.smartycard.com" target="_blank">SmartyCard</a> launched in early March at the DEMO conference picking up the People&#8217;s Choice Award.  SmartyCard is a <a href="http://springwise.com/education/smartycard/" target="_blank">learning site that offers kids rewards for completing a variety of interactive learning games</a>.  Kids are able to &#8216;learn, earn and play&#8217; grade-appropriate games while earning real and virtual rewards.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2009/03/flexflash/smartycard-launches/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stripes: A Successful First Project</title>
		<link>http://blog.carbonfive.com/2009/02/java/stripes-a-succesful-first-project</link>
		<comments>http://blog.carbonfive.com/2009/02/java/stripes-a-succesful-first-project#comments</comments>
		<pubDate>Thu, 26 Feb 2009 19:12:47 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[stripes]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=301</guid>
		<description><![CDATA[We&#8217;re wrapping up a project that I&#8217;ve been leading since September and I&#8217;ve been reflecting on some of my decisions. Some of this reflection might be interesting to other developers. There are a few things on my mind, but I&#8217;ll start off off with my decision to use Stripes as our MVC instead of our [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re wrapping up a project that I&#8217;ve been leading since September and I&#8217;ve been reflecting on some of my decisions.  Some of this reflection might be interesting to other developers.  There are a few things on my mind, but I&#8217;ll start off off with my decision to use <a href="http://stripesframework.org">Stripes</a> as our MVC instead of our usual, Spring MVC.</p>
<h3>Background</h3>
<p>I&#8217;ve never been completely satisfied with Spring MVC (note that it&#8217;s pretty hard to win me over completely).  We know it well and we&#8217;ve had many successful projects while using it.  We&#8217;ve also used many of the new features that came along with Spring 2.5 (@Controller, more convention over configuration, etc), but in the end I still wasn&#8217;t loving it.</p>
<p>I came across Stripes over a year ago, and noted that it had a small but fairly vibrant and excited community.  The projects goals definitely resonated with me:</p>
<ul>
<li>Make developing web applications in Java easy</li>
<li>Provide simple yet powerful solutions to common problems</li>
<li>Make the Stripes ramp up time for a new developer less than 30 minutes</li>
<li>Make it really easy to extend Stripes, without making you configure every last thing</li>
</ul>
<p>So I decided to give it a try on a real project.  Switching from something we know inside and out to something that none of us had production experience with was arguably risky, so we decided to give it a try for a week with the intention that we&#8217;d go back to Spring MVC if anything took too long or felt awkward.  Thankfully, that never happened.</p>
<p>Some of this article may read a bit like a Stripes versus Spring MVC comparison.  That&#8217;s not really my  intention, but it&#8217;s somewhat inevitable as much of my experience has been with Spring MVC.  This isn&#8217;t intended to be a Stripes tutorial (there are great ones out there), so the code snippets and technical details will be sparse.</p>
<h3>Controller Lifecycle, Binding, and the Model</h3>
<p>Stripes controllers are called &#8220;Actions&#8221; or &#8220;ActionBeans&#8221; and each incoming HTTP request is routed to one primary Action (like Spring MVC).  Stripes creates a new Action instance for each incoming request; Spring Controllers are singletons in comparison.  Stripes binds parameters into the fields on the Action where Spring MVC passes them as method parameters.  The Stripes Action is not only the &#8220;Controller&#8221; in the MVC, but it also serves as the root of the &#8220;Model&#8221; as well.  The Action is made available to the View and all properties with getters can be queried using JSP-EL.  Spring&#8217;s model is separate, necessitated by the Singleton nature of the Controller.</p>
<p>Let&#8217;s look at a simple example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// URI and embedded parameters defined using CleanURLs</span>
@UrlBinding<span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;/status/{orderId}/{$event}&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> OrderStatusAction <span style="color: #000000; font-weight: bold;">extends</span> AbstractActionBean
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Spring managed service to be dependency injected (see &quot;Worth Mentioning&quot; below)</span>
    @Autowired OrderService orderService<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Required incoming parameter bound in the URI with {orderId}</span>
    @Validate<span style="color: #009900;">&#40;</span>required <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span>, minvalue <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">long</span> orderId<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// OrderStatus to be accessible from the view for rendering</span>
    OrderStatus orderStatus<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// public setter tells stripes to allow binding</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setOrderId<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">long</span> orderId<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">orderId</span> <span style="color: #339933;">=</span> orderId<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// public getter tell stripes to allow access from the view</span>
    <span style="color: #000000; font-weight: bold;">public</span> OrderStatus getOrderStatus<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> orderStatus<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Resolution view<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        orderStatus <span style="color: #339933;">=</span> orderService.<span style="color: #006633;">getOrderStatus</span><span style="color: #009900;">&#40;</span>orderId<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>orderStatus <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> ErrorResolution<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">404</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> ForwardResolution<span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;/WEB-INF/jsp/order-status.jsp&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In our view we can access the Action / Model:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">...
&lt;jsp:useBean id=&quot;actionBean&quot; scope=&quot;request&quot; type=&quot;eg.OrderStatusBean&quot;/&gt;
...
&lt;li&gt;Order Number: ${actionBean.orderStatus.order.id}&lt;/li&gt;
&lt;li&gt;Status: ${actionBean.orderStatus.status}&lt;/li&gt;
&lt;li&gt;Tracking Number: ${actionBean.orderStatus.trackingNumber}&lt;/li&gt;
...</pre></div></div>

<p>This example binds to a long, which is pretty simple.  Stripes can bind into graphs of objects, instantiating them along the way if necessary.  Collections are fully supported as well.  We haven&#8217;t yet found an example of something we couldn&#8217;t bind into right out of the box.</p>
<p>While I first was resistant to the Stripes lifecycle and combination of Controller and Model, I soon warmed up to it and now I find it quite natural, a bit better from a code readability standpoint, and more aesthetic.  It&#8217;s just the right amount of abstraction and encapsulation to make for speedy development while being easy to maintain.  I really like the fact that new instances of actions are created for each request, because the alternative is to pass all of your state into a handler method, which can easily lead hard-to-read code, especially with the annotations required to describe which request parameter maps to which method parameter.</p>
<p>If you can&#8217;t bind directly into your value objects and entities, the Action gives you a great place to bind into first, allowing you to manually instantiate your domain objects plugging in values from the Action.  This is quite useful when your domain model isn&#8217;t direct-binding friendly because of invariant enforcing, immutable value objects, and other practices encouraged by <a href="http://domaindrivendesign.org/">Domain Driven Design</a>.</p>
<p>We keep our Actions simple and lightweight, deferring all non-display logic to transactional, spring-managed services.  I&#8217;ve seen examples where Actions are directly interacting with the database, a pattern I discourage.</p>
<p>If you want to know more about how Stripes works, check out the references section at the end of this article.</p>
<h3>Generating URIs in Views</h3>
<p>I can&#8217;t tell you how many times I&#8217;ve run into regressions after making changes to URIs where a page would link to a controller at the wrong URI.  With Stripes, your URIs are defined once and only once, so when you change where an Action lives, pages will link to it correctly at its new location.  Stripes tags take a <code>beanclass</code> argument so that it can determine the correct URI at runtime rather than hard-coding it in the view.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;stripes:link</span> <span style="color: #000066;">beanclass</span>=<span style="color: #ff0000;color: blue;">&quot;eg.OrderStatusAction&quot;</span> <span style="color: #000066;">event</span>=<span style="color: #ff0000;color: blue;">&quot;view&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;stripes:param</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;orderId&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;65432&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  View Order Status
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/stripes:link<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Renders: &lt;a href=&quot;http://example.com/status/65432/view&quot;&gt;View Order Status&lt;/a&gt;</p>
<p>The &lt;stripes:url &#8230;/&gt; and &lt;stripes:form &#8230;/&gt; tags work the same way.  To round it out, Actions can forward or redirect to other Actions without embedding URIs:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> ForwardResolution<span style="color: #009900;">&#40;</span>OrderHistoryAction.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #0000ff;color: blue;">&quot;view&quot;</span><span style="color: #009900;">&#41;</span>.
<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> RedirectResolution<span style="color: #009900;">&#40;</span>OrderHistoryAction.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #0000ff;color: blue;">&quot;view&quot;</span><span style="color: #009900;">&#41;</span>.</pre></div></div>

<p>The net result is that there&#8217;s a single definition of each URI in our system and it lives on the Action which handles that URI, realizing the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don&#8217;t Repeat Yourself (DRY)</a> principle.  We&#8217;ve been able able to change our URIs easily without fear of breaking views, which has been helpful as the project grows.</p>
<h3>Configuration</h3>
<p>Stripes only needs a few lines of configuration in your web.xml.  That&#8217;s it (really).  Stripes was built with convention over configuration in mind from day one.  Actions and Extensions (Converters, Formatters, Interceptors, etc) are auto-discovered via classpath scanning.  We never found ourselves needing to configure something differently than how it was out of the box.</p>
<p>While you can configure Spring MVC to be convention based (it&#8217;s okay to chuckle at this too), it&#8217;s not that way out of the box.  Perhaps Spring 3.0 will change this, but I have the sense that no matter what, there will always be some evidence of the fact that Spring MVC&#8217;s internals allow a wide range of configuration.</p>
<h3>Converters and Formatters</h3>
<p>In other frameworks, these concepts are often conflated into a single class.  Stripes converters do one thing: convert from strings to objects (e.g. phone numbers, zip codes, etc).  Whenever you need to turn an incoming request parameters into something more than a string, the converter is there to help.</p>
<p>Formatters work the other way, formatting objects into something that looks right on the screen as text.  Formatters can support multiple format types, so that you can support displaying objects differently when necessary (e.g. phone with extension, zip code with a plus 4, etc).</p>
<p>These helpers are simple to write and test.  All of the stripes tags will use them if they&#8217;re present, so it&#8217;s easy to affect how something &#8212; phone numbers for example &#8212; are displayed across the entire application.</p>
<h3>Testing</h3>
<p>There&#8217;s no reference to the servlet API in your Action classes, so it&#8217;s easy to write tests against the Java code within.  Tests fall into two categories: very lightweight unit tests which only test what&#8217;s happening in your handler and slightly more heavy-weight tests which involve more of the stack (but not the servlet container).</p>
<p>The outline for a unit test goes something like this:</p>
<ol>
<li>Instantiate your Action</li>
<li>Inject service stubs/mocks</li>
<li>Use the public setters to specify values to necessary fields</li>
<li>Invoke the handler</li>
<li>Assert on the Resolution and the state of the Action (optionally your Stub)</li>
</ol>
<p>Note that all of our Action tests fall into this category, even though you can test more of the stack (URL binding and validation).</p>
<p>What you can&#8217;t do &#8212; I haven&#8217;t seen any Java MVC provide this though &#8212; is write tests against the rendered markup of your views (a la Rails) without bringing up the servlet container.</p>
<p>Read more about <a href="http://stripesframework.org/display/stripes/Unit+Testing">testing with Stripes here</a>.</p>
<h3>Documentation and Community</h3>
<p>The Stripes documentation is definitely not very complete or polished.  Some of the documentation is out of date or non-existent (e.g. CleanURLs).  The same goes for the examples.  There is a decent book from Pragmatic Programmers press however, which I recommend if you&#8217;re interested in Stripes.</p>
<p>The good news is that despite all of this, it&#8217;s easy enough to find or figure out what you need without too much fuss.  Piecing together examples, tutorials, bogs, documentation, etc ultimately gives you what you need.  The <a href="http://stripes.svn.sourceforge.net/viewvc/stripes/">Stripes source</a> is small enough that you can rummage through to see how things work easily.  It&#8217;s not as configurable as Spring MVC so the code is less abstract and a little easier to grok (though it&#8217;s not as elegant).</p>
<p>There is an active mailing list where the developers and other users help out with questions.</p>
<h3>Conclusion</h3>
<p>I think working with Stripes is a lot of fun and that we made the right decision to use it.  I&#8217;d go as far as saying that we were at least as productive with it as we would have been with Spring MVC, and it&#8217;s likely we were more productive.  I&#8217;d say that the authors have largely delivered on their goals.  One of our front-end developers quickly dove right into building Actions without much help from other developers.  While we had the occasional &#8220;Huh?!&#8221; moment while trying to figure out why something wasn&#8217;t working, they were few and far between.</p>
<p>In comparing it to Spring MVC, I think there&#8217;s a simplicity and elegance to Stripes that comes from it being just an MVC and it not having the same legacy as Spring.  While Spring MVC has certainly evolved, it&#8217;s brought some of its crufty parts along with it.  I&#8217;ll be keeping an eye on Spring MVC to see what&#8217;s in store with 3.0, and I hope to be proven wrong.</p>
<p>There&#8217;s no doubt that Stripes is in a niche as compared to many of the other web frameworks.  The community is much smaller, and the development cycle much longer (last release was August 2008 and the one before that May 2007), which sometimes makes me wonder what Stripes future holds.</p>
<p>I&#8217;d say that one downside to Stripes, or any other framework that has a single backing Action per URI, is that there isn&#8217;t a great story for dealing with pages that aggregate a number of features and those features also show up on other pages.  The problem is that we can&#8217;t rely on the Action to provide all of the reference data, so we have to rely on other mechanisms for fetching it (filters, interceptors, tags, etc).  It&#8217;s not an issue with Stripes specifically, but all framework with the same approach.</p>
<p>For projects where this single primary controller per URI limitation isn&#8217;t a problem, I would definitely use Stripes again and I think it&#8217;s a framework Java developers should look into if they aren&#8217;t completely happy with whatever they&#8217;re using.</p>
<h3>Also Worth Mentioning&#8230;</h3>
<p>There are lots of other neat features in Stripes too: validation annotations and helper methods, <a href="http://stripesframework.org/display/stripes/Layout+Reuse">stripes layout</a>, <a href="http://stripes.sourceforge.net/docs/current/javadoc/net/sourceforge/stripes/controller/FlashScope.html">flash scope</a>, wizard forms, encrypted parameters, a <a href="http://stripes.sourceforge.net/docs/current/javadoc/net/sourceforge/stripes/ajax/JavaScriptResolution.html">JavaScriptResolution</a> for serializing Java objects to JavaScript, etc.  Open up the Stripes jar and start looking around.</p>
<p>Our application is using Spring as an IoC container for everything behind our Actions; to get handles to your Spring managed services we use a <a href="http://blog.carbonfive.com/2008/03/java/injecting-spring-25-beans-into-stripes-actions">simple Stripes Interceptor which injects dependencies into Actions</a>.</p>
<p>When using CleanURLs, you&#8217;ll want to use the <a href="http://stripes.sourceforge.net/docs/current/javadoc/net/sourceforge/stripes/controller/DynamicMappingFilter.html">DynamicMappingFilter</a>, though there&#8217;s not much mention of it in the documentation.  CleanURLs in Stripes 1.5.1 should be even more flexible (see <a href="http://www.stripesframework.org/jira/browse/STS-617">STS-617</a>).</p>
<p>We used Spring Security on our application found that Stripes and Spring Security play nicely together.</p>
<p>Spring 3.0 will include a few new features that are similar to features I really like in Stripes, including RESTy URLs, and tags for generating the URIs to controllers.  The downside is that it&#8217;s still using the singleton model, which equates to controller handler methods with potentially lots of annotated parameters.</p>
<h3>References</h3>
<ul>
<li><a href="http://stripesframework.org">Stripes Homepage</a></li>
<li><a href="http://www.amazon.com/Stripes-development-Pragmatic-Programmers/dp/1934356212">Stripes by Federick Daoud</a></li>
<li><a href="http://stripesframework.org/display/stripes/2008/08/18/Stripes+1.5+Release+Available">Summary of Stripes 1.5 New Features</a></li>
<li><a href="http://greggbolinger.blogspot.com/2008/01/stripes-15-feature-clean-urls.html">CleanURLs Features</a></li>
<li><a href="http://www.devx.com/Java/Article/39199">Stripes in Black and White</a></li>
<li><a href="  http://www.gridshore.nl/2008/12/13/using-stripes-as-a-webmvc-framework-without-that-thing-called-xml/">Using Stripes as a webmvc framework without that thing called xml</a></li>
<li><a href="http://plugins.intellij.net/plugin/?id=1528">IntelliStripes &#8211; IntelliJ IDEA Plugin</a></li>
<li><a href="http://github.com/knifhen/javarebel-stripes-plugin/tree/master">Stripes JavaRebel Plugin</a></li>
<li><a href="http://blog.springsource.com/2008/12/05/spring-framework-30-m1-released/">Spring 3.0 M1 Features</a> and <a href="http://blog.springsource.com/2009/02/25/spring-framework-30-m2-released/">Spring 3.0 M2 Features</a></li>
<li><a href="http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/">Spring 3.0 MVC Features</a></li>
</ul>
<p>Updates: added reference to recently published Spring 3.0 MVC blog.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2009/02/java/stripes-a-succesful-first-project/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>More fun with Java Concurrency: BlockingQueue</title>
		<link>http://blog.carbonfive.com/2009/02/java/more-fun-with-java-concurrency-blockingqueue</link>
		<comments>http://blog.carbonfive.com/2009/02/java/more-fun-with-java-concurrency-blockingqueue#comments</comments>
		<pubDate>Mon, 23 Feb 2009 17:35:59 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[concurrency]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=308</guid>
		<description><![CDATA[I&#8217;ve written about Java 5 concurrency in the past and I&#8217;ve recently had the opportunity to make use of another one of the concurrency constructs: the BlockingQueue. The Problem There&#8217;s a problem we&#8217;ve seen a few times in the last few years. From time to time, applications must import data from external systems and massage [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve written about Java 5 concurrency <a href="http://blog.carbonfive.com/2008/05/testing/multithreaded-testing">in the past</a> and I&#8217;ve recently had the opportunity to make use of another one of the concurrency constructs: the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html">BlockingQueue</a>.</p>
<h3>The Problem</h3>
<p>There&#8217;s a problem we&#8217;ve seen a few times in the last few years.  From time to time, applications must import data from external systems and massage it into a form that is useful.  Sometimes these feeds are streamed over the net while other times they&#8217;re in the form of massive text files.  My current project has two such feeds that are imported on a weekly basis, the larger of the two rings in at around 10M entities.</p>
<p>Loading the data is pretty straightforward: entities are parsed from the source, a transient entity object is instantiated and the parsed values plugged in, entities are batched up and then persisted as a batch.</p>
<h3>The Collaborators</h3>
<p>The Parser is responsible for loading records one at a time from the source.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Parser<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">boolean</span> hasNextRecord<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    T nextRecord<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">void</span> close<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The Persister is responsible for saving batches of entities.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Persister<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">void</span> initializeFeed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">void</span> insertBatch<span style="color: #009900;">&#40;</span>List<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> entities<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">void</span> finalizeFeed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And the FeedLoader is the glue that pulls it all together, it coordinates parsing records into a batch and then triggering persisting the batches when they&#8217;re ready.  It&#8217;s used like this, where 1000 is the batch size:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Parser<span style="color: #339933;">&lt;</span>Wombat<span style="color: #339933;">&gt;</span> parser <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> WombatParser<span style="color: #009900;">&#40;</span>inputStream<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Persister<span style="color: #339933;">&lt;</span>Wombat<span style="color: #339933;">&gt;</span> persister <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> WombatPersister<span style="color: #009900;">&#40;</span>dataSource<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
FeedStats stats <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> FeedLoader<span style="color: #009900;">&#40;</span>parser, persister, <span style="color: #cc66cc;">1000</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">loadData</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now that the stage is set and we&#8217;ve covered the parts, we can get into what happens behind loadData().</p>
<h3>Synchronous Parsing and Persistence</h3>
<p>Our first cut of loadData() was a simple synchronous implementation:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FeedLoader<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Parser<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> parser<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Persister<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> persister<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> batchSize<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> FeedLoader<span style="color: #009900;">&#40;</span>Parser<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> parser, Persister<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> persister, <span style="color: #000066; font-weight: bold;">int</span> batchSize<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        Validate.<span style="color: #006633;">isTrue</span><span style="color: #009900;">&#40;</span>batchSize <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">parser</span> <span style="color: #339933;">=</span> parser<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">persister</span> <span style="color: #339933;">=</span> persister<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">batchSize</span> <span style="color: #339933;">=</span> batchSize<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> FeedStats loadData<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        persister.<span style="color: #006633;">initializeFeed</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        List<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> entities <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>batchSize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>parser.<span style="color: #006633;">hasNextRecord</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            entities.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>parser.<span style="color: #006633;">nextRecord</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>entities.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;=</span> batchSize<span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                persister.<span style="color: #006633;">insertBatch</span><span style="color: #009900;">&#40;</span>entities<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                entities.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// Save the stragglers that didn't make it into the last batch.</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>entities.<span style="color: #006633;">isEmpty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            persister.<span style="color: #006633;">insertBatch</span><span style="color: #009900;">&#40;</span>entities<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        parser.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        persister.<span style="color: #006633;">finalizeFeed</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> FeedStats<span style="color: #009900;">&#40;</span>...<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This worked well&#8230; we were able to process records at a throughput of about 3125 per second.  After a bit of research I realized we were spending nearly as much time parsing records as we were persisting them.  I also noticed that the load on the machine was pretty low during the import process.  While there is a relationship between parsing and persisting, it seemed like there should be an easy way split the processes across multiple threads while keeping the code simple and readable.</p>
<h3>Asynchronous processing with BlockingQueue and ExecutorService</h3>
<p>Digging through java.util.concurrent, I came across BlockingQueue which is described as &#8220;A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.&#8221;  Sounds like a great construct to bridge the gap between our Parser and Persister threads.  The parser can add entities to the queue while the persister is pulling them off into batches.  Let&#8217;s see what it looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FeedLoader<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Parser<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> parser<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Persister<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> persister<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> batchSize<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> done <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> FeedLoader<span style="color: #009900;">&#40;</span>Parser<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> parser, Persister<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> persister, <span style="color: #000066; font-weight: bold;">int</span> batchSize<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        Validate.<span style="color: #006633;">isTrue</span><span style="color: #009900;">&#40;</span>batchSize <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">parser</span> <span style="color: #339933;">=</span> parser<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">persister</span> <span style="color: #339933;">=</span> persister<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">batchSize</span> <span style="color: #339933;">=</span> batchSize<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> FeedStats loadData<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        persister.<span style="color: #006633;">initializeFeed</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        BlockingQueue blockingQueue <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayBlockingQueue<span style="color: #009900;">&#40;</span>batchSize <span style="color: #339933;">*</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">try</span>
        <span style="color: #009900;">&#123;</span>
            ExecutorService executorService <span style="color: #339933;">=</span> Executors.<span style="color: #006633;">newFixedThreadPool</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #666666; font-style: italic;">// invokeAll() blocks until both tasks have completed</span>
            executorService.<span style="color: #006633;">invokeAll</span><span style="color: #009900;">&#40;</span>
                asList<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ParserTask<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>parser, blockingQueue<span style="color: #009900;">&#41;</span>,
                       <span style="color: #000000; font-weight: bold;">new</span> PersisterTask<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>persister, blockingQueue<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            executorService.<span style="color: #006633;">shutdown</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InterruptedException</span> e<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            log.<span style="color: #006633;">error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Failed to load feed.&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">RuntimeException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Failed to load feed.&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        persister.<span style="color: #006633;">finalizeFeed</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> FeedStats<span style="color: #009900;">&#40;</span>...<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">class</span> ParserTask<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> <span style="color: #000000; font-weight: bold;">implements</span> Callable<span style="color: #339933;">&lt;</span>Object<span style="color: #339933;">&gt;</span>
    <span style="color: #009900;">&#123;</span>
        Parser<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> parser<span style="color: #339933;">;</span>
        BlockingQueue<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> queue<span style="color: #339933;">;</span>
&nbsp;
        ParserTask<span style="color: #009900;">&#40;</span>Parser<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> parser, BlockingQueue<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> queue<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">parser</span> <span style="color: #339933;">=</span> parser<span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">queue</span> <span style="color: #339933;">=</span> queue<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> call<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>parser.<span style="color: #006633;">hasNextRecord</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">try</span>
                <span style="color: #009900;">&#123;</span>
                    queue.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>parser.<span style="color: #006633;">nextRecord</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InterruptedException</span> e<span style="color: #009900;">&#41;</span>
                <span style="color: #009900;">&#123;</span>
                    log.<span style="color: #006633;">error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Failed to load feed.&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">RuntimeException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Failed to load feed.&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
            parser.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            done <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Indicates that the parser is done.</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">class</span> PersisterTask<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> <span style="color: #000000; font-weight: bold;">implements</span> Callable<span style="color: #339933;">&lt;</span>Object<span style="color: #339933;">&gt;</span>
    <span style="color: #009900;">&#123;</span>
        Persister<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> persister<span style="color: #339933;">;</span>
        BlockingQueue<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> queue<span style="color: #339933;">;</span>
&nbsp;
        PersisterTask<span style="color: #009900;">&#40;</span>Persister<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> persister, BlockingQueue<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> queue<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">persister</span> <span style="color: #339933;">=</span> persister<span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">queue</span> <span style="color: #339933;">=</span> queue<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> call<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            List<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> entities <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>batchSize<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">// &quot;done&quot; is set to false when the parser is done, at which point</span>
            <span style="color: #666666; font-style: italic;">// all remaining entities will be in the queue.</span>
            <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>done <span style="color: #339933;">||</span> <span style="color: #339933;">!</span>queue.<span style="color: #006633;">isEmpty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">try</span>
                <span style="color: #009900;">&#123;</span>
                    entities.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>queue.<span style="color: #006633;">take</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>entities.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;=</span> batchSize<span style="color: #009900;">&#41;</span>
                    <span style="color: #009900;">&#123;</span>
                        persister.<span style="color: #006633;">insertBatch</span><span style="color: #009900;">&#40;</span>entities<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        entities.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InterruptedException</span> e<span style="color: #009900;">&#41;</span>
                <span style="color: #009900;">&#123;</span>
                    log.<span style="color: #006633;">error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Failed to load feed.&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">RuntimeException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Failed to load feed.&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>entities.<span style="color: #006633;">isEmpty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                persister.<span style="color: #006633;">insertBatch</span><span style="color: #009900;">&#40;</span>entities<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>By allowing the parser and persister to run concurrently using two threads, the feed loaded with a throughput of 4608 entities per second, nearly a 50% improvement over the single threaded version.</p>
<p>There are two caveats to the code as written above: creating an ExecutorService for each loadData() isn&#8217;t ideal; it&#8217;s best to configure one for the application and resuse it, and also is must be shutdown before the application quits.  I&#8217;ve skimped on error handling, which is fine if the Parser<T> and Persister<T> implementations don&#8217;t throw exceptions.</p>
<h3>Conclusion</h3>
<p>The ExecutorService and BlockingQueue provide the tools to make this improvement easy while keeping the code pretty readable.  As always, we should be striving for readability, so adding unnecessary concurrency is never a good idea.  And your mileage may vary depending on many things, including the hardware, network, data, server load&#8230; so do some testing to measure the real improvement in production.</p>
<p>Even if you don&#8217;t end up using it, it&#8217;s fun to experiment with and learn about concurrency issues.  There are scenarios where the smart application of concurrency constructs can yield fantastic benefits.  Check our Greg Luck&#8217;s <a href="http://gregluck.com/blog/archives/2009/02/i_have_been_wai.html">recent blog on Ehcache performance</a> for an example.</p>
<p><em>Updates: added caveats and call to ExecutorService.shutdown().  Fixed a typo in the PersisterTask.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2009/02/java/more-fun-with-java-concurrency-blockingqueue/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Make the things you do often fast and easy</title>
		<link>http://blog.carbonfive.com/2008/09/java/make-the-things-you-do-often-fast-and-easy</link>
		<comments>http://blog.carbonfive.com/2008/09/java/make-the-things-you-do-often-fast-and-easy#comments</comments>
		<pubDate>Wed, 10 Sep 2008 15:31:59 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Rescue Mission]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=151</guid>
		<description><![CDATA[Many of our projects are &#8216;greenfield&#8217; and we have the opportunity to do things the way we like. By working on new projects every few months, as opposed to one project over the course of years, we have lots of opportunity to easily tweak and tune the way we do things. Not all of our [...]]]></description>
			<content:encoded><![CDATA[<p>Many of our projects are &#8216;greenfield&#8217; and we have the opportunity to do things the way we like.  By working on new projects every few months, as opposed to one project over the course of years, we have lots of opportunity to easily tweak and tune the way we do things.  Not all of our projects are from scratch though (see Alon&#8217;s post about <a href="http://blog.carbonfive.com/2008/09/testing/rewrite-or-rescue">Rewrite or Rescue</a>), so we sometimes end up dealing with years worth of history and crufty code.  It&#8217;s safe to say that each time we roll onto one of these projects, there&#8217;s going to be some level of bewilderment regarding what developers deal with on a daily basis.</p>
<p>Maybe it&#8217;s because we have a special opportunity to optimize the hell out of our development process, or the fact that we&#8217;re all productivity junkies; regardless of the reason, we religiously embrace the tenant &#8220;Make the things you do often fast and easy&#8221;.  It&#8217;s almost embarrassing to suggest that others don&#8217;t also subscribe to this simple notion, but &#8212; brace yourself &#8212; many do not.  On a project that has history, not everyone has been there for every decision.  In fact, many developers are at least relatively new and it&#8217;s somewhat customary to have a &#8220;it must be this way for a reason&#8221; attitude.  After all, who would deliberately make something cumbersome without good reason?</p>
<p>When we start working on one of these projects, we dedicate time to do some serious spring cleaning and tackle the things that will cost us the most in terms of pain and productivity.  The whole development team gets psyched about where we end up as it&#8217;s a significant improvement.  Projects with a history usually have a fair bit of low-hanging fruit.  Let&#8217;s discuss some of the things we see regularly.</p>
<h2>Build Systems</h2>
<p>Apparently few people like working on build scripts and when they do they have a habit of lowering their standards for quality of work.  That&#8217;s obviously not literally true, but sometimes it seems that way.  We&#8217;ve seen a number of beastly build systems that are slow because they&#8217;re doing things that aren&#8217;t necessary (extraneous jaring, copying, code generating, etc), they&#8217;re brittle and expensive to maintain, and full of dead code and duplicate target definitions&#8230; and they&#8217;re run many times every single work day.  It&#8217;s true that most developers may be compiling code from their IDE and thus bypassing the command-line build, but it&#8217;s still run on the build server, by ops folks, and even by developers when they&#8217;re debugging why something works from the IDE but busts on the build server.</p>
<h3>Guidelines for simplifying the build</h3>
<ul>
<li>Distill the build process down to the fastest, simplest steps that are necessary.</li>
<li>Eliminate duplicate and no-longer used dependencies; these files are being copied around and bundled for no reason (I&#8217;ve seen over 15 megs of unnecessary dependencies before).</li>
<li>When a project is split into multiple modules (and it should if it&#8217;s more than a few thousand lines), modules should be built in a consistent fashion using targets that are shared across modules.</li>
<li>Look for exceptions.  When you see something special happening for a particular file type, file name, or modules, ask yourself why.  Ask again.  Strive to eliminate these special cases when possible, even if they seem trivial.</li>
<li>Build a single deployable (or deployables) for all environments by eliminating environment-specific build code and externalizing application configuration. (Use Spring?  Check out this <a href="http://blog.carbonfive.com/2008/04/java/configuring-applications-with-spring">post on externalizing configuration with Spring</a>.)</li>
<li>Look for unnecessary code generation steps; if generated code changes once a year then check it in and make regenerating a manual step.</li>
<li>If you generate code coverage data, make sure that it&#8217;s only created when it&#8217;s needed (e.g. a nightly build on the build server), not on every build.</li>
</ul>
<p>So, we use <a href="http://maven.apache.org/">Maven 2</a> for all of our Java projects.  For sure, it has its share of rough edges (most of which are being fixed at a reasonable rate).  But it recommends some very sound conventions and doesn&#8217;t provide any scripting functionality, so it&#8217;s harder to hack it to do anything too unorthodox (please don&#8217;t use the antrun plugin unless as an incremental step when moving from Ant to Maven).  When you play ball by the Maven rules you&#8217;ll find your build much simpler and easier to maintain.  It&#8217;s likely you&#8217;ll notice other emergent benefits to boot.  For example, once you migrate to Maven you eliminate duplicate build configuration (both your command line build tool and IDE know how to compile your app &#8212; remember the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a>).  <a href="http://www.jetbrains.com/idea/features/ant_maven.html">IDEA</a>, Eclipse (via <a href="http://m2eclipse.codehaus.org/">m2eclipse</a>), and NetBeans all support importing from and synchronize with Maven.</p>
<p>Some people use <a href="http://incubator.apache.org/buildr/">Buildr</a> or Ant + <a>Ivy</a>, but either they don&#8217;t have the breadth of use (Buildr) or are more susceptible to writing nasty, unmaintainable build code (Ant).  That&#8217;s why we use Maven.</p>
<h2>Compile &gt; Deploy &gt; Make Changes &gt; Deploy Development Cycle</h2>
<p>Possibly more important than a simple and easy build, developers must be able to go through the compile, deploy, make changes, deploy cycle <em>FAST</em> (note that the compile, run tests, make changes, run tests cycle is also <em>very</em> important).</p>
<p>I remember working on an embedded system in 1998: a complex radio communications routing application written in C++ and deployed to custom hardware running the real-time operating system <a href="http://en.wikipedia.org/wiki/PSOS">PSOS</a>.  The build and deploy cycle took about 30 minutes and there were only 10 hardware instances for 60 engineers; you had to sign up for time slot on real hardware.  It was the epitome of unproductive as far as development environments go (and don&#8217;t even ask about debugging!).  You&#8217;d think such things were completely in the past (luckily they mostly are), but they&#8217;re not completely.  In the last 2 years I&#8217;ve seen applications that take 15 minutes to deploy.</p>
<p>It&#8217;s a drag when developers have to wait for these things to happen and it can totally destroy one&#8217;s rhythm, keeping developers from getting into the zone.  What&#8217;s worse, it&#8217;s completely unnecessary with modern tools.</p>
<h3>General Suggestions</h3>
<ul>
<li>Don&#8217;t drop down to the command-line; compile and deploy from your IDE (the IDE is your friend &#8211; master it).</li>
<li>Minimize steps for deploying changes to a running app:
<ul>
<li>Your IDE may support building on frame deactivation (IDEA does); check it out.</li>
<li>Look into the <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin">maven-jetty-plugin</a> if you use Maven.</li>
<li>Run in debug mode so that code can be hot-swapped or invest in <a href="http://www.zeroturnaround.com/javarebel/">JavaRebel</a>, which allows all sorts of code changes to take place without redeploying your application.</li>
<li>Deploy your application in exploded form; bundling a war or ear incurs unnecessary IO overhead.</li>
</ul>
</li>
<li>Host your database either locally on your workstation or on a beefy database server on the same LAN.  Remote databases are generally many times slower due to latency, even over fast connections.</li>
<li>Use JBoss?  Consider migrating to Jetty or Tomcat.  If that&#8217;s impossible, use the most stripped down profile (minimal, default, or all) that has what you need, or better yet, create a custom one which includes <em>only</em> what you need.</li>
<li>Minimize the amount of data needed in the database to run the application.  The same goes for running tests: do whatever it takes to run your tests against an empty (or very close to) schema. Check out the <a href="http://code.google.com/p/c5-db-migration/">Carbon Five DB Migration Project</a>.</li>
<li>Don&#8217;t skimp on developer hardware.  Buying the very fastest CPU isn&#8217;t going to be worth it, so aim for one or two models down from the fastest.  Buy the fastest hard disk you can since development is generally IO bound (WD Raptor and the new VelociRaptor are awesome, consider SSDs if your coffers run deep).  Avoid older CPU architectures (Pentium D), even when the clock speed (GHz) is faster.  Lastly, don&#8217;t be shy with memory; 4GB isn&#8217;t too much for a developer machine.</li>
</ul>
<p>In addition to these general recommendations, each individual application will have its own specific sources of inefficiency.  Many real world applications depend on services provided by application servers and/or a commercial products: message queues (JMS, ActiveMQ, etc), distributed caches (memcached, coherence, etc), enterprise service buses, job schedulers, work flow engines, etc.  It&#8217;s important that these services don&#8217;t get in the way of developing <em>fast</em>.  Some of them can be run in a light-weight development mode.  If you need to use one of these potentially heavyweight solutions, invest the time to minimize or eliminate any adverse effects to the development cycle.</p>
<h2>What Else?</h2>
<p>Some of the best improvements have nothing to do with the technical side of software development.  Take a step back and look at what else is happening (or not happening) each day.  There may be meetings which can be time boxed, consolidated, or eliminated all together.  Take a look at collaboration between engineers, product managers, testers, support and operations.  How long are developers waiting to have requirements-clarifying questions answered?  Ask your whole team where they think things can be improved.  Ask for feedback on a regular basis and allow it to help drive these improvements.</p>
<h3>Survey of other activities that should be fast and easy</h3>
<ul>
<li>Running the automated test suite &#8211; &lt; 10 minutes</li>
<li>Getting build results from continuous integration server &#8211; &lt; 10 minutes</li>
<li>Pushing a build to staging/acceptance server &#8211; One click build and deploy</li>
<li>Create a new instance of a minimal database instance &#8211; <a href="http://code.google.com/p/c5-db-migration/">Carbon Five DB Migration Project</a></li>
<li>Recreate production state in development for debugging</li>
<li>Story approval/acceptance &#8211; Continuous acceptance</li>
<li>Meetings &#8211; Timebox, Consolidate, Eliminate</li>
<li>Configure a new developer machine &#8211; Strive for zero configuration</li>
</ul>
<h2>Value Simplicity</h2>
<blockquote><p>Any intelligent fool can make things bigger, more complex and more violent.  It takes a touch of genius and a lot of courage to move in the opposite direction. -Albert Einstein</p></blockquote>
<p>There&#8217;s a theme underlying most of the solutions to these problems: simplicity.  Complex  systems don&#8217;t become complex and crufty overnight, they get that way one small step at a time.  With each change to a system it&#8217;s important to recognize that the change will either add complexity or remove it.  Complexity has a cost and it&#8217;s not to be taken lightly; make sure the benefit to each of the decisions that add complexity is worth that cost.</p>
<h2>Conclusion</h2>
<p>Making the things that people do often fast and easy can pay off geometrically as all developers benefit and regain a little more of their day (and sanity).  In the end, it&#8217;s not <em>just</em> about shaving off seconds or minutes, though that&#8217;s a huge part of it; it&#8217;s about creating a development environment that lets the team do what&#8217;s really important: write awesome code to solve real problems.  When the team dynamics, technical environment, and process are tuned just right, the overall benefit is greater than the sum of its parts.</p>
<p>Where have you seen changes in infrastructure, software, or process that&#8217;s resulted in a significant productivity bump?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/09/java/make-the-things-you-do-often-fast-and-easy/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rewrite or Rescue</title>
		<link>http://blog.carbonfive.com/2008/09/java/rewrite-or-rescue</link>
		<comments>http://blog.carbonfive.com/2008/09/java/rewrite-or-rescue#comments</comments>
		<pubDate>Fri, 05 Sep 2008 20:31:14 +0000</pubDate>
		<dc:creator>alon</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Rescue Mission]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=164</guid>
		<description><![CDATA[Java has been the tool of choice for enterprise application development for many organizations for over 10 years. We are seeing more and more applications that are aging and suffering for it. We have worked with several recent clients to breathe new life in to these legacy applications so they can evolve and grow with [...]]]></description>
			<content:encoded><![CDATA[<p>Java has been the tool of choice for enterprise application development for many organizations for over 10 years. We are seeing more and more applications that are aging and suffering for it. We have worked with several recent clients to breathe new life in to these legacy applications so they can evolve and grow with the business they support.</p>
<p>This is the first of a series of articles about improving the quality of existing software and the processes that produce it.</p>
<h2>Why Not Rewrite</h2>
<p>We&#8217;ve all encountered software that we would rather just rewrite than try to fix. The problem may be poor design, poor implementation, lack of tests, bugs or any of a host of other software ills. We see ahead of us the pain of working with a poor quality system and the risks to schedule and quality of end product it creates.</p>
<p>At Carbon Five, we have participated in many successful projects to rewrite applications for our clients. Sometimes starting with a clean slate and all the lessons learned from a previous effort is exactly the right approach. Often it is not. </p>
<p>In our experience the greatest obstacle to a rewrite effort is that the existing system is the only accurate record of the requirements for the system. Applications evolve over years to meet the changing needs of a organization and its users. Many small decisions are made and captured in the functioning application only. Rewriting to reproduce the features of an existing system can be a very difficult effort to define and scope.</p>
<p>Usually the troubled application will continue to be use while a rewrite effort is underway. Often support, maintenance and feature development will need to continue on that application even while a rewrite is under way. A rewrite will compete for development resources and will be chasing new feature development on the existing application.</p>
<p>Not everything in the troubled application is rotten. There are often good pieces, or at least components that are reliable and well understood. It would be great to not have to rewrite them.</p>
<p>How can you be sure that a rewritten application will be so much better than the one it is replacing? All too often, the source of poor software quality is poor process and practices. Unless you fix those problems it is not worth embarking on a new software development effort. </p>
<h2>How to Rescue</h2>
<p>Sometimes a decision to rewrite is made because rescuing an application seems too daunting. Where do you start? How long will it take? Here are some high level thoughts from our experiences with our customers. We will get in to more detail on specifics in later articles.</p>
<h3>Set Short Term Goals</h3>
<p>Be sure to set demonstrable short term goals with meaningful names. When your job is to make the system &#8220;better&#8221; your job is never done. You need discrete goals with names that you can finish, demonstrate, release and feel good about before moving on. Easily communicated goals help to show management that the effort is progressing successfully and help your team build confidence in an often daunting task.</p>
<p>On one of our projects we set a goal of having a unit test in place for a component in our service layer. &#8220;Service Test&#8221; would be a fine name for that goal. In a system with no testing support, this was a big task that once completed opened the door for much easier testing.</p>
<h3>Don&#8217;t Let &#8220;Refactor&#8221; Become a Dirty Word</h3>
<p>A lot of the work you will do when rescuing an application can be characterized as refactoring:</p>
<blockquote cite="http://www.refactoring.com"><p>
Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.<br />
<em>Martin Fowler, http://www.refactoring.com</em>
</p></blockquote>
<p>Don&#8217;t let &#8220;refactor&#8221; become a dirty word. It&#8217;s too easy to say, &#8220;Yesterday I worked on refactoring our persistence layer. Today I&#8217;m going to keep working on that.&#8221; Again, come up with a name or description for the work you are doing that enables others to understand what you are doing and for you to describe progress through that task. Refactoring is one activity of many that you will engage in during this process. Avoid using &#8220;refactor&#8221; in the names of your short term goals.</p>
<h3>Introduce Testing</h3>
<p>A common attribute of many struggling applications is conspicuous lack of automated testing and the design and infrastructure to support it. We have found that the many changes required to support and write automated unit and integration tests are exactly the changes an application needs to get healthy. They include:</p>
<ul>
<li>Automating and streamlining build systems</li>
<li>Decoupling application components</li>
<li>Minimizing dependencies on application server features </li>
<li>Building test data sets</li>
<li>Continuous integration</li>
<li>Building a team interest in quality</li>
</ul>
<p>Each of these items is challenging to implement. You can&#8217;t do them all at once yet they are dependent on each other. Fortunately there are good open tools and practices available that provide a helpful bootstrap including Maven for convention-based builds, EasyMock to test code with lots of dependencies, Spring for component management outside of an application server, and CruiseControl for continuous integration (not to ignore the excellent almost-free options like TeamCity and Bamboo).</p>
<p>Introducing testing to a legacy application with no support for it is a daunting challenge and slow going at first. We&#8217;ve had good success in the past by first cleaning up the build and adding the ability to run tests, then finding a place in the application to break apart components and wedge a first test in. With a running test, you have something to automate so you can get continuous integration running. You also have a lot more insight into the architectural changes that will both improve the health of the application and make it easier to add more tests.</p>
<p>We have a lot more to say about this topic and specific experiences to share in coming articles.</p>
<h3>A Culture of Quality</h3>
<p>Another common attribute of a struggling application is that the team maintaining and developing the application is in continuous firefighting mode. They&#8217;ve lost hope of making fundamental improvements to their system and on a daily basis are fixing emergency bugs and hacking in features with their fingers crossed that they are not breaking something else.</p>
<p>Teams working in this mode collaborate poorly with product management. Product management feels that the developers are resistant to new features. Getting releases out is painful and unpredictable because defect rates are high.</p>
<p>These teams also collaborate poorly with each other. Developers tend to become isolated from each other as sole maintainers of one application component or another. They do not talk about how to make things better and become resigned to living with the status quo. </p>
<p>To be successful in a rescue mission or even a rewrite, you have to turn the firefighting culture into one where developers value quality and work for it daily. They should be excited to make things better and be engaging each other with ideas and practices to get there.</p>
<p>Again, this can be a very difficult effort. Sometimes it requires dramatic measures. In our experience this includes:</p>
<ul>
<li>Changing a workspace to remove barriers to casual conversation</li>
<li>Relocating developers to the same physical location</li>
<li>Hiring new blood and firing those resistant to change</li>
<li>Pair programming</li>
<li>Book clubs and study groups</li>
</ul>
<p>These changes are often the most painful to make. As a consulting company Carbon Five can advocate for these changes, teach pair programming and run a study group, but the real changes have to come from within. We have seen the most success in making these changes when there is an commitment to improve from the business and champions of this effort in management.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/09/java/rewrite-or-rescue/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Java Database Migrations</title>
		<link>http://blog.carbonfive.com/2008/09/java/java-database-migrations</link>
		<comments>http://blog.carbonfive.com/2008/09/java/java-database-migrations#comments</comments>
		<pubDate>Wed, 03 Sep 2008 16:00:12 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=129</guid>
		<description><![CDATA[News: v0.9.9-m2 has been released! A while back, I wrote to introduce the first incarnation of the Carbon Five Database Migration tools, a simple though powerful framework for applying discrete changes to a database and tracking which changes have been applied to a specific database. It was inspired by Rails&#8217; Migration support. We&#8217;ve made a [...]]]></description>
			<content:encoded><![CDATA[<p><b>News: v0.9.9-m2 has been released!</b></p>
<p>A while back, I wrote to introduce the first incarnation of the <a href="http://blog.carbonfive.com/2008/02/java/introducing-java-db-migrations">Carbon Five Database Migration tools</a>, a simple though powerful framework for applying discrete changes to a database and tracking which changes have been applied to a specific database.  It was inspired by Rails&#8217; Migration support.</p>
<p>We&#8217;ve made a number of changes in the v0.9.1 release.  We adopted some of the improvements found in Rails 2.1 as well as feedback from our users.  Here&#8217;s an overview of what&#8217;s changed:</p>
<ul>
<li>New create, drop, and reset goals for maven plugin. Now you can create a new database, drop an existing one, or reset an existing database by dropping it, creating a new one and then migrating it.  This is tested with MySQL and PostgreSQL.</li>
<li>Each applied migration is tracked in the database schema_version table (instead of just the last one).  Also, when it was run and how long it took to run are now saved for each.</li>
<li>Validate goal now lists which migrations are pending in addition to whether the database is up to date.</li>
<li>Maven artifact ids have changed (migration -> db-migration, maven-migration-plugin -> maven-db-migration-plugin) and there&#8217;s been some restructuring in the core framework.</li>
<li>Maven plugin is configured a bit differently now; environments have been removed completely since maven supports a better solution out of the box: <a href="http://maven.apache.org/guides/introduction/introduction-to-profiles.html">profiles</a>.
<li>Maven plugin now looks for migrations in src/main/db/migrations by default; alternate locations can be specified via the &lt;migrationsPath/&gt; element.</li>
<li>We now recommend using timestamps for migration versions instead of the NNN format, though any numerical character sequence will work.</li>
<li>Reworked the algorithm for determining which migrations to run to allow for a little more flexibility.  Pending migrations aren&#8217;t determined by a single version number, they&#8217;re determined by comparing what is available to what has already been run.  In conjunction with timestamp versions, developers won&#8217;t be stepping on each other&#8217;s migrations.</li>
<li>New and updated <a href="http://code.google.com/p/c5-db-migration/">google code project</a> and documentation.</li>
</ul>
<p>As you can imagine, some of these changes aren&#8217;t backwards compatible.  While we&#8217;re in pre-release (< v1.0) mode, we feel like it's more important to make the fundamental changes to build a solid foundation than to retain complete backwards compatibility.  The  <a href="http://code.google.com/p/c5-db-migration/wiki/ReleaseNotes">release notes</a> give some guidelines for upgrading.</p>
<p>Here&#8217;s a quick getting started guide for the maven-db-migration-plugin:</p>
<h4>Step 1: Configure maven in your project&#8217;s pom.xml</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;build<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   ...
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.carbonfive<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>maven-db-migration-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>RELEASE<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jdbc:mysql://localhost/myapp_test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>dev<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>dev<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependencies<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>mysql<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>mysql-connector-java<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>5.1.6<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependencies<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/build<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pluginRepositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pluginRepository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>c5-public-repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://mvn.carbonfive.com/public<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pluginRepository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pluginRepositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></td></tr></table></div>

<p>Lines 29-31 configure the database connection (see the <a href="http://code.google.com/p/c5-db-migration/wiki/MavenPlugin">reference</a> for more options).<br />
Lines 35-39 specify the required dependency on our database driver.<br />
Lines 43-48 adds the Carbon Five maven plugin repository.</p>
<h4>Step 2: Create a migration script</h4>
<p>In src/main/db/migrations, create a script using the format YYYYMMDDHHMMSS.sql (e.g. 20080830174515.sql).  Example:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> users <span style="color: #66cc66;">&#40;</span>
  id INT <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span><span style="color: #66cc66;">,</span>
  email VARCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">255</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  password VARCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">255</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
  enabled <span style="color: #993333; font-weight: bold;">BOOLEAN</span> <span style="color: #993333; font-weight: bold;">DEFAULT</span> <span style="color: #ff0000;color: blue;">'TRUE'</span>
<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<h4>Step 3: Create the database</h4>
<p><b>$ mvn db-migration:create</b></p>
<p>The supplied credentials must have the appropriate privileges, of course.  If you&#8217;re not using MySQL or PostgreSQL, then do this step manually.</p>
<h4>Step 4: Check the status of the database</h4>
<p><b>$ mvn db-migration:validate</b></p>
<p>Your migration will be listed as pending and the database as not up-to-date.</p>
<h4>Step 5: Migrate to the latest version</h4>
<p><b>$ mvn db-migration:migrate</b></p>
<p>The pending migration will be applied to the database and logged in the schema_version table.</p>
<h4>Want to learn more?</h4>
<p>Check out the <a href="http://code.google.com/p/c5-db-migration/">google code project page</a>, the <a href="http://code.google.com/p/c5-db-migration/wiki/ReleaseNotes">release notes</a> and the <a href="http://code.google.com/p/c5-db-migration/wiki/SampleApplications">sample applications</a>.</p>
<p>In the near future, I&#8217;m going to look at supporting MS SQL Server and improving the SQL Script Runner.  Thanks for all of the feedback and please keep it coming!</p>
<p>Christian</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/09/java/java-database-migrations/feed</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Database Testing with Spring 2.5 and DBUnit</title>
		<link>http://blog.carbonfive.com/2008/07/testing/database-testing-with-spring-25-and-dbunit</link>
		<comments>http://blog.carbonfive.com/2008/07/testing/database-testing-with-spring-25-and-dbunit#comments</comments>
		<pubDate>Thu, 31 Jul 2008 22:31:18 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog/?p=30</guid>
		<description><![CDATA[Note: Version 0.9.1 of c5-test-support has been released. We&#8217;ve been using DB Unit on our Java projects for years and the mechanics of how it&#8217;s used has evolved over time. I&#8217;ve recently spent some time making it work a little nicer for how we typically write database tests. What I&#8217;ve created makes using DBUnit on [...]]]></description>
			<content:encoded><![CDATA[<p><em>Note: Version 0.9.1 of c5-test-support has been released.</em></p>
<p>We&#8217;ve been using <a href="http://www.dbunit.org">DB Unit</a> on our Java projects for years and the mechanics of how it&#8217;s used has evolved over time.  I&#8217;ve recently spent some time making it work a little nicer for how we typically write database tests.  What I&#8217;ve created makes using DBUnit on a project that is already using Spring and the testing support added in Spring 2.5 just a little easier through the application of convention and annotations.</p>
<p>In general, we&#8217;ve adopted the convention of loading data off the classpath from a flat dataset file named after the test located next to the test on the classpath.  For example (in the maven standard directory structure):</p>
<ul>
<li>src/test/java/com/acme/TripRepositoryTest.java &#8211; Java Test Code</li>
<li>src/test/resources/com/acme/TripRepositoryTest.xml &#8211; DB Unit Data Set for TripRepositoryTest</li>
</ul>
<p>For most tests, the data set is loaded inside the test&#8217;s transaction and rolled back when the test completes so that nothing needs to be cleaned up (see <a href="http://www.springframework.net/doc-latest/reference/html/testing.html#testing-tx">Spring&#8217;s reference</a>).  For other tests &#8212; service or integration tests &#8212; the data is loaded outside of a transaction and must be cleared out manually.  Most projects have a mix of both strategies and both should be easily supported.</p>
<p>When Spring 2.5 came out with its <a href="http://static.springframework.org/spring/docs/2.5.x/reference/new-in-2.html#new-in-2-other-testing">new testing framework</a>, I threw together a custom TestExecutionListener that looks for test methods that are annotated with @DataSet, and when found, loads the data using DB Unit.  Here&#8217;s a transaction-per-test example:</p>
<h4>TripRepositoryImplTest.java &#8211; Example transaction-per-test Test Case</h4>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@ContextConfiguration<span style="color: #009900;">&#40;</span>locations = <span style="color: #009900;">&#123;</span><span style="color: #0000ff;color: blue;">&quot;classpath:applicationContext.xml&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TripRepositoryImplTest <span style="color: #000000; font-weight: bold;">extends</span> AbstractTransactionalDataSetTestCase <span style="color: #009900;">&#123;</span>
    @Autowired TripRepository repository<span style="color: #339933;">;</span>
&nbsp;
    @Test
    @DataSet
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> forIdShouldFindTrip<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span> <span style="color: #009900;">&#123;</span>
        Trip trip = repository.<span style="color: #006633;">forId</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertThat<span style="color: #009900;">&#40;</span>trip, not<span style="color: #009900;">&#40;</span>nullValue<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The high-level execution path for this example looks like:</p>
<ol>
<li>Inject dependencies (DependencyInjectionTestExecutionListener)</li>
<li>Start transaction (TransactionalTestExecutionListener)</li>
<li>Load dbunit data set from TripRepositoryImplTest.xml (DataSetTestExecutionListener) using the setup operation (default is CLEAN_INSERT)</li>
<li>Execute test</li>
<li>Optionally cleanup dbunit data using the tear down operation (default is NONE)</li>
<li>Rollback transaction (TransactionalTestExecutionListener)</li>
</ol>
<p>Here&#8217;s the trimmed down log output for this test:</p>

<div class="wp_syntax"><div class="code"><pre class="apache" style="font-family:monospace;">INFO: Began transaction (<span style="color: #ff0000;">1</span>): transaction manager; rollback [true] (TransactionalTestExecutionListener.java:<span style="color: #ff0000;">259</span>)
INFO: Loading dataset <span style="color: #00007f;">from</span> <span style="color: #00007f;">location</span> <span style="color: #7f007f;color: blue;">'classpath:/eg/domain/TripRepositoryImplTest.xml'</span> using operation <span style="color: #7f007f;color: blue;">'CLEAN_INSERT'</span>. (DataSetTestExecutionListener.java:<span style="color: #ff0000;">152</span>)
INFO: Tearing down dataset using operation <span style="color: #7f007f;color: blue;">'NONE'</span>, leaving database connection open. (DataSetTestExecutionListener.java:<span style="color: #ff0000;">67</span>)
INFO: Rolled back transaction after test execution for test context (TransactionalTestExecutionListener.java:<span style="color: #ff0000;">279</span>)</pre></div></div>

</p>
<p>For this to work in its current incarnation, a single datasource must be available for lookup in the application context.  One of the interesting details is what to do with the connection used to load the data.  The framework assumes that if it&#8217;s a transactional connection it should be left open because whatever started the transaction should do the closing.  When it&#8217;s non-transactional it&#8217;s closed after the dataset is loaded.  This convention works well for how I typically write my database tests.</p>
<p>In addition to the @DataSet annotation, we must add the DataSetTestExecutionListener to the set of listeners that are applied to the test class.  As in the above example, you can extend AbstractTransactionalDataSetTestCase which does this for you or you can specify the listener using the class-level annotation @TestExecutionListeners (see <a href="http://svn.carbonfive.com/public/christian/spring-dbunit-test-extension/trunk/src/test/java/eg/domain/TripServiceImplTest.java">example</a>).  It&#8217;s important that the listener is triggered after the TransactionalTestExecutionListener.</p>
<p>If all test methods use the dataset, then the test class (or super class) can be annotated and every test will load the dataset.  Also, if a different dataset should be loaded, the name of the resource can be specified in the annotation (e.g. @DataSet(&#8220;TripRepositoryImplTest-foo.xml&#8221;) or @DataSet(&#8220;classpath:/db/trips.xml&#8221;)).  Lastly, the setup and teardown database operations can be overriden (e.g. @DataSet(setupOperation = &#8220;INSERT&#8221;, teardownOperation=&#8221;DELETE&#8221;)).</p>
<p>This functionality is part of the C5 Test Support package and is available in our maven repository.  To use it, first add the C5 Public Maven repository to your pom.xml, and then add the necessary dependencies:</p>
<h4>pom.xml</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;repositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;repository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>c5-public-repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://mvn.carbonfive.com/public<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;snapshots<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;updatePolicy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>always<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/updatePolicy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/snapshots<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/repository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/repositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependencies<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.dbunit<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>dbunit<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>2.2.3<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;scope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/scope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.carbonfive<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test-support<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0.6<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;scope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/scope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependencies<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</p>
<p>Check out the <a href="http://svn.carbonfive.com/public/christian/spring-dbunit-test-extension/trunk">sample application</a> for details.  It&#8217;s mavenized and utilizes an in-memory database.  Just check it out of subversion, look over the code, and give it a run using your IDE or from the command-line (mvn install).  I&#8217;d be psyched to hear what you think and of course, welcome comments and suggestions.</p>
<h4>Resources:</h4>
<ul>
<li>C5 Test Support Source: <a href="http://svn.carbonfive.com/public/carbonfive/test-support/trunk">http://svn.carbonfive.com/public/carbonfive/test-support/trunk</a></li>
<li>C5 Test Support Maven Home: <a href="http://mvn.carbonfive.com/public/com/carbonfive/test-support/0.6/">http://mvn.carbonfive.com/public/com/carbonfive/test-support/0.6/</a></li>
<li>Sample Application: <a href="http://svn.carbonfive.com/public/christian/spring-dbunit-test-extension/trunk">http://svn.carbonfive.com/public/christian/spring-dbunit-test-extension/trunk</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/07/testing/database-testing-with-spring-25-and-dbunit/feed</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Multithreaded Testing</title>
		<link>http://blog.carbonfive.com/2008/05/testing/multithreaded-testing</link>
		<comments>http://blog.carbonfive.com/2008/05/testing/multithreaded-testing#comments</comments>
		<pubDate>Mon, 05 May 2008 22:06:42 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog/?p=29</guid>
		<description><![CDATA[Every now and then you&#8217;ll work on something that needs to handle requests from multiple concurrent threads in a special way. I say &#8220;special way&#8221; because in a web application, everything needs to handle being executed concurrently and there are a slew of techniques used to handle this (prototypes, thread locals, stateless services, etc). Here&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Every now and then you&#8217;ll work on something that needs to handle requests from multiple concurrent threads in a special way.  I say &#8220;special way&#8221; because in a web application, <i>everything</i> needs to handle being executed concurrently and there are a slew of techniques used to handle this (prototypes, thread locals, stateless services, etc).  Here&#8217;s an example of what I mean by &#8220;special&#8221;&#8230;</p>
<p>On my current project, we have a queue of articles that need human-user attention (i.e. editorial moderation).  Each article must be doled out to only one moderator and there are multiple instances of the web application servicing requests in the cluster.  Imagine tens of thousands of articles per day and a team of moderators churning through them.  We can&#8217;t rely on Java synchronization because it only works within the JVM instance, not across server instances.</p>
<p>The simplified version of the service interface we&#8217;re working on looks like this:</p>
<h4>ArticleService.java &#8211; Example service interface</h4>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> ArticleService
<span style="color: #009900;">&#123;</span>
    Article findNextArticleForModeration<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>What makes this interesting is that we must ensure that the service doesn&#8217;t hand out the same Article to more than one user.  This is impossible to assert using a single thread.  We&#8217;ve all been told that multiple threads and automated testing don&#8217;t mix.  It&#8217;s generally true and should be avoided if at all possible, but in some cases it&#8217;s the only way we can truly assert specific behavior.  I&#8217;ve found a pretty simple way to do this type of testing in a reliable, consistent, and non-disruptive manner.  Despite the fact that the technique leverages Java 1.5 built-in concurrency utilities, most of the engineers who have seen it are surprised and weren&#8217;t aware that such testing was so easy to implement.</p>
<p>Given the above service interface, here&#8217;s a test that will assert that no single article is given out to more than one invoker of the method findNextArticleForModeration().  The scenario we&#8217;re simulating is 10 users feverishly moderating a queue of 250 articles as quickly as possible.</p>
<h4>ArticleServiceImplTest.java &#8211; Test to invoke service concurrently</h4>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">...
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> findNextArticleForModerationStressTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #006600; font-weight: bold;">int</span> ARTICLE_COUNT = <span style="color: #cc66cc;">250</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #006600; font-weight: bold;">int</span> THREAD_COUNT = <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Create test data and callable tasks</span>
    <span style="color: #666666; font-style: italic;">//</span>
    Set<span style="color: #339933;">&lt;</span>Article<span style="color: #339933;">&gt;</span> testArticles = <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>Article<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    Collection<span style="color: #339933;">&lt;</span>Callable<span style="color: #339933;">&lt;</span>Article<span style="color: #339933;">&gt;&gt;</span> tasks = <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>Callable<span style="color: #339933;">&lt;</span>Article<span style="color: #339933;">&gt;&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000;  font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #006600; font-weight: bold;">int</span> i = <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> ARTICLE_COUNT<span style="color: #339933;">;</span> i++<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// Test data</span>
        testArticles.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Article<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// Tasks - each task makes exactly one service invocation.</span>
        tasks.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Callable<span style="color: #339933;">&lt;</span>Article<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">public</span> Article call<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> articleService.<span style="color: #006633;">findNextArticleForModeration</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    articleService.<span style="color: #006633;">createArticles</span><span style="color: #009900;">&#40;</span>testArticles<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Execute tasks</span>
    <span style="color: #666666; font-style: italic;">//</span>
    <span style="color: #003399; font-weight: bold;">ExecutorService</span> executorService = <span style="color: #003399; font-weight: bold;">Executors</span>.<span style="color: #006633;">newFixedThreadPool</span><span style="color: #009900;">&#40;</span>THREAD_COUNT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// invokeAll() blocks until all tasks have run...</span>
    List<span style="color: #339933;">&lt;</span>Future<span style="color: #339933;">&lt;</span>Article<span style="color: #339933;">&gt;&gt;</span> futures = executorService.<span style="color: #006633;">invokeAll</span><span style="color: #009900;">&#40;</span>tasks<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>futures.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, is<span style="color: #009900;">&#40;</span>ARTICLE_COUNT<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Assertions</span>
    <span style="color: #666666; font-style: italic;">//</span>
    Set<span style="color: #339933;">&lt;</span>Long<span style="color: #339933;">&gt;</span> articleIds = <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>Long<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>ARTICLE_COUNT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000;  font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Future<span style="color: #339933;">&lt;</span>Article<span style="color: #339933;">&gt;</span> future : futures<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// get() will throw an exception if an exception was thrown by the service.</span>
        Article article = future.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// Did we get an article?</span>
        assertThat<span style="color: #009900;">&#40;</span>article, not<span style="color: #009900;">&#40;</span>nullValue<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// Did the service lock the article before returning?</span>
        assertThat<span style="color: #009900;">&#40;</span>article.<span style="color: #006633;">isLocked</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, is<span style="color: #009900;">&#40;</span><span style="color: #006600; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// Is the article id unique (see Set.add() javadoc)?</span>
        assertThat<span style="color: #009900;">&#40;</span>articleIds.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>article.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>, is<span style="color: #009900;">&#40;</span><span style="color: #006600; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #666666; font-style: italic;">// Did we get the right number of article ids?</span>
    assertThat<span style="color: #009900;">&#40;</span>articleIds.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, is<span style="color: #009900;">&#40;</span>ARTICLE_COUNT<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
...</pre></div></div>

<p>The test starts off by creating 250 test articles to be moderated.  It also creates 250 &#8216;tasks&#8217;, each designed to make a single service invocation of findNextArticleForModeration().  The real magic happens in <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)">Executors.newFixedThreadPool()</a> and <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection)">executorService.invokeAll()</a>.  The first creates a new <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html">ExecutorService</a> backed by a thread pool of the specified size.  This is a generic ExecutorService that is designed to churn through tasks using all of the threads in the pool.  invokeAll blocks until every task has finished executing.  In this test, 10 threads will rip through 250 tasks, each making a single call to our service and capturing the result of that call.  Each task execution results in a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html">Future</a>, which is a handle to the results of the task (and more).</p>
<p>Iterating over each resulting future, we make several assertions.  The most important one is the last, where we assert that every task is given a unique Article.  Thanks to the natural semantics of Set, this is easy to do in an elegant way.  Another useful, though unexpected, feature is that if an exception occurs during the task execution, an <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutionException.html">ExecutionException</a> will be thrown when <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html#get()">get()</a> is called on the corresponding Future.  If our service fails for some reason, the test will fail because no exceptions are expected.</p>
<p>This technique makes simulating a multi-threaded environment in a test easy and readable.  It&#8217;s important to only use this technique when it&#8217;s <em>really</em> necessary.  The resulting test is more of an integration test than a unit test, and its run time is orders of magnitude more than a unit test, so overuse of the technique will artificially inflate the time it takes to runs the tests.  After I&#8217;ve finished working on the component under test, I will reduce the test-data size and thread count to a level that the test still provides value, but is no longer a stress test (e.g. 10 articles and 2 threads).  The next time the component is being worked on, the developer can crank up the values and run the tests to be confident that the behavior isn&#8217;t broken.</p>
<p>The complete source for a working example of this technique is available <a href="http://svn.carbonfive.com/public/christian/multi-threaded-testing/trunk">here</a>.  You&#8217;ll need Maven (or IntelliJ IDEA 7.x) to build and run the test.  By default, the tests run against an in-memory H2Database instance, but if you look at application.properties you&#8217;ll see configurations for PostgreSQL and MySQL as well.</p>
<p>Happy testing!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/05/testing/multithreaded-testing/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Configuring applications with Spring</title>
		<link>http://blog.carbonfive.com/2008/04/java/configuring-applications-with-spring</link>
		<comments>http://blog.carbonfive.com/2008/04/java/configuring-applications-with-spring#comments</comments>
		<pubDate>Fri, 25 Apr 2008 17:57:31 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog/?p=28</guid>
		<description><![CDATA[If you&#8217;ve used Spring before, you&#8217;ve almost definitely used a PropertyPlaceholderConfigurer to inject settings from external sources &#8212; most likely properties files &#8212; into your application context. The most common use cases include JDBC and Hibernate settings, but it&#8217;s not that uncommon to also configure Lucene index, temp file, or image cache directories as well. [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve used Spring before, you&#8217;ve almost definitely used a PropertyPlaceholderConfigurer to inject settings from external sources &#8212; most likely properties files &#8212; into your application context.  The most common use cases include JDBC and Hibernate settings, but it&#8217;s not that uncommon to also configure Lucene index, temp file, or image cache directories as well.  The simplest case looks something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;classpath:application.properties&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #808080; font-style: italic;">&lt;!-- A sample bean that needs some settings. --&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;color: blue;">&quot;dataSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;driverClassName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${jdbc.driver}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${jdbc.url}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;username&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${jdbc.username}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${jdbc.password}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>And application.properties might look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">jdbc.<span style="color: #006633;">driver</span>=org.<span style="color: #006633;">h2</span>.<span style="color: #003399; font-weight: bold;">Driver</span>
jdbc.<span style="color: #006633;">url</span>=jdbc:h2:mem:example
jdbc.<span style="color: #006633;">username</span>=sa
jdbc.<span style="color: #006633;">password</span>=</pre></div></div>

<p>Note, you can achieve the same simple configuration using the new spring 2.x style schema configuration, but it doesn&#8217;t allow for any further customization so we&#8217;re going to use the old style.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">&lt;!-- Example of new Spring 2.x style --&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:property-placeholder</span> <span style="color: #000066;">location</span>=<span style="color: #ff0000;color: blue;">&quot;classpath:application.properties&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>This handles the simple case of replacing placeholders (e.g. ${jdbc.url}) with values found in a properties files (e.g. jdbc.url=jdbc:h2:mem:example).  In a real-world application, we not only need to collect settings, but also override them in different environments.  Many of our applications are deployed in 4 or more environments (developer machine, build server, staging server, and production), each requiring different databases at the very least.</p>
<p>There are a few ways to enable overriding of properties.  Let&#8217;s take a look at them in turn:</p>
<h4>1. Setting the system properties mode to override (default is fallback)</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;systemPropertiesModeName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;SYSTEM_PROPERTIES_MODE_OVERRIDE&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;classpath:application.properties&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>When configured in this mode, any value specified as a system property to the JVM will override any values set in properties files.  For example, adding -Djdbc.url=jdbc:h2:mem:cheesewhiz to the JVM arguments would override the value in the file (jdbc:h2:mem:example).  On a Java 1.5 or newer platform, Spring will also look for an environment variable called jdbc.url is no system property was found.</p>
<h4>2. Specifying an optional properties file</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;ignoreResourceNotFound&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;locations&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>classpath:application.properties<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>classpath:local.properties<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>When <i>ignoreResourceNotFound</i> is set to true, Spring will ignore resources that don&#8217;t exist.  You can imagine application.properties, containing all of the default settings, versioned in your SCM system.  Developers have the option of creating a properties file called local.properties to override any settings that differ in their environment.  This file should be unversioned and ignored by your SCM system.  This works because properties are loaded in order and replace previous values.</p>
<h4>3. Web Application overrides</h4>
<p>In a web application environment, Spring also supports specifying values in web.xml as context params or in your application server specific meta-data as servlet attributes.  For example, if you&#8217;re using Tomcat you can specify one or more parameter elements in your context.xml, and Spring will can inject those values into placeholders.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;classpath:application.properties&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The ServletContextPropertyPlaceholderConfigurer conveniently works in non servlet environments by falling back to the behavior of a PropertyPlaceholderConfigurer.  This is great when running unit tests.</p>
<h4>4. Combining techniques</h4>
<p>There&#8217;s no reason why these techniques can&#8217;t be combined.  Technique #1 is great for overriding a few values while #2 is better for overriding many.  #3 just expands the field of view when Spring goes to resolve placeholders.  When combined, system properties override those in files.  When using technique #3, there are some settings available for adjusting the override behavior (see contextOverride).  Test the resolution order when combining to ensure it&#8217;s behaving as expected.</p>
<h4>Optional External Properties</h4>
<p>There&#8217;s another use case that applies to some projects.  Often in non-developer environments, system admins want to keep properties for the environment outside of the deployable archive or the application server, and they don&#8217;t want to deal with keeping those files in a Tomcat context file; they prefer a simple properties file.  They also don&#8217;t want to have to place the file in a hard-coded location (e.g. /var/acmeapp/application.properties) or they may keep configuration for multiple servers in the same network directory, each file names after the server.  With a little trickery, it&#8217;s easy to support an optional external properties file that isn&#8217;t in a hard-coded location.  The location of the file is passed as a single system property to the JVM, for example: -Dconfig=file://var/acmeapp/server1.properties.  Here&#8217;s the configuration to make it happen:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;ignoreUnresolvablePlaceholders&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;ignoreResourceNotFound&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;${config}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The first definition enables basic property resolution through system properties (in fallback mode).  The second bean loads the resource from the location resolved from the system property -Dconfig.  All spring resource urls are supported, making this very flexible.</p>
<h4>Putting it all together</h4>
<p>Here&#8217;s a configuration that does more than most people would need, but allows for ultimate flexibility:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;ignoreUnresolvablePlaceholders&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;systemPropertiesModeName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;SYSTEM_PROPERTIES_MODE_OVERRIDE&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;searchContextAttributes&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;contextOverride&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;ignoreResourceNotFound&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;locations&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>classpath:application.properties<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>classpath:local.properties<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>${config}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Every placeholder goes through the following resolution process.  Once a value is found it&#8217;s set and the next placeholder is resolved:</p>
<ol>
<li>(optional) Property value specified as a system or environment property; useful for overriding specific placeholders (e.g. -Djdbc.host=devdb / -Djdbc.username=carbon5)</li>
<li>(optional) Context parameters located in web.xml or context attributes specified in application server meta-data (e.g. a Tomcat context.xml).</li>
<li>(optional) Properties file located by the system/environment variable called &#8220;config&#8221;; useful for externalizing configuration.  All URL types are supported (e.g. -Dconfig=c://hmc.properties).</li>
<li>(optional) Properties file identified by classpath:local.properties; useful for specific developer overrides.</li>
<li>(required) Properties file identified by classpath:application.properties, which contains default settings for our application.</li>
</ol>
<h4>Best Practices</h4>
<ul>
<li>Deploy the same exact artifact (e.g. war, ear, etc) across all environments by externalizing configuration.  This may seem daunting, but the emergent benefits are huge in terms of simplicity.</li>
<li>Only make things that can safely change across environments configurable.  Also, only things that need to be configurable should be configurable, it&#8217;s easy to go overboard.</li>
<li>Configure the minimal properties search path that meets your requirements.</li>
<li>When looking for properties files in the project tree, use classpath resources whenever possible.  This makes finding those files easy, consistent, and insensitive to the working-dir, which is great when running tests from your IDE and command line.</li>
<li>Aim for a zero-configuration check-out, build, run-tests cycle for the environment where its happens most: development.</li>
</ul>
<p>What other interesting configuration scenarios have you seen?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/04/java/configuring-applications-with-spring/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Injecting Spring 2.5 beans into Stripes Actions</title>
		<link>http://blog.carbonfive.com/2008/03/java/injecting-spring-25-beans-into-stripes-actions</link>
		<comments>http://blog.carbonfive.com/2008/03/java/injecting-spring-25-beans-into-stripes-actions#comments</comments>
		<pubDate>Thu, 27 Mar 2008 16:52:25 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog/?p=27</guid>
		<description><![CDATA[I&#8217;ve been playing around with Stripes, a light-weight, well-designed simple Java web MVC framework recently. I haven&#8217;t had the pleasure of working with it on a production application yet, but hope to sometime soon. Meanwhile, I&#8217;ve been tinkering on a pet project. As you may know, we often use Spring for lifecycle management of our [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing around with <a href="http://www.stripesframework.org">Stripes</a>, a light-weight, well-designed simple Java web MVC framework recently.  I haven&#8217;t had the pleasure of working with it on a production application yet, but hope to sometime soon.  Meanwhile, I&#8217;ve been tinkering on a pet project.</p>
<p>As you may know, we often use <a href="http://springframework.org/">Spring</a> for lifecycle management of our services and dependency injection (among other uses).  In a Stripes + Spring application, you can imagine Spring-managed services being used by Stripes Actions (i.e. controllers).  Every incoming HTTP request results in a new instance of a Stripes Action, thus the newly created actions must have their dependencies injected for every request.</p>
<p>Stripes ships with a <a href="http://stripes.sourceforge.net/docs/current/javadoc/index.html?net/sourceforge/stripes/integration/spring/SpringInterceptor.html">SpringInterceptor</a> that supports annotating fields and methods on your actions with <a href="http://stripes.sourceforge.net/docs/current/javadoc/net/sourceforge/stripes/integration/spring/SpringBean.html">@SpringBean</a>.  While this works fine, I was pretty interested in being able to use Spring 2.5&#8242;s annotations for marking what should be injected on my actions, so I created a Spring25Interceptor (see code below).</p>
<p>The Spring25Interceptor is configured the same way as the out-of-the-box SpringInterceptor.  In your web.xml:</p>
<h4>web.xml</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;display-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Stripes Filter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/display-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>StripesFilter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>net.sourceforge.stripes.controller.StripesFilter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;init-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Interceptor.Classes<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            net.sourceforge.stripes.integration.spring.Spring25Interceptor
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param-value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/init-param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>Since it uses the same annotations that Spring 2.5&#8242;s supports (<a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/Autowired.html">@Autowired</a>, @Resource, and <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/Qualifier.html">@Qualifier</a>), annotating your Stripes Actions is easy and should look pretty familiar (see <a href="http://blog.springsource.com/main/2008/01/28/spring-25s-comprehensive-annotation-support/">Juergen&#8217;s blog</a> for a comprehensive overview).  Here are a few hypothetical examples:</p>
<h4>LandingActionBean.java</h4>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> LandingActionBean <span style="color: #000000; font-weight: bold;">extends</span> AbstractActionBean
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Autowire by type (looks for a bean in the application context of type ServiceA)</span>
    @Autowired ServiceA serviceA<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Autowire by name (looks for a bean with the name 'serviceB')</span>
    @Resource ServiceB serviceB<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Autowire by name (looks for a bean with the name 'serviceC')</span>
    @Autowired @Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;serviceC&quot;</span><span style="color: #009900;">&#41;</span> ServiceC serviceCee<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Method injection examples (all of the above can be applied to methods as well)</span>
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> setServiceA<span style="color: #009900;">&#40;</span>ServiceA a<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">serviceA</span> = a<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
    @Autowired
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> setServices<span style="color: #009900;">&#40;</span>ServiceA a, ServiceB b, ServiceC c<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">serviceA</span> = a<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">serviceB</span> = b<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">serviceC</span> = c<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @<span style="color: #003399; font-weight: bold;">DefaultHandler</span>
    <span style="color: #000000; font-weight: bold;">public</span> Resolution execute<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> ForwardResolution<span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;/landing.jsp&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>While it may be considered a subtle improvement, I really like the fact that with this new interceptor, my application has a consistent syntax for dependency injection across the tiers.  Additionally, the semantics of the Spring annotations are also consistent and shared throughout.  An added bonus is that the new Interceptor is significantly smaller than the existing one.</p>
<p>Here&#8217;s the Interceptor code that does the dependency injection into actions:</p>
<h4>Spring25Interceptor.java</h4>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">net.sourceforge.stripes.action.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">net.sourceforge.stripes.controller.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">net.sourceforge.stripes.util.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.beans.factory.config.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.context.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.util.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.web.context.support.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.servlet.*</span><span style="color: #339933;">;</span>
&nbsp;
@Intercepts<span style="color: #009900;">&#40;</span>LifecycleStage.<span style="color: #006633;">ActionBeanResolution</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Spring25Interceptor <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399; font-weight: bold;">Interceptor</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Log log = Log.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span>Spring25Interceptor.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Resolution intercept<span style="color: #009900;">&#40;</span>ExecutionContext context<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span>
    <span style="color: #009900;">&#123;</span>
        Resolution resolution = context.<span style="color: #006633;">proceed</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        log.<span style="color: #006633;">debug</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Running Spring dependency injection for instance of &quot;</span>, context.<span style="color: #006633;">getActionBean</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getSimpleName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        ServletContext servletContext = StripesFilter.<span style="color: #006633;">getConfiguration</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getServletContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        ApplicationContext applicationContext = WebApplicationContextUtils.<span style="color: #006633;">getWebApplicationContext</span><span style="color: #009900;">&#40;</span>servletContext<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        AutowireCapableBeanFactory beanFactory = applicationContext.<span style="color: #006633;">getAutowireCapableBeanFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        beanFactory.<span style="color: #006633;">autowireBeanProperties</span><span style="color: #009900;">&#40;</span>context.<span style="color: #006633;">getActionBean</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, AutowireCapableBeanFactory.<span style="color: #006633;">AUTOWIRE_NO</span>, <span style="color: #006600; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        beanFactory.<span style="color: #006633;">initializeBean</span><span style="color: #009900;">&#40;</span>context.<span style="color: #006633;">getActionBean</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, StringUtils.<span style="color: #006633;">uncapitalize</span><span style="color: #009900;">&#40;</span>context.<span style="color: #006633;">getActionBean</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getSimpleName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> resolution<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I&#8217;ve created a <a href="http://www.stripesframework.org/jira/browse/STS-520">enhancement request</a> for this feature, though the comment-thread is a little bit all over the place.  You can find the latest version of the code and Javadoc as an attachment on the issue.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/03/java/injecting-spring-25-beans-into-stripes-actions/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing Java DB Migrations</title>
		<link>http://blog.carbonfive.com/2008/02/java/introducing-java-db-migrations</link>
		<comments>http://blog.carbonfive.com/2008/02/java/introducing-java-db-migrations#comments</comments>
		<pubDate>Wed, 06 Feb 2008 23:42:56 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog/?p=23</guid>
		<description><![CDATA[UPDATE: A new version of the Java DB Migrations framework has been release, check this post for details and the project documentation.]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE:</strong> A new version of the Java DB Migrations framework has been release, check <a href="http://blog.carbonfive.com/2008/09/java/java-database-migrations">this post</a> for details and the <a href="http://code.google.com/p/c5-db-migration">project documentation</a>.</P</p>
<p>Here at Carbon Five we have the luxury of working on many projects, so anything we can do to make things easier will pay off in multiplicity across new projects.  One of the things that we have to deal with on every project is maintaining a database schema over time.  We’ve had a manual process of capturing changes in incremental db patch scripts for a while, but it was error prone and sometimes neglected.  We’ve been doing more Ruby on Rails work and found <a href="http://wiki.rubyonrails.org/rails/pages/UnderstandingMigrations">Rails Migrations</a> easy to work with and a real time saver.  We wanted something that would make our lives easier when working on Java projects in the same way Migrations improve Rails development.  With that manifest in mind, Alon and I collaborated on a simple Java database migration framework.</p>
<p>During development, it’s a big deal because each engineer has two instances of the database, one for unit tests and another for running the application.  We need an easy way to create a new, up-to-date database and update existing databases.  Once a project has launched, it’s a big deal because we need a way to migrate a database teeming with important production data to the latest version without losing critical information.</p>
<p>High Level Requirements</p>
<ul>
<li>Initiate a migration from the command-line as a Maven plugin</li>
<li>Programmatically migrate a database during application startup</li>
<li>Convention over Configuration</li>
<li>Initially support migrations written in SQL</li>
</ul>
<p>At a high level, the migration process looks like this:</p>
<ol>
<li>Query the database (table db_version) to find the current version.</li>
<li>Determine the latest database schema version available.</li>
<li>If the database is out of date, run each migration in order in its own transaction, updating the db_version for each migration.</li>
</ol>
<p>We’d identified two usage patterns, the first is more akin to the Rails Migration model in that you explicitly migrate the database via the command line.  The second is automatic migration when an application starts up, before Hibernate initializes or any other data access takes place.  I’ll<br />
discuss each in turn.</p>
<h3>Migrating using Maven</h3>
<p>This functionality is easy to enable in a mavenized project. First you add the Carbon Five public plugin repository:</p>
<h4>pom.xml</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pluginRepositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pluginRepository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>c5-public-repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://mvn.carbonfive.com/public<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pluginRepository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/pluginRepositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>And then you configure the migration plugin:</p>
<h4>pom.xml</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.carbonfive<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>maven-migration-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0.9-SNAPSHOT<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;defaultEnvironment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/defaultEnvironment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;environments<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;environment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>default<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;driver<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.mysql.jdbc.Driver<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/driver<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>dev<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>dev<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/environment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;environment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jdbc:mysql://localhost/myapp_test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/environment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;environment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>development<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jdbc:mysql://localhost/myapp_development<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/environment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/environments<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependencies<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>mysql<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>mysql-connector-java<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>5.1.5<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependencies<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>You’ll notice that we’ve got 2 environments configured.  You can have as many as you need and you can specify which you want to migrate on the command line.  If none are specified the default environment will be migrated.  In this example we’re specifying the dependency on our JDBC driver so that the plugin has access to the code it needs to connect the database.</p>
<p>Lastly, you drop in your migration scripts into the src/main/resources/db/migrations directory, naming them using the pattern NNN_description.sql, where NNN is three digits indicating the script sequence.  Some examples might be:</p>
<ul>
<li>001_create_users_table.sql</li>
<li>002_add_default_users.sql</li>
<li>003_add_lastvisit_column.sql</li>
</ul>
<p>The description is optional and isn’t used for anything, it’s just there so that other developers can get an idea of what a script does without having to open it.</p>
<p>From the command line, you can run the migration plugin like this:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ mvn migration:migrate</pre></div></div>

<p>Note that he database must exist for the migrations to take place as we do not create missing databases (yet).</p>
<p>I’ve created a simple, complete sample that shows off this functionality, it’s on the C5 public subversion repository <a href="https://svn.carbonfive.com/public/christian/migration-sample1/trunk">here</a>. Check it out and then read the readme.txt at the top of the project.</p>
<h3>Migrating from your Application</h3>
<p>The other usage scenario is to auto-migrate during application startup.  At the core of the framework, there’s an interface called MigrationManager which has two implementations: DataSourceMigrationManager and DriverManagerMigrationManager. Migration happens right after a datasource (of the javax.sql variety) is created.</p>
<p>Migrating from your application is as easy as instantiating one of these early in the startup cycle and invoking the migrate() method, something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">MigrationManager migrationManager = <span style="color: #000000; font-weight: bold;">new</span>
    DriverManagerMigrationManager<span style="color: #009900;">&#40;</span>“com.<span style="color: #006633;">mysql</span>.<span style="color: #006633;">jdbc</span>.<span style="color: #003399; font-weight: bold;">Driver</span>”,
    “jdbc:mysql:<span style="color: #666666; font-style: italic;">//localhost/myapp_test”, “dev”, “dev”);</span>
migrationManager.<span style="color: #006633;">migrate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Of course this needs to happen before anything else in the application uses the database; we want to database to be updated completely before it’s used.</p>
<p>Spring is part of our standard development stack on our Java projects, and it’s easy to enforce these dependencies in Spring configuration. First we define a data source for the application:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;color: blue;">&quot;dataSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;driverClassName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;org.h2.Driver&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;jdbc:h2:file:~/.h2/migration_sample2_test&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;username&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;dev&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;dev&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>And now we declare our MigrationManager instance.  Note the ‘init-method’ attribute:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;color: blue;">&quot;migrationManager&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;com.carbonfive.db.migration.DataSourceMigrationManager&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">init-method</span>=<span style="color: #ff0000;color: blue;">&quot;migrate&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;color: blue;">&quot;dataSource&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>And then you define something that’s going to use the defined DataSource.  Note the ‘depends-on’ attribute:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;color: blue;">&quot;userService&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;com.carbonfive.migration.sample2.UserService&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">depends-on</span>=<span style="color: #ff0000;color: blue;">&quot;migrationManager&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;color: blue;">&quot;dataSource&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>This is obviously a little contrived for the sake of example, but you get the point.  In a typical application the thing that would depend on the datasource is a Hibernate SessionFactory.</p>
<p>You can visit the source code for this example on the C5 public subversion repository <a<br />
href="https://svn.carbonfive.com/public/christian/migration-sample2/trunk">here</a>.</p>
<p><b>Best Practices</b></p>
<p>Here are a few of the things we’ve learned along the way:</p>
<ul>
<li>Start using migrations early.  Definitely start by time there’s more than one person on a project. I usually start off letting hibernate generate my schema while I’m experimenting with things, but as soon as I’m really working on features I’ll switch over to migrations.</li>
<li>All database changes are captured as a new migration.</li>
<li>Migration scripts cannot be changed once <b>anyone</b> has run them and make further changes in a new migrations.</li>
</ul>
<p><b>Source Code Access</b></p>
<p>The Carbon Five db-support project which contains all of this migration goodness is available on the C5 public subversion repository at <a href="https://svn.carbonfive.com/public/carbonfive/db-support/trunk">https://svn.carbonfive.com/public/carbonfive/db-support/trunk</a>. It’s a maven project and should compile and pass its tests out of the box.  I encourage you to look through the code and check out the tests.</p>
<p><b>Future</b></p>
<p>If you look through the code you’ll see some of what’s in store for this project.  We’ve got initial support for writing migrations in Groovy and JRuby and we’re thinking about added Java support as well.  We’re looking for feedback to drive the future direction of the project, so feel free to write us and let us know what you think.</p>
<blockquote></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/02/java/introducing-java-db-migrations/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>JRubyGems Release</title>
		<link>http://blog.carbonfive.com/2008/01/java/jrubygems-release</link>
		<comments>http://blog.carbonfive.com/2008/01/java/jrubygems-release#comments</comments>
		<pubDate>Fri, 04 Jan 2008 19:39:27 +0000</pubDate>
		<dc:creator>alon</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Ruby (on Rails)]]></category>

		<guid isPermaLink="false">http://blog/?p=20</guid>
		<description><![CDATA[I&#8217;m releasing a first version of JRubyGems. This post is documentation until I come up with something better. JRubyGems allows you to package RubyGems on your Java application classpath. It removes the file system dependencies on locally installed gems that get awkward when using JRuby and dependent gems in a Java environment. Usage Use JRubyGems [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m releasing a first version of JRubyGems. This post is documentation until I come up with something better.</p>
<p>JRubyGems allows you to package RubyGems on your Java application classpath. It removes the file system dependencies on locally installed gems that get awkward when using JRuby and dependent gems in a Java environment.</p>
<p><strong><a name="JRubyGems-Usage"></a>Usage</strong></p>
<p>Use JRubyGems as a replacement for RubyGems. Instead of</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;color: blue;">'rubygems'</span>
gem <span style="color:#996600;color: blue;">'activerecord'</span></pre></div></div>

<p>use</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;color: blue;">'jrubygems'</span>
gem <span style="color:#996600;color: blue;">'activerecord'</span></pre></div></div>

<p>Behind the scenes JRubyGems requires RubyGems and injects behavior specific to finding gems on the Java classpath if they are not already installed.</p>
<p>You make JRubyGems available to your application by putting the jar on your application classpath.</p>
<p><strong><a name="JRubyGems-GetIt"></a>Get It</strong></p>
<p>Source is available from Subversion at <a href="https://svn.carbonfive.com/public/carbonfive/jruby/jrubygems/trunk/">https://svn.carbonfive.com/public/carbonfive/jruby/jrubygems/trunk/</a>. The tests in <a href="https://svn.carbonfive.com/public/carbonfive/jruby/jrubygems/trunk/ruby/test/test_jrubygems.rb">ruby/test/test_jrubygems.rb</a> illustrate JRubyGems&#8217; behavior.</p>
<p>The jar at <a href="http://mvn.carbonfive.com/public/com/carbonfive/jruby/jrubygems/0.3/jrubygems-0.3.jar">http://mvn.carbonfive.com/public/com/carbonfive/jruby/jrubygems/0.3/jrubygems-0.3.jar</a> is all you need to try it out in your own scripts. With JRuby you can require jar files that are in your load path to get them on your classpath and make Ruby files in the jar available on your load path. So if I have a folder lib/ in my load path with the file lib/jrubygems-0.3.jar, I can use JRubyGems directly from a JRuby script with:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;color: blue;">'jrubygems-0.3.jar'</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;color: blue;">'jrubygems'</span></pre></div></div>

<p>Most Java applications using embedded Ruby will have their own classpath management strategy. Just make sure the JRubyGems jar gets on the classpath of your application. If you are using Maven, you can use JRubyGems from the Carbon Five repository:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;repositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;repository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>c5-public-repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Carbon Five Public Repository<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://mvn.carbonfive.com/public<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/repository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/repositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependencies<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.carbonfive.jruby<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jrubygems<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0.3<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependencies<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>If you are using Maven you can also require your JRuby dependency with:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.jruby<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jruby-complete<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.1RC1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><strong><a name="JRubyGems-PackagingGemDependencies"></a>Packaging Gem Dependencies</strong></p>
<p>JRubyGems expects a gem to be available on your application classpath as a .gem file (the distribution package for a gem) under the classpath location /gems. This means you can have a gems/ folder on your classpath with a bunch of .gem files in it, a jar with all your .gem files under /gems or a jar per .gem file with each file under /gems in each jar. (A limitation in the JDK&#8217;s ClassLoader.getResources method which only returns file system locations for a passed-in empty String prevented me from allowing .gem files in jar roots.)</p>
<p>For our migration application, I built a jar for each gem dependency and deployed it to our central Maven repository. My Maven build references these dependencies in my project POM just as I would a jar dependency.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.carbonfive.jruby.gems<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>activerecord<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.15.6<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>I just grabbed the .gem files from my local JRuby installation&#8217;s gem cache dir at jruby-1.1b1/lib/ruby/gems/1.8/cache/ to build these jars for now.</p>
<p><em>I like that <a href="http://raven.rubyforge.org/">Raven</a> takes exactly the opposite approach &#8211; managing jar dependencies as gems.</em></p>
<p><strong><a name="JRubyGems-Background"></a>Background</strong></p>
<p>Christian and I have a side project at Carbon Five to create a standard mechanism for managing database migrations for our Java projects. The first implementation defines a migration as a SQL script to be run against the target database. I thought it would be cool to support ActiveRecord migrations too, especially for providing an easy way to do the data migrations that accompany a schema change.</p>
<p>My prototype of this idea went well (more on that some other time) but I quickly ran into an issue with the gem dependency for &#8216;activerecord-jdbc-adapter&#8217; and its dependencies &#8216;activesupport&#8217; and &#8216;activerecord&#8217;. The issue is that my Java project was nicely portable but the gems create a dependency on the runtime system having specific gems installed. If I install the gems locally, I also have to install them on other runtime systems like our continuous integration server.</p>
<p>I found another example of a JRuby user running into this problem when reading about this example of <a href="http://quickdeck.blogspot.com/2007/07/use-your-favorite-ruby-library-in-java.html">using the RedCloth Ruby library to format text in a Spring/Java application</a>. Note the &#8220;ugly underbelly&#8221; footnote.</p>
<p>In the Ruby world, this is the way things work. Large Ruby applications (especially Rails applications) often rely on system services like cron to do their work. These applications have their own mechanisms for setting up new runtime systems. In the Java world, we expect to package our application with all of its dependencies and deploy it to little more than a JVM and webapp container.</p>
<p>Java has the classpath abstraction to address minimizing file system dependencies while Ruby uses the file system directly and extensively. I&#8217;ve seen a couple approaches for addressing this mismatch between Java and Ruby. All of them involve taking some set of resources packaged in a Java archive (jar, war), extracting it to a file system location at runtime and configuring Ruby to use the resources at that location. The &#8220;jruby-complete&#8221; JRuby distribution unpacks the core Ruby libraries into ~/.jruby/. <a href="http://wiki.jruby.org/wiki/Goldspike">GoldSpike</a>, the Rails plugin for packaging Rails applications as war files, bundles gems in WEB-INF and configures GEM_HOME at runtime to use the gems from the unpacked war.</p>
<p>I decided to take a similar approach with JRubyGems &#8211; bundle gem dependencies in the application classpath and install them on the local file system on demand if they are not already available. As I expect happens with many JRuby projects, it took a little Java and a little Ruby and works quite well.</p>
<p><strong><a name="JRubyGems-HowItWorks"></a>How It Works</strong></p>
<p>The main flow for RubyGems to load a gem that has not yet been loaded for an application is:</p>
<ol>
<li>Kernel::gem</li>
<li>Kernel::activate_gem_with_options</li>
<li>Gem.activate</li>
<li>Gem.source_index.find_name</li>
<li>Gem.activate each dependency of this gem first</li>
<li>Finish activating this gem</li>
</ol>
<p>JRubyGems replaces the Gem.activate implementation to insert a couple steps that:</p>
<ol>
<li>Check if the gem is locally installed</li>
<li>Search the Java classpath for the gem source if not installed</li>
<li>Install the gem locally</li>
<li>Continue with the base Gem.activate implementation</li>
</ol>
<p>This ensures that gems and their transitive dependencies are installed and loaded.</p>
<p>The classpath searching is implemented in Java.</p>
<p><strong>Release History</strong></p>
<p><em>0.3 2008-01-28</em></p>
<ul>
<li>Upgrade to use JRuby 1.1RC1 and RubyGems 1.0.1 (bundled with 1.1RC1)</li>
<li>Added test for gem that bundles a jar in lib/ (hpricot)</li>
</ul>
<p><em>0.2 2008-01-07</em></p>
<ul>
<li>Resolved issues with transitive dependency installation</li>
<li>Force install of classpath gems to avoid dependency errors</li>
<li>Additional logging of install locations</li>
</ul>
<p><em>0.1 2008-01-04</em></p>
<p>Initial release.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/01/java/jrubygems-release/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Thoughts on JRuby</title>
		<link>http://blog.carbonfive.com/2008/01/java/thoughts-on-jruby</link>
		<comments>http://blog.carbonfive.com/2008/01/java/thoughts-on-jruby#comments</comments>
		<pubDate>Wed, 02 Jan 2008 21:00:47 +0000</pubDate>
		<dc:creator>alon</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Ruby (on Rails)]]></category>

		<guid isPermaLink="false">http://blog/?p=19</guid>
		<description><![CDATA[At Carbon Five we have built our professional consulting practice on the solid foundation of enterprise Java development. In 2007 we added Ruby and Ruby on Rails as development tool and framework that complement our existing values and process in many fantastic ways. Looking forward, I want to be sure that we take maximum advantage [...]]]></description>
			<content:encoded><![CDATA[<p>At Carbon Five we have built our professional consulting practice on the solid foundation of enterprise Java development. In 2007 we added Ruby and Ruby on Rails as development tool and framework that complement our existing values and process in many fantastic ways.</p>
<p>Looking forward, I want to be sure that we take maximum advantage of our existing knowledge and new learning in both Java and Ruby. I have high hopes for <a href="http://jruby.codehaus.org/">JRuby</a> as a valuable bridge that spans both languages and gives developers the flexibility to use the strengths of the two. Sun appears to feel the same way as <a href="http://headius.blogspot.com/2006/09/jruby-steps-into-sun.html">they have hired the two core JRuby developers</a>, <a href="http://headius.blogspot.com/2007/11/top-five-questions-i-get-asked.html">Charles Nutter</a> and Thomas Enebo, to work on JRuby full time.</p>
<p>In preparation for more specific posts, here are some light musings on JRuby.</p>
<p><b><a name="JRuby-JRuby1.0"></a>JRuby 1.0</b></p>
<p>Released mid-2007 JRuby 1.0 was focused on Ruby compatibility. The idea is that any Ruby script or application you can run with the native C Ruby interpreter, you can run with JRuby. The success of this effort can be observed with Ruby on Rails applications <a href="http://oracleappslab.com/2007/11/21/mix-jruby-on-rails-small-teams-agile-and-its-effects-on-the-world/">now running on JRuby</a>. Of course, there are <a href="http://jruby.codehaus.org/Limitations">some limitations</a>.</p>
<p>In addition to running pure Ruby, JRuby can access the Java environment in which it is running. You get the Ruby niceties that you would expect like optional conversion of CamelCase method names to underscore_separated.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">list = java.<span style="color:#9900CC;">util</span>.<span style="color:#9900CC;">ArrayList</span>.<span style="color:#9900CC;">new</span>
list.<span style="color:#9900CC;">add</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;color: blue;">&quot;one&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
list.<span style="color:#9900CC;">add_all</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">2</span>, <span style="color:#996600;color: blue;">&quot;three&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span></pre></div></div>

<p>Any Java classes in the Java classpath are available to your JRuby script. Additionally, you can &#8216;require foo.jar&#8217; to make it available on your classpath at runtime. </p>
<p>You can also extend Java classes in JRuby.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> MyList <span style="color:#006600; font-weight:bold;">&lt;</span> java.<span style="color:#9900CC;">util</span>.<span style="color:#9900CC;">ArrayList</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> say_hi
    <span style="color:#996600;color: blue;">&quot;hi&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Internally, many core Ruby classes have been rewritten to delegate to core Java classes.</p>
<p><b><a name="JRuby-JRuby1.1"></a>JRuby 1.1</b></p>
<p>JRuby 1.1 is presently in beta. The top priorities for JRuby 1.1 are performance and Java integration. Ruby is not fast. JRuby 1.0 was worse. Performance was not a priority for 1.0 and the consensus is that there are a lot of easy performance wins that it is now time to take advantage of. <a href="http://headius.blogspot.com/2007/11/top-five-questions-i-get-asked.html">In his blog</a>, Charles Nutter states:</p>
<p>
<blockquote>
Straight-line execution is now typically 2-4x better than Ruby 1.8.6. Rails whole-app performance ranges from just slightly slower to slightly better, though there have been reports of specific apps running many times faster.
</p></blockquote>
<p><b><a name="JRuby-JavaIntegration"></a>Java Integration</b></p>
<p>Java integration refers to features for the using Ruby from Java rather than Java from Ruby as I discuss above. When I first started looking at JRuby Christian and I were working on a Java library to manage database migrations ala RoR and some other neat tricks we&#8217;ve seen along the way. (More on that later.) I thought it would be cool if you could write migrations using ActiveRecord&#8217;s migration features and invoke them from Java. I found myself looking for the easy means to invoke Ruby from Java. Some of this is in place with more slated for future JRuby versions. </p>
<p>The Spring Framework provides JRuby integration through which you can expose Ruby classes as Spring-managed beans. This example of <a href="http://quickdeck.blogspot.com/2007/07/use-your-favorite-ruby-library-in-java.html">using the RedCloth Ruby library to format text in a Java application</a> is a pretty slick example of how this works.</p>
<p>This post does point out one issue that I ran into with using Ruby from Java &#8211; RubyGems. Gems are Ruby libraries available from central repositories and installed on the system running Ruby. For Java applications, this dependency on system-installed resources is lame. To address this issue, I&#8217;ve spent some time working on a solution for <a href="http://www.nabble.com/Proposal-for-managing-gem-dependencies-in-a-Java-%2B-JRuby-application-to14161350.html#a14223747">packaging Ruby gem dependencies in Java applications</a>. More on JRubyGems coming soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2008/01/java/thoughts-on-jruby/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parameterized REST URLs with Spring MVC</title>
		<link>http://blog.carbonfive.com/2007/06/java/parameterized-rest-urls-with-spring-mvc</link>
		<comments>http://blog.carbonfive.com/2007/06/java/parameterized-rest-urls-with-spring-mvc#comments</comments>
		<pubDate>Mon, 11 Jun 2007 16:45:03 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog/?p=15</guid>
		<description><![CDATA[At Carbon Five, we&#8217;ve been working REST-ful practices into our web applications for some time now. Providing simple URLs for application entities is a key principal of this style, but parsing parameters out of the request path has been klunky in Spring MVC. Spring&#8217;s WebFlow apparently supports REST-ful URLs, but I&#8217;ve never found anything in [...]]]></description>
			<content:encoded><![CDATA[<p>At Carbon Five, we&#8217;ve been working <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">REST</a>-ful practices into our web applications for some time now.  Providing simple URLs for application entities is a key principal of this style, but parsing parameters out of the request path has been klunky in Spring MVC.  Spring&#8217;s <a href="http://opensource.atlassian.com/confluence/spring/display/WEBFLOW/Home">WebFlow</a> apparently supports REST-ful URLs, but I&#8217;ve never found anything in what I&#8217;ve read or heard to recommended that project (though I&#8217;ve heard nothing bad).</p>
<p>I finally got fed up with the situation and worked out a solution that lets developers specify path parameters in the dispatcher mappings, which will appear as request parameters in the controller and view.  I&#8217;ve made the project <a href="https://svn.carbonfive.com/public/pathparameter/trunk/">available</a> on our public SVN server.  The solution requires only 4 classes, so you can <a href="https://svn.carbonfive.com/public/pathparameter/trunk/src/main/java/carbonfive/spring/web/pathparameter/">download</a> them instead.  Read on for configuration information.</p>
<div class="content">
<h3>ParameterizedUrlHandlerMapping</h3>
<p>The solution is to replace Spring MVC&#8217;s SimpleUrlHandlerMapping  with ParameterizedUrlHandlerMapping.  This class is responsible for routing requests to the appropriate handler (servlet, controller, or JSP), so it&#8217;s an ideal place to specify the parameters.    Of course, at this point, it has no more access to the request than a controller, so the best it can do is add the path parameters to the request attributes.  It adds them as a Map of String name/value pairs with the key &#8220;ParameterizedUrlHandlerMapping.path-parameters&#8221;.</p>
<p>To use ParameterizedUrlHandlerMapping, replace the SimpleUrlHandlerMapping bean in the dispatcher configuration file<br />
with something that looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;carbonfive.spring.web.pathparameter.ParameterizedUrlHandlerMapping&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;alwaysUseFullPath&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;mappings&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;/view/noparameters&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>controller1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;/view/(bar:foo)&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>controller2<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;/view/(*.html:html)&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>controller3<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;/view/(**&amp;#47;*:view).view&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>controller4<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;/view/c/(*:controller)/(*:id)&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>controller5<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The ParameterizedUrlHandlerMapping supports all mappings that are valid using SimpleUrlHandlerMapping&#8217;s default AntPathMatcher.  The special parenthetical sections of the patterns have the syntax:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">'(' + [ant_style_path] + ':' + [parameter_name] + ')'</pre></div></div>

<p>
Any part of the path pattern can be within parenthesis.  The above example will having the following effect:</p>
<style type="text/css">
.content table {
width: 100%;
border: 1px solid #ccc;
}
.content th {
background-color:#eee;
}
.content td {
background-color: #f5f5f5;
}
</style>
<table>
<thead>
<th>path</th>
<th>controller</th>
<th>parameters
<th></thead>
<tbody style="vertical-align: top;">
<tr>
<td>/view/noparameters</td>
<td>controller1</td>
<td></td>
</tr>
<tr>
<td>/view/bar</td>
<td>controller2</td>
<td>foo -&gt; bar</td>
</tr>
<tr>
<td>/view/piglet.html</td>
<td>controller3</td>
<td>html -&gt; piglet.html</td>
</tr>
<tr>
<td>/view/this/that/the-other.view</td>
<td>controller4</td>
<td>view -&gt; this/that/the-other</td>
</tr>
<tr>
<td>/view/c/save/2342443</td>
<td>controller5</td>
<td>controller -&gt; save<br />id -&gt; 2342443</td>
</tr>
</tbody>
</table>
<p />
<h3>ParameterizedPathFilter</h3>
<p>If accessing the parameters from request attributes is all you need,  you can stop here.  But to elevate your path parameters to first class citizen status in your web app, you need them to appear as request parameters.  Once they are request parameters, Spring will bind them to your command or form objects, and your controllers can once again forget the details of request parsing and focus on business logic.  To complete the solution, we need the ParameterizedPathFilter configured as a web filter.  It proxies the request with a wrapper class that listens for ParameterizedUrlHandlerMapping&#8217;s request attribute.  When it is set, the wrapper class adds the parameters to the request parameters for the remaining life of the request.</p>
<p>To configure the ParameterizedPathFitler, add the following to your web.xml:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>PathParameterFilter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>carbonfive.spring.web.pathparameter.ParameterizedPathFilter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>PathParameterFilter<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/path/to/dispatcher/servlet/*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url-pattern<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/filter-mapping<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>You should have a filter mapping for each path pattern mapped to a Spring dispatcher servlet.</p>
<p>That&#8217;s all it takes to add this functionality to your webapp.  We&#8217;ve been using it in our current project. It&#8217;s been problem free and the architectural improvements have been satisfying.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2007/06/java/parameterized-rest-urls-with-spring-mvc/feed</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Using UrlRewriteFilter with the Spring Framework</title>
		<link>http://blog.carbonfive.com/2007/06/java/using-urlrewritefilter-with-the-spring-framework</link>
		<comments>http://blog.carbonfive.com/2007/06/java/using-urlrewritefilter-with-the-spring-framework#comments</comments>
		<pubDate>Fri, 08 Jun 2007 18:52:28 +0000</pubDate>
		<dc:creator>alon</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog/?p=14</guid>
		<description><![CDATA[UrlRewriteFilter is a powerful and widely used Java Servlet Filter for rewriting URLs ala Apache&#8217;s mod_rewrite module. We use Spring extensively at Carbon Five and I wanted to use UrlRewriteFilter with Spring-managed configuration and without having to register it in my web.xml file. Our content management system, SmileMaker, already uses Spring-managed filter chaining and I [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://tuckey.org/urlrewrite/">UrlRewriteFilter</a> is a powerful and widely used Java <a href="http://java.sun.com/products/servlet/Filters.html">Servlet Filter</a> for rewriting URLs ala Apache&#8217;s <a href="http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html">mod_rewrite</a> module. We use Spring extensively at Carbon Five and I wanted to use UrlRewriteFilter with Spring-managed configuration and without having to register it in my web.xml file.</p>
<p>Our content management system, SmileMaker, already uses Spring-managed filter chaining and I needed to add UrlRewriteFilter to the mix to give the CMS pretty URLs and to support search engine optimizations (SEO). I achieved this by writing a FilterFactoryBean that will initialize and configure a servlet filter in my Spring application context.</p>
<p>
We typically register one Spring <a href="http://www.acegisecurity.org/multiproject/acegi-security/apidocs/org/acegisecurity/util/FilterToBeanProxy.html">FilterToBeanProxy</a> and configure our filters using <a href="http://www.acegisecurity.org/multiproject/acegi-security/apidocs/org/acegisecurity/util/FilterChainProxy.html">FilterChainProxy</a>. (Note: these classes referenced are actually part of the ACEGI security framework for Spring.) This keeps the web.xml simple and gives us all the power of Spring for configuring and initializing our filters. In this model, you typically use setter-based injection to configure your filter. In the case of UrlRewriteFilter, the filter must be initialized with the Filter API method <a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/Filter.html#init(javax.servlet.FilterConfig)<br />
">init</a> and a <a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/FilterConfig.html">FilterConfig</a> object. The problem I needed to solve was how to create and initialize this filter, or any servlet filter really, from Spring where init must be called with initialization parameters in the FilterConfig.
</p>
<p>
My solution is a fairly standard approach that you use when integrating 3rd party libraries with Spring &#8211; create a FactoryBean. The Spring <a href="http://www.springframework.org/docs/api/org/springframework/beans/factory/FactoryBean.html">FactoryBean interface</a> provides a simple mechanism for creating objects with life cycle constraints that make them hard to create using Spring&#8217;s standard mechanisms.
</p>
<p>
Here&#8217;s my implementation of a FilterFactoryBean. Note that this FactoryBean could be used to initialize any servlet filter in Spring.
</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">carbonfive.springframework.filter</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.servlet.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.*</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.beans.factory.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.web.context.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.apache.commons.logging.*</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * FactoryBean implementation for creating and initializing a servlet filter for use
 * in a Spring context. Written to handle initializing UrlRewriteFilter.
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FilterFactoryBean <span style="color: #000000; font-weight: bold;">implements</span> FactoryBean, ServletContextAware, InitializingBean
<span style="color: #009900;">&#123;</span>
  Log log <span style="color: #339933;">=</span> LogFactory.<span style="color: #006633;">getLog</span><span style="color: #009900;">&#40;</span>FilterFactoryBean.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Hashtable</span> initParameters<span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">Class</span> filterClass<span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">private</span> ServletContext servletContext<span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getObject<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span>
  <span style="color: #009900;">&#123;</span>
    log.<span style="color: #006633;">info</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Creating filter &quot;</span> <span style="color: #339933;">+</span> filterClass.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    Filter filter <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Filter<span style="color: #009900;">&#41;</span> filterClass.<span style="color: #006633;">newInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    FilterConfig config <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> FilterConfigImpl<span style="color: #009900;">&#40;</span>initParameters<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    filter.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>config<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">return</span> filter<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">Class</span> getObjectType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> Filter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> isSingleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setFilterClass<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> filterClass<span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">filterClass</span> <span style="color: #339933;">=</span> filterClass<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setInitParameters<span style="color: #009900;">&#40;</span><span style="color: #003399;">Hashtable</span> initParameters<span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">initParameters</span> <span style="color: #339933;">=</span> initParameters<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setServletContext<span style="color: #009900;">&#40;</span>ServletContext servletContext<span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">servletContext</span> <span style="color: #339933;">=</span> servletContext<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> afterPropertiesSet<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>filterClass <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalArgumentException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;filterClass can not be null&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Filter.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>filterClass<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalArgumentException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;filterClass must implement javax.servlet.Filter&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">class</span> FilterConfigImpl <span style="color: #000000; font-weight: bold;">implements</span> FilterConfig
  <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">Hashtable</span> properties<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> FilterConfigImpl<span style="color: #009900;">&#40;</span><span style="color: #003399;">Hashtable</span> properties<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">properties</span> <span style="color: #339933;">=</span> properties<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getFilterName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> filterClass.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;color: blue;">&quot;-filter&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> ServletContext getServletContext<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> servletContext<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getInitParameter<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span> properties.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Enumeration</span> getInitParameterNames<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> properties.<span style="color: #006633;">keys</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
And a test for this implementation using UrlRewriteFilter:
</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">carbonfive.springframework.filter</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">carbonfive.smilemaker.web.spring.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">junit.framework.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.apache.commons.logging.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.mock.web.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.tuckey.web.filters.urlrewrite.*</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.servlet.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.*</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FilterFactoryBeanTest <span style="color: #000000; font-weight: bold;">extends</span> TestCase
<span style="color: #009900;">&#123;</span>
  Log log <span style="color: #339933;">=</span> LogFactory.<span style="color: #006633;">getLog</span><span style="color: #009900;">&#40;</span>FilterFactoryBeanTest.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testCreateUrlRewriteFilter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span>
  <span style="color: #009900;">&#123;</span>
    log.<span style="color: #006633;">info</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Starting test&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    FilterFactoryBean factory <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> FilterFactoryBean<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    factory.<span style="color: #006633;">setServletContext</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MockServletContext<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    factory.<span style="color: #006633;">setFilterClass</span><span style="color: #009900;">&#40;</span>UrlRewriteFilter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003399;">Properties</span> properties <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Properties</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    properties.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;confPath&quot;</span>, <span style="color: #0000ff;color: blue;">&quot;/WEB-INF/rewrite.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    properties.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;confReloadCheckInterval&quot;</span>, <span style="color: #0000ff;color: blue;">&quot;30&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    properties.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;logLevel&quot;</span>, <span style="color: #0000ff;color: blue;">&quot;DEBUG&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    properties.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;statusPath&quot;</span>, <span style="color: #0000ff;color: blue;">&quot;/status&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    properties.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;statusEnabled&quot;</span>, <span style="color: #0000ff;color: blue;">&quot;true&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    properties.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;statusEnabledOnHosts&quot;</span>, <span style="color: #0000ff;color: blue;">&quot;localhost,127.0.0.1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    factory.<span style="color: #006633;">setInitParameters</span><span style="color: #009900;">&#40;</span>properties<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    factory.<span style="color: #006633;">afterPropertiesSet</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    assertEquals<span style="color: #009900;">&#40;</span>Filter.<span style="color: #000000; font-weight: bold;">class</span>, factory.<span style="color: #006633;">getObjectType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    Filter filter <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Filter<span style="color: #009900;">&#41;</span> factory.<span style="color: #006633;">getObject</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertNotNull<span style="color: #009900;">&#40;</span>filter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertTrue<span style="color: #009900;">&#40;</span>filter <span style="color: #000000; font-weight: bold;">instanceof</span> UrlRewriteFilter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    UrlRewriteFilter rewriter <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>UrlRewriteFilter<span style="color: #009900;">&#41;</span> filter<span style="color: #339933;">;</span>
    assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">30</span>, rewriter.<span style="color: #006633;">getConfReloadCheckInterval</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertEquals<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span>, rewriter.<span style="color: #006633;">isConfReloadCheckEnabled</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertEquals<span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;/status&quot;</span>, rewriter.<span style="color: #006633;">getStatusPath</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertEquals<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span>, rewriter.<span style="color: #006633;">isStatusEnabled</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
To create this filter in Spring my configuration looks like:
</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;color: blue;">&quot;smilemaker-urlRewriteFilter&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;color: blue;">&quot;carbonfive.springframework.filter.FilterFactoryBean&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;filterClass&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;color: blue;">&quot;org.tuckey.web.filters.urlrewrite.UrlRewriteFilter&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;color: blue;">&quot;initParameters&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;confPath&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>/WEB-INF/config/urlrewrite.xml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;confReloadCheckInterval&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>10<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;statusEnabled&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;prop</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;color: blue;">&quot;statusPath&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>/admin/rewrite-status<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/prop<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/props<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>
Note that I found and reported (and locally fixed) <a href="http://code.google.com/p/urlrewritefilter/issues/detail?id=2">a bug in UrlRewriteFilter</a> where changes to a config file in a non-standard location do not get picked up.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2007/06/java/using-urlrewritefilter-with-the-spring-framework/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using classpath*: vs. classpath: when loading Spring resources.</title>
		<link>http://blog.carbonfive.com/2007/05/java/using-classpath-vs-classpath-when-loading-spring-resources</link>
		<comments>http://blog.carbonfive.com/2007/05/java/using-classpath-vs-classpath-when-loading-spring-resources#comments</comments>
		<pubDate>Thu, 17 May 2007 17:59:57 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[classpath: Spring framework hibernate mapping files wildcard]]></category>

		<guid isPermaLink="false">http://blog/?p=13</guid>
		<description><![CDATA[After a few hours of hair-pulling and a deep tour of the Spring source, we realized that the problem was that our test Spring configuration was in a different classpath root from our Hibernate mappings, even though both directories were in the test's classpath.
]]></description>
			<content:encoded><![CDATA[<p>I recently resolved a build problem nestled deep within the esoterica of spring resource loading.  The behavior of classpath: URLs is explained <a href="http://www.springframework.org/docs/reference/resources.html#resources-classpath-wildcards">at length</a> in the Spring documentation, but, sadly, this is probably the last place a developer of my disposition would look.  The problem (which I describe in more detail beyond the fold) was that we were unable to load hibernate mapping files from our Spring configured integration tests even though they gave us no trouble in our web application.  The solution was to replace the &#8220;classpath:&#8221; prefix of our mappingLocation URI with &#8220;classpath*:&#8221;.</p>
<p>In this project, we are storing our Hibernate mapping files as separate files located in the package of the class they map (i.e. &#8220;Foo.hbm.xml&#8221; stored in &#8220;src/main/java/com/example/&#8221;).  We inherited the persisted classes and Hibernate and Spring configuration from another project.  The sessionFactory configuration in spring specified the mappingLocations as &#8220;classpath:**/*.hbm.xml&#8221; which worked fine when we deployed the web application.</p>
<p>We soon ran into problems when we added integration tests to test new DAO functionality. The test configuration was not able to find any hibernate mappings even though we were using the same &#8220;classpath:**/*.hbm.xml&#8221; URI.  After a few hours of hair-pulling and a deep tour of the Spring source, we realized that the problem was that our test Spring configuration was in a different classpath root from the Hibernate mappings, even though both directories were in the test&#8217;s classpath.</p>
<p>When you use &#8216;classpath:&#8217; for an Ant style wildcard search, Spring uses a single classpath directory for the search. The <a href="http://www.springframework.org/docs/reference/resources.html#resources-classpath-wildcards">documentation</a> is vague, but it seems the directory returned will be the first one provided by ClassLoader.getResources(&#8220;&#8221;).  In our case, it returned the &#8216;/target/test-classes&#8217; directory that contains applicationTest.xml and our test classes, instead of &#8216;/target/classes&#8217; which contains application.xml and all the *.hbm.xml files.</p>
<p>Using the &#8216;classpath*:&#8217; prefix fixes the problem.  It indicates that the resource loader should look in all directories on the classpath, so making this change solved our problem.  Apparently Spring maintains both prefixes because limitations in the Classloader (at the specification level) make it difficult to search for resources in the classpath root when performing wildcard searches across all classpath directories.  This suggest it might be good practice to always create a directory to contain resources you might otherwise want to put in the classpath root and <i>always</i> use the &#8216;claspath*:&#8217; prefix.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2007/05/java/using-classpath-vs-classpath-when-loading-spring-resources/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DBUnit 2.2, Spring, and Testing</title>
		<link>http://blog.carbonfive.com/2007/05/testing/dbunit-22-spring-and-testing</link>
		<comments>http://blog.carbonfive.com/2007/05/testing/dbunit-22-spring-and-testing#comments</comments>
		<pubDate>Tue, 15 May 2007 16:30:20 +0000</pubDate>
		<dc:creator>christian</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog/?p=12</guid>
		<description><![CDATA[You may have noticed that DBUnit changed its connection closing behavior in v2.2. We noticed it when tests deriving from our custom DatabaseTestCase implementation (which uses DBUnit) starting failing. Initially we just reverted back to version 2.1. Since then I&#8217;ve discovered what the problem was and found a workaround, and while I was at it, [...]]]></description>
			<content:encoded><![CDATA[<p>You may have noticed that <a href="http://www.dbunit.org/">DBUnit</a> changed its connection closing behavior in v2.2.  We noticed it when tests deriving from our custom DatabaseTestCase implementation (which uses DBUnit) starting failing.  Initially we just reverted back to version 2.1.  Since then I&#8217;ve discovered what the problem was and found a workaround, and while I was at it, I created some nice utilities to be used in tests which need data fixtures.</p>
<p><strong>Problem</strong></p>
<p>In v2.2 DBUnit introduces some new abstractions, one of which is the <a href="http://www.dbunit.org/apidocs/org/dbunit/IDatabaseTester.html">IDatabaseTester</a>.  Whether it’s by design or by accident, the default implementation closes connections after executing its operations (<a href="http://sourceforge.net/tracker/?func=detail&#038;aid=1473744&#038;group_id=47439&#038;atid=449494">more info</a>).  The end result is that in our unit tests, the database connection is closed before the test can run.</p>
<p><strong>Solution</strong></p>
<p>I’ve created two simple util classes for loading test data into a database without closing the connection:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/** A helper for loading data sets into unit tests. */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> DatabaseUtils <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #006600; font-weight: bold;">void</span> loadDataSet<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">Class</span> clazz, <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399; font-weight: bold;">DataSource</span> dataSource<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span> <span style="color: #009900;">&#123;</span>
        IDataSet dataSet = <span style="color: #000000; font-weight: bold;">new</span> FlatXmlDataSet<span style="color: #009900;">&#40;</span>TestUtils.<span style="color: #006633;">datasetInputStream</span><span style="color: #009900;">&#40;</span>clazz<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        IDatabaseTester tester = <span style="color: #000000; font-weight: bold;">new</span> ExistingConnectionDatabaseTester<span style="color: #009900;">&#40;</span>dataSource<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        tester.<span style="color: #006633;">setDataSet</span><span style="color: #009900;">&#40;</span>dataSet<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        tester.<span style="color: #006633;">onSetup</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/** A special DatabaseTester that doesn’t close the connection when its done. */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ExistingConnectionDatabaseTester <span style="color: #000000; font-weight: bold;">extends</span> AbstractDatabaseTester <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">DataSource</span> dataSource<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> ExistingConnectionDatabaseTester<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">DataSource</span> dataSource<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">dataSource</span> = dataSource<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> IDatabaseConnection getConnection<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> DatabaseConnection<span style="color: #009900;">&#40;</span>DataSourceUtils.<span style="color: #006633;">getConnection</span><span style="color: #009900;">&#40;</span>dataSource<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> closeConnection<span style="color: #009900;">&#40;</span>IDatabaseConnection connection<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// Don't close that connection!</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The first of these depends on another test-related utility, TestUtils.java (see below), which converts a class to a path.  The second depends on Spring’s <a href="http://www.springframework.org/docs/api/org/springframework/jdbc/datasource/DataSourceUtils.html">DataSourceUtils</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * A set of utilities that generate paths from classnames.  This is useful when
 * making reference to resources used by test cases, when the resources are
 * located in a directory path matching the class' package.
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TestUtils <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399; font-weight: bold;">String</span> TEST_PREFIX = <span style="color: #0000ff;color: blue;">&quot;src/test/resources/&quot;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Maven2 default</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399; font-weight: bold;">String</span> pathString<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">Class</span> clazz<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> pathString<span style="color: #009900;">&#40;</span>TEST_PREFIX, clazz, <span style="color: #0000ff;color: blue;">&quot;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399; font-weight: bold;">String</span> pathString<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">Class</span> clazz, <span style="color: #003399; font-weight: bold;">String</span> resource<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> pathString<span style="color: #009900;">&#40;</span>TEST_PREFIX, clazz, resource<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399; font-weight: bold;">String</span> pathString<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">String</span> prefix, <span style="color: #003399; font-weight: bold;">Class</span> clazz, <span style="color: #003399; font-weight: bold;">String</span> resource<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        prefix = <span style="color: #009900;">&#40;</span>prefix <span style="color: #339933;">!</span>= <span style="color: #006600; font-weight: bold;">null</span> <span style="color: #339933;">?</span> prefix : <span style="color: #0000ff;color: blue;">&quot;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003399; font-weight: bold;">StringBuffer</span> sb = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399; font-weight: bold;">StringBuffer</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>prefix<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000;  font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>prefix.<span style="color: #006633;">endsWith</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>ClassUtils.<span style="color: #006633;">classPackageAsResourcePath</span><span style="color: #009900;">&#40;</span>clazz<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>resource<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> sb.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399; font-weight: bold;">InputStream</span> pathInputStream<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">Class</span> clazz, <span style="color: #003399; font-weight: bold;">String</span> resource<span style="color: #009900;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">FileNotFoundException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> pathInputStream<span style="color: #009900;">&#40;</span>TEST_PREFIX, clazz, resource<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399; font-weight: bold;">InputStream</span> pathInputStream<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">String</span> prefix, <span style="color: #003399; font-weight: bold;">Class</span> clazz, <span style="color: #003399; font-weight: bold;">String</span> resource<span style="color: #009900;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">FileNotFoundException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399; font-weight: bold;">FileInputStream</span><span style="color: #009900;">&#40;</span>pathString<span style="color: #009900;">&#40;</span>prefix, clazz, resource<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399; font-weight: bold;">InputStream</span> datasetInputStream<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">Class</span> clazz<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">FileNotFoundException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> pathInputStream<span style="color: #009900;">&#40;</span>TEST_PREFIX, clazz, ClassUtils.<span style="color: #006633;">getShortName</span><span style="color: #009900;">&#40;</span>clazz<span style="color: #009900;">&#41;</span> + <span style="color: #0000ff;color: blue;">&quot;.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>These three classes give us everything we need to load data into our test database using DBUnit.  And TestUtils can be used to load other test resources from the classpath as well, like images, documents, CSVs, etc.</p>
<p>Here&#8217;s an example of how it can be used in a DAO test based on Spring&#8217;s test classes.</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ArtistHibernateDaoTest <span style="color: #000000; font-weight: bold;">extends</span> AbstractAnnotationAwareTransactionalTests <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> ArtistHibernateDao artistDao<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> setArtistDao<span style="color: #009900;">&#40;</span>ArtistHibernateDao artistDao<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">artistDao</span> = artistDao<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #003399; font-weight: bold;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getConfigLocations<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399; font-weight: bold;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span><span style="color: #0000ff;color: blue;">&quot;applicationContext-database.xml&quot;</span>, <span style="color: #0000ff;color: blue;">&quot;applicationContext-hibernate.xml&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #006600; font-weight: bold;">void</span> onSetUpInTransaction<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399; font-weight: bold;">Exception</span> <span style="color: #009900;">&#123;</span>
        DatabaseUtils.<span style="color: #006633;">loadDataSet</span><span style="color: #009900;">&#40;</span>getClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, getJdbcTemplate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getDataSource</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> testFindAllNames<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        List<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> names = artistDao.<span style="color: #006633;">findAllNames</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3</span>, names.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertTrue<span style="color: #009900;">&#40;</span>names.<span style="color: #006633;">contains</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;The Cure&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertTrue<span style="color: #009900;">&#40;</span>names.<span style="color: #006633;">contains</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;Depeche Mode&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertTrue<span style="color: #009900;">&#40;</span>names.<span style="color: #006633;">contains</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;color: blue;">&quot;New Order&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>onSetUpInTransaction() loads the data set using the convention of (packagename).(ClassName).xml before each test (e.g. com.c5.PizzaTest loads the file com/c5/PizzaText.xml on the classpath).  In this case the data is loaded in the same transaction as the test so that no clean-up is necessary when the test is completed.  These tests run fast!</p>
<p>We&#8217;ve been talking about moving away from our custom DatabaseTestCase class hierarchy.  The above functionality in conjunction with <a href="http://www.springframework.org/docs/api/org/springframework/test/annotation/AbstractAnnotationAwareTransactionalTests.html">Spring&#8217;s test hierarchy</a> could be a good start.</p>
<p>On a somewhat related note, there is a new unit testing framework called <a href="http://unitils.sourceforge.net">Unitils </a>which does this sort of thing and much more.  I haven’t used it but it sounds interesting.</p>
<p>Christian</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2007/05/testing/dbunit-22-spring-and-testing/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Presenting Spring AOP at SDForum April 4</title>
		<link>http://blog.carbonfive.com/2006/04/java/presenting-spring-aop-at-sdforum-april-4</link>
		<comments>http://blog.carbonfive.com/2006/04/java/presenting-spring-aop-at-sdforum-april-4#comments</comments>
		<pubDate>Mon, 03 Apr 2006 22:19:47 +0000</pubDate>
		<dc:creator>alon</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog/?p=10</guid>
		<description><![CDATA[
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m giving a presentation at the <a href="http://www.sdforum.org/SDForum/Templates/CalendarEvent.aspx?CID=1879&#038;mo=4&#038;yr=2006">SDForum Java SIG tomorrow evening, April 4</a>, on aspect oriented programming with the Spring Framework.</p>
<p/>
I will be discussing a model for using the AOP features of Spring to expose Hibernate-managed POJOs to remote clients through web services complete with role-based security and declarative transactions. It follows one of the <a href="http://www.carbonfive.com/community/archives/2005/07/ive_been_meanin.html">service API design approaches</a> I discussed in this forum last year.</p>
<p/>
The source for this presentation <a href="http://www.carbonfive.com/community/download/springaop.zip">is available here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2006/04/java/presenting-spring-aop-at-sdforum-april-4/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>SsTemplates Spreadsheet Templates for Excel</title>
		<link>http://blog.carbonfive.com/2005/09/java/sstemplates-spreadsheet-templates-for-excel</link>
		<comments>http://blog.carbonfive.com/2005/09/java/sstemplates-spreadsheet-templates-for-excel#comments</comments>
		<pubDate>Mon, 12 Sep 2005 17:53:12 +0000</pubDate>
		<dc:creator>alon</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog/?p=8</guid>
		<description><![CDATA[I am writing to announce the public release of SsTemplates, our solution for creating Excel documents in Java. SsTemplates builds upon the Jakarta POI/HSSF libraries for writing Microsoft Office documents by providing a simple XML templating language for creating Excel documents similar to creating HTML pages with JSP and CSS. An example from the documentation: [...]]]></description>
			<content:encoded><![CDATA[<p>I am writing to announce the public release of <a href="http://carbonfive.sourceforge.net/sstemplates/api/com/carbonfive/sstemplates/package-summary.html#documentation">SsTemplates</a>, our solution for creating Excel documents in Java.</p>
<p>SsTemplates builds upon the Jakarta POI/HSSF libraries for writing Microsoft Office documents by providing a simple XML templating language for creating Excel documents similar to creating HTML pages with JSP and CSS.</p>
<p>An example from the documentation:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>workbook xmlns<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;http://carbonfive.com/schema/sstemplates&quot;</span><span style="color: #339933;">&gt;</span>
  <span style="color: #339933;">&lt;</span>style name<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;label&quot;</span> fontWeight<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;bold&quot;</span><span style="color: #339933;">/&gt;</span>
  <span style="color: #339933;">&lt;</span>style name<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;money&quot;</span> dataFormat<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;$0.00&quot;</span><span style="color: #339933;">/&gt;</span>
&nbsp;
  <span style="color: #339933;">&lt;</span>sheet name<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;Formula Spreadsheet&quot;</span><span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>row<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>cell style<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;label&quot;</span><span style="color: #339933;">&gt;</span>January<span style="color: #339933;">&lt;/</span>cell<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>cell style<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;money&quot;</span> type<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;numeric&quot;</span><span style="color: #339933;">&gt;</span><span style="color: #cc66cc;">1.99</span><span style="color: #339933;">&lt;/</span>cell<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;/</span>row<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>row<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>cell style<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;label&quot;</span><span style="color: #339933;">&gt;</span>February<span style="color: #339933;">&lt;/</span>cell<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>cell style<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;money&quot;</span> type<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;numeric&quot;</span><span style="color: #339933;">&gt;</span><span style="color: #cc66cc;">2.09</span><span style="color: #339933;">&lt;/</span>cell<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;/</span>row<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>row<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>cell style<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;label&quot;</span><span style="color: #339933;">&gt;</span>March<span style="color: #339933;">&lt;/</span>cell<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>cell style<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;money&quot;</span> type<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;numeric&quot;</span><span style="color: #339933;">&gt;</span><span style="color: #cc66cc;">3</span><span style="color: #339933;">&lt;/</span>cell<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;/</span>row<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>row<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>cell style<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;label&quot;</span><span style="color: #339933;">&gt;</span>Total<span style="color: #339933;">&lt;/</span>cell<span style="color: #339933;">&gt;</span>
      <span style="color: #339933;">&lt;</span>cell style<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;money&quot;</span> type<span style="color: #339933;">=</span><span style="color: #0000ff;color: blue;">&quot;formula&quot;</span><span style="color: #339933;">&gt;</span>sum<span style="color: #009900;">&#40;</span>B1<span style="color: #339933;">:</span>B3<span style="color: #009900;">&#41;</span><span style="color: #339933;">&lt;/</span>cell<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;/</span>row<span style="color: #339933;">&gt;</span>
  <span style="color: #339933;">&lt;/</span>sheet<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>workbook<span style="color: #339933;">&gt;</span></pre></div></div>

<p/>
<img src="http://carbonfive.sourceforge.net/sstemplates/api/com/carbonfive/sstemplates/doc-files/formula.png" alt="Formula Example"></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2005/09/java/sstemplates-spreadsheet-templates-for-excel/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
