<?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>Jayway Team Blog &#187; Ulrik Sandberg</title>
	<atom:link href="http://blog.jayway.com/author/ulriksandberg/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Tue, 20 Jul 2010 08:26:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>The Golden Ratio</title>
		<link>http://blog.jayway.com/2009/10/24/the-golden-ratio/</link>
		<comments>http://blog.jayway.com/2009/10/24/the-golden-ratio/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 21:40:53 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[goldenratio]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2139</guid>
		<description><![CDATA[Also known as the "Divine Quotient", the Golden Ratio was given an almost magical meaning during the renaissance, but it's actually much older than that. Leonardo DaVinci used it. Euclid used it. It was supposedly discovered by Pythagoras. So, what is it? It's very simple. Take a length and divide it into two parts: a [...]]]></description>
			<content:encoded><![CDATA[<p>Also known as the "Divine Quotient", the Golden Ratio was given an almost magical meaning during the renaissance, but it's actually much older than that. Leonardo DaVinci used it. Euclid used it. It was supposedly discovered by Pythagoras. So, what is it? It's very simple. Take a length and divide it into two parts: <code>a</code> and <code>b</code>:
</p>
<p><img src="http://upload.wikimedia.org/wikipedia/commons/6/65/Image-Golden_ratio_line.png" /></p>
<p>
When the ratio between <code>a</code> and <code>b</code> is equal to the ratio between <code>a+b</code> and <code>a</code>, then you have the Golden Ratio. The value of the Golden Ratio is:
</p>
<p><img src="http://upload.wikimedia.org/math/a/3/d/a3d3da4fbbcb7bfb997c5f480ad905bd.png" /></p>
<p>Why is it so special? Because if you know about it, it can be seen in many different places; in geometrical figures, in architecture, in paintings, and in nature. I'll show you. Draw a pentagon:
</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/10/pentagon.png" alt="Pentagon" title="pentagon" width="382" height="364" class="size-full wp-image-2154" /></p>
<p>Draw straight lines between all vertices of the pentagon. This will result in a pentagram (five-pointed star). Now mark the lengths <code>a</code> and <code>b</code> as this picture shows:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/10/pentagram_lengths.png" alt="Pentagram inside pentagon" title="pentagram with lengths" width="382" height="364" class="size-full wp-image-2154" /></p>
<p>Guess what the ratio is between the lengths <code>a</code> and <code>b</code>? The Golden Ratio. Now, mark two other lengths <code>a'</code> and <code>b'</code>:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/10/pentagram_lengths2.png" alt="Pentagram inside pentagon with other lengths" title="pentagram with other lengths" width="382" height="364" class="size-full wp-image-2154" /></p>
<p>You guessed it. The ratio between <code>a'</code> and <code>b'</code> is the Golden Ratio.</p>
<p>It's actually pretty easy to approximate Phi (<em>&#x03C6;</em>), as the Golden Ratio normally is called. Take any two numbers and add them, then divide the sum with the larger number. For example, 11 and 74:
</p>
<pre>
11.0+74.0=85.0
85.0/74.0=1.1486486486486487
</pre>
<p>Now we add the larger of the numbers (74) to the sum (85), and then we again divide the new sum (159) with the the previous sum (85):
</p>
<pre>
74.0+85.0=159.0
159.0/85.0=1.8705882352941177
</pre>
<p>We're getting there. One more time:</p>
<pre>
85.0+159.0=244.0
244.0/159.0=1.5345911949685536
</pre>
<p>No, this is too tedious. Let's write a program that does it. For no reason whatsoever, I'll pick Scala. What is Scala? I'm on a Mac, so I'll just do:</p>
<pre>
% port info scala
scala @2.7.5 (lang, java)

Description:          Scala is a modern multi-paradigm programming language designed to express common programming patterns
                      in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and
                      functional languages. It runs inside a Java Virtual Machine and is fully interoperable with Java.
Homepage:             http://www.scala-lang.org/
</pre>
<p>This is how I install Scala:</p>
<pre>
% sudo port install scala
</pre>
<p>I'll want some editor support, so I install the TextMate bundle that accompanies Scala:</p>
<pre>
% cd /Library/Application\ Support/TextMate/Bundles/
% unzip /opt/local/share/scala/misc/scala-tool-support/textmate/Bundles/Scala.tmbundle.zip
</pre>
<p>I'll tell TextMate to reload its bundles by selecting the menu "Bundles | Bundle Editor | Reload Bundles". Now I'm all set.</p>
<p>Consider this Scala program (phi1.scala):</p>
<pre>
var x = 11.
var y = 74.

for (i &lt;- 1 to 5) {
    var sum = x + y
    var q = sum / y
    println(q)
    x = y
    y = sum
}
</pre>
<p>I'll run it like this:</p>
<pre>
% scala phi1.scala
1.1486486486486487
1.8705882352941177
1.5345911949685536
1.651639344262295
1.6054590570719602
</pre>
<p>It's not pretty, but it does the job. Let's spice it up with some input arguments and better printout (phi2.scala):</p>
<pre>
var x = 11.
var y = 74.
var n = 13

if (args.length &gt; 3) {
    println(&quot;Usage: scala phi2.scala [n [x [y]]]&quot;)
    println(&quot;  n: number of times to perform calculation (default: &quot; + n + &quot;)&quot;)
    println(&quot;  x: start value of &#x27;x&#x27; (default: &quot; + x + &quot;)&quot;)
    println(&quot;  y: start value of &#x27;y&#x27; (default: &quot; + y + &quot;)&quot;)
    System.exit(1)
}
if (args.length &gt;= 1) n = Integer.parseInt(args(0))
if (args.length &gt;= 2) x = Integer.parseInt(args(1))
if (args.length == 3) y = Integer.parseInt(args(2))

for (i &lt;- 1 to n) {
    var sum = x + y
    print(i + &quot;: &quot; + x + &quot;+&quot; + y + &quot;=&quot; + sum)
    var q = sum / y
    println(&quot;, &quot; + sum + &quot;/&quot; + y + &quot;=&quot; + q)
    x = y
    y = sum
}
</pre>
<p>I'll run it with four arguments to test it:</p>
<pre>
% scala phi2.scala 1 2 3 4
Usage: scala phi2.scala [n [x [y]]]
  n: number of times to perform calculation (default: 13)
  x: start value of 'x' (default: 11.0)
  y: start value of 'y' (default: 74.0)
</pre>
<p>I won't bore you with more tests, but instead do what we intended to do from the start: have a program run the iterations for us. I'll run it with no arguments, using the defaults:</p>
<pre>
% scala phi2.scala
1: 11.0+74.0=85.0, 85.0/74.0=1.1486486486486487
2: 74.0+85.0=159.0, 159.0/85.0=1.8705882352941177
3: 85.0+159.0=244.0, 244.0/159.0=1.5345911949685536
4: 159.0+244.0=403.0, 403.0/244.0=1.651639344262295
5: 244.0+403.0=647.0, 647.0/403.0=1.6054590570719602
6: 403.0+647.0=1050.0, 1050.0/647.0=1.6228748068006182
7: 647.0+1050.0=1697.0, 1697.0/1050.0=1.6161904761904762
8: 1050.0+1697.0=2747.0, 2747.0/1697.0=1.618738951090159
9: 1697.0+2747.0=4444.0, 4444.0/2747.0=1.6177648343647615
10: 2747.0+4444.0=7191.0, 7191.0/4444.0=1.618136813681368
11: 4444.0+7191.0=11635.0, 11635.0/7191.0=1.6179947156167431
12: 7191.0+11635.0=18826.0, 18826.0/11635.0=1.6180489901160293
13: 11635.0+18826.0=30461.0, 30461.0/18826.0=1.6180282587910337
</pre>
<p>Actually, I will run one more test, but this time I'll choose the starting values more carefully. One of many wonderful properties of the <a href="http://en.wikipedia.org/wiki/Fibonacci">Fibonacci</a> series is that the ratio between the numbers is very close to the Golden Ratio. This means it will converge much quicker. Check this out, four correct decimals after just four iterations:
</p>
<pre>
% scala phi2.scala 4 21 34
1: 21.0+34.0=55.0, 55.0/34.0=1.6176470588235294
2: 34.0+55.0=89.0, 89.0/55.0=1.6181818181818182
3: 55.0+89.0=144.0, 144.0/89.0=1.6179775280898876
4: 89.0+144.0=233.0, 233.0/144.0=1.6180555555555556
</pre>
<p>Here is the final version, with some stuff that makes the file executable (phi.scala):
</p>
<pre>
#!/bin/sh
exec scala $0 $@
!#
var x = 11.
var y = 74.
var n = 13

if (args.length &gt; 3) {
    println(&quot;Usage: scala phi.scala [n [x [y]]]&quot;)
    println(&quot;  n: number of times to perform calculation (default: &quot; + n + &quot;)&quot;)
    println(&quot;  x: start value of &#x27;x&#x27; (default: &quot; + x + &quot;)&quot;)
    println(&quot;  y: start value of &#x27;y&#x27; (default: &quot; + y + &quot;)&quot;)
    System.exit(1)
}
if (args.length &gt;= 1) n = Integer.parseInt(args(0))
if (args.length &gt;= 2) x = Integer.parseInt(args(1))
if (args.length == 3) y = Integer.parseInt(args(2))

for (i &lt;- 1 to n) {
    var sum = x + y
    print(i + &quot;: &quot; + x + &quot;+&quot; + y + &quot;=&quot; + sum)
    var q = sum / y
    println(&quot;, &quot; + sum + &quot;/&quot; + y + &quot;=&quot; + q)
    x = y
    y = sum
}
</pre>
<p>I'll make it executable and run it:</p>
<pre>
% chmod +x phi.scala
% ./phi.scala 10 13 21
1: 13.0+21.0=34.0, 34.0/21.0=1.619047619047619
2: 21.0+34.0=55.0, 55.0/34.0=1.6176470588235294
3: 34.0+55.0=89.0, 89.0/55.0=1.6181818181818182
4: 55.0+89.0=144.0, 144.0/89.0=1.6179775280898876
5: 89.0+144.0=233.0, 233.0/144.0=1.6180555555555556
6: 144.0+233.0=377.0, 377.0/233.0=1.6180257510729614
7: 233.0+377.0=610.0, 610.0/377.0=1.6180371352785146
8: 377.0+610.0=987.0, 987.0/610.0=1.618032786885246
9: 610.0+987.0=1597.0, 1597.0/987.0=1.618034447821682
10: 987.0+1597.0=2584.0, 2584.0/1597.0=1.6180338134001253
</pre>
<p>Check out <a href="http://en.wikipedia.org/wiki/Golden_ratio">Golden Ratio</a> on Wikipedia for more details.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/10/24/the-golden-ratio/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Power of Unit Testing</title>
		<link>http://blog.jayway.com/2009/05/21/the-power-of-unit-testing/</link>
		<comments>http://blog.jayway.com/2009/05/21/the-power-of-unit-testing/#comments</comments>
		<pubDate>Thu, 21 May 2009 14:07:00 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scrum]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1761</guid>
		<description><![CDATA[The purpose of Unit Testing is to verify for the developer that a software unit does what it is supposed to and is fit for use. The confidence that the developer gets, gives the developer courage to do other useful practices like Refactoring. Unit testing is often used to test complex units with one or [...]]]></description>
			<content:encoded><![CDATA[<p>The purpose of <a href="http://en.wikipedia.org/wiki/Unit_testing" title="Unit testing - Wikipedia, the free encyclopedia">Unit Testing</a> is to verify for the developer that a software unit does what it is supposed to and is fit for use. The confidence that the developer gets, gives the developer courage to do other useful practices like <a href="http://en.wikipedia.org/wiki/Refactoring" title="Code refactoring - Wikipedia, the free encyclopedia">Refactoring</a>. </p>
<p>Unit testing is often used to test complex units with one or more collaborators, usually with the help of mock objects. But the greatest value with unit testing, in my opinion, lies in testing the lowest level utility methods; the building blocks that simply <em>have</em> to be bullet-proof in order for the rest of the system to have a stable foundation.</p>
<p>Let's say that we have an Article domain object, storing article numbers from the database in the form "01234567":</p>
<pre>
public class Article {

    /**
     * 8 character numeric article number, eg &quot;01234567&quot;.
     */
    private String articleNumber = &quot;&quot;;

    public String getArticleNumber() {
        return articleNumber;
    }

    public void setArticleNumber(String articleNumber) {
        this.articleNumber = articleNumber;
    }
}
</pre>
<p>Business now demands that the article number should be formatted with dots here and there. They have added the story "User should see article numbers formatted as 123.456.78" to the Sprint Backlog.</p>
<p>We decide to write a test for this:</p>
<pre>
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class ArticleTest {

    @Test
    public void testGetFormattedArticleNumberNoZeros() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;98765432&quot;);
        assertEquals(&quot;987.654.32&quot;, tested.getFormattedArticleNumber());
    }
}
</pre>
<p>We search around for a while, and find several nice tools for <em>parsing</em> formatted strings, but nothing useful for <em>writing</em> formatted strings that will help us in our scenario. Lacking ideas, we desperately try <a href="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html" title="DecimalFormat (Java Platform SE 6)">DecimalFormat</a>. It's actually not that bad. If we divide by 100, we'll automatically get the right-most dot, don't we? We decide to give it a try:</p>
<pre>
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;

public class Article {

    /**
     * 8 character numeric article number, eg &quot;01234567&quot;.
     */
    private String articleNumber = &quot;&quot;;

    public String getArticleNumber() {
        return articleNumber;
    }

    public void setArticleNumber(String articleNumber) {
        this.articleNumber = articleNumber;
    }

    /**
     * Retrieves the formatted article number.
     *
     * TODO I didn&#x27;t find a nice generic formatting method, so I wrote this terrible hack.
     *
     * @return the formatted article number, eg 123.456.78
     */
    public String getFormattedArticleNumber() {
        NumberFormat nf = NumberFormat.getNumberInstance();
        DecimalFormat df = (DecimalFormat) nf;
        BigDecimal number = new BigDecimal(articleNumber);
        number = number.divide(new BigDecimal(100));
        String str = df.format(number);
        return str;
    }
}
</pre>
<p>We get a failure:</p>
<pre>expected:&lt;987[.654.]32&gt; but was:&lt;987[&nbsp;654,]32&gt;
</pre>
<p>The decimal point is a comma (,) in the default locale, and the grouping separator is a blank. We can tweak that by calling the <code>getDecimalFormatSymbols</code> method, giving us a <a href="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormatSymbols.html" title="DecimalFormatSymbols (Java Platform SE 6)">DecimalFormatSymbols</a> that we can change:</p>
<pre>DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
symbols.setDecimalSeparator(&#x27;.&#x27;);
symbols.setGroupingSeparator(&#x27;.&#x27;);
df.setDecimalFormatSymbols(symbols);
</pre>
<p>We also make sure the grouping size is always three by calling <code>df.setGroupingSize(3)</code>. Here is the code so far:</p>
<pre>public String getFormattedArticleNumber() {
    NumberFormat nf = NumberFormat.getNumberInstance();
    DecimalFormat df = (DecimalFormat) nf;
    df.setGroupingSize(3);
    DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
    symbols.setDecimalSeparator(&#x27;.&#x27;);
    symbols.setGroupingSeparator(&#x27;.&#x27;);
    df.setDecimalFormatSymbols(symbols);
    BigDecimal number = new BigDecimal(articleNumber);
    number = number.divide(new BigDecimal(100));
    String str = df.format(number);
    return str;
}
</pre>
<p>Success! Excellent. Now, we suspect that there might be problems with leading zeros, so we add another test:</p>
<pre>
    @Test
    public void testGetFormattedArticleNumberLeadingZero() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;01234567&quot;);
        assertEquals(&quot;012.345.67&quot;, tested.getFormattedArticleNumber());
    }
</pre>
<p>As we suspected. We get a failure:</p>
<pre>expected:&lt;[0]12.345.67&gt; but was:&lt;[]12.345.67&gt;
</pre>
<p>This can be fixed by setting the minimum integer size to 6:</p>
<pre>df.setMinimumIntegerDigits(6);
</pre>
<p>We run the test suite again. Success! Great. We suspect that <em>trailing</em> zeros can also be troublesome. We add a few tests for that:</p>
<pre>
    @Test
    public void testGetFormattedArticleNumberSingleTrailingZero() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;98765430&quot;);
        assertEquals(&quot;987.654.30&quot;, tested.getFormattedArticleNumber());
    }

    @Test
    public void testGetFormattedArticleNumberTrailingZeros() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;98765400&quot;);
        assertEquals(&quot;987.654.00&quot;, tested.getFormattedArticleNumber());
    }

    @Test
    public void testGetFormattedArticleNumberAllZeros() {
        Article tested = new Article();
        tested.setArticleNumber(&quot;00000000&quot;);
        assertEquals(&quot;000.000.00&quot;, tested.getFormattedArticleNumber());
    }
</pre>
<p>We run the tests. The last three tests all fail, indicating that trailing zeros are lost. We fix that by setting the minimum fraction size to 2:</p>
<pre>df.setMinimumFractionDigits(2);
</pre>
<p>Success! The complete method now looks like this:</p>
<pre>/**
 * Retrieves the formatted article number.
 *
 * TODO I didn&#x27;t find a nice generic formatting method, so I wrote this terrible hack.
 *
 * @return the formatted article number, eg 123.456.78
 */
public String getFormattedArticleNumber() {
    NumberFormat nf = NumberFormat.getNumberInstance();
    DecimalFormat df = (DecimalFormat) nf;
    df.setGroupingSize(3);
    df.setMinimumIntegerDigits(6);
    df.setMinimumFractionDigits(2);
    DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
    symbols.setDecimalSeparator(&#x27;.&#x27;);
    symbols.setGroupingSeparator(&#x27;.&#x27;);
    df.setDecimalFormatSymbols(symbols);
    BigDecimal number = new BigDecimal(articleNumber);
    number = number.divide(new BigDecimal(100));
    String str = df.format(number);
    return str;
}
</pre>
<p>It's not pretty, but it works. We check in the code, relax, and think for a while. Is there a simpler way? Of course there is:</p>
<pre>/**
 * Retrieves the formatted article number.
 *
 * @return the formatted article number, eg 123.456.78
 */
public String getFormattedArticleNumber() {
    StringBuffer number = new StringBuffer(articleNumber);
    number.insert(3, &#x27;.&#x27;);
    number.insert(7, &#x27;.&#x27;);
    return number.toString();
}
</pre>
<p>Here, the power of unit testing shows. We don't even think twice about replacing the existing code. The tests still run, so we hook this code into the user interface, run the functional tests, check in, wait for a successful build, and finally ask the Product Owner to run the acceptance tests for the story.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/21/the-power-of-unit-testing/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Upgrading Groovy to 1.6.2 Fails on Mac</title>
		<link>http://blog.jayway.com/2009/04/29/upgrading-groovy-to-162-fails-on-mac/</link>
		<comments>http://blog.jayway.com/2009/04/29/upgrading-groovy-to-162-fails-on-mac/#comments</comments>
		<pubDate>Wed, 29 Apr 2009 07:41:37 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[macosx]]></category>
		<category><![CDATA[macports]]></category>
		<category><![CDATA[problem]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[upgrade]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1584</guid>
		<description><![CDATA[When I tried to upgrade Groovy from 1.6.1 to 1.6.2 using MacPorts, it failed with an OutOfMemoryError. I managed to get it to build using some manual fixing in the build file. I'll explain what I did in this blog. This was the result that I got: $ sudo port upgrade groovy ---&#62; Building groovy [...]]]></description>
			<content:encoded><![CDATA[<p>When I tried to upgrade Groovy from 1.6.1 to 1.6.2 using MacPorts, it failed with an OutOfMemoryError. I managed to get it to build using some manual fixing in the build file. I'll explain what I did in this blog.</p>
<p>This was the result that I got:</p>
<pre>
$ sudo port upgrade groovy
---&gt;  Building groovy
...
Command output:     [javac] Compiling 699 source files to /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_java_groovy/work/groovy-1.6.2/target/classes
    [javac]
    [javac]
    [javac] The system is out of resources.
    [javac] Consult the following stack trace for details.
    [javac] java.lang.OutOfMemoryError: Java heap space
    ...
    [javac] 	at com.sun.tools.javac.Main.main(Main.java:54)

BUILD FAILED
/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_java_groovy/work/groovy-1.6.2/build.xml:173: Compile failed; see the compiler error output for details.
</pre>
<p>Looking in the directory mentioned above, we find a <code>build.properties</code> file that contains some settings:</p>
<pre>
$ cat /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_java_groovy/work/groovy-1.6.2/build.properties
...
groovycMain_mx = 512m
groovycTest_mx = 1G
groovycExamples_mx = ${groovycMain_mx}

javaDoc_mx = 512m
groovyDoc_mx = 640m
</pre>
<p>OK, plenty of memory, but nothing seems related to javac compilation. Let's check the line 173, that the error message mentioned:</p>
<pre>
sudo vi +173 /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_java_groovy/work/groovy-1.6.2/build.xml
</pre>
<p>The javac call there does not contain any memory setting, so we must assume that it uses the default heap size:</p>
<pre>
&lt;javac srcdir=&quot;${mainSourceDirectory}&quot; includeantruntime=&quot;false&quot; destdir=&quot;${mainClassesDirectory}&quot;
       deprecation=&quot;on&quot; debug=&quot;yes&quot; source=&quot;1.5&quot; target=&quot;1.5&quot; fork=&quot;true&quot; classpathref=&quot;compilePath&quot;&gt;
</pre>
<p>However, looking a few lines further down, we find the groovyc call:</p>
<pre>
&lt;groovyc srcdir=&quot;${mainSourceDirectory}&quot; destdir=&quot;${mainClassesDirectory}&quot; fork=&quot;true&quot; memorymaximumsize=&quot;${groovycMain_mx}&quot;&gt;
</pre>
<p>Let's add the same memory setting as the groovyc call uses to the javac call:</p>
<pre>
&lt;javac srcdir=&quot;${mainSourceDirectory}&quot; includeantruntime=&quot;false&quot; destdir=&quot;${mainClassesDirectory}&quot;
       memorymaximumsize=&quot;${groovycMain_mx}&quot; deprecation=&quot;on&quot; debug=&quot;yes&quot; source=&quot;1.5&quot; target=&quot;1.5&quot; fork=&quot;true&quot; classpathref=&quot;compilePath&quot;&gt;
</pre>
<p>Let's try the upgrade again:</p>
<pre>
$ sudo port upgrade groovy
---&gt;  Building groovy
---&gt;  Staging groovy into destroot
---&gt;  Deactivating groovy @1.6.1_0
---&gt;  Installing groovy @1.6.2_0
---&gt;  Activating groovy @1.6.2_0
---&gt;  Cleaning groovy
</pre>
<p>Success.</p>
<p><strong>Update:</strong> The memory problem seems to be related to Java6. Switching to Java5 makes the build go through, and I've replicated that on two Macs.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/04/29/upgrading-groovy-to-162-fails-on-mac/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Always Use Parenthesis in Groovy Builders</title>
		<link>http://blog.jayway.com/2009/04/24/always-use-parenthesis-in-groovy-builders/</link>
		<comments>http://blog.jayway.com/2009/04/24/always-use-parenthesis-in-groovy-builders/#comments</comments>
		<pubDate>Fri, 24 Apr 2009 06:28:46 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[builder]]></category>
		<category><![CDATA[gotcha]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[parenthesis]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1570</guid>
		<description><![CDATA[I recently ran into an interesting Groovy feature when demonstrating the strengths of the <a href="http://groovy.codehaus.org/Creating+XML+using+Groovy%27s+MarkupBuilder">MarkupBuilder</a>. As you probably know, parenthesis in a Groovy method call are optional, unless it's a no-args call. In that case the parenthesis are needed in order to distinguish the call from a property. However, leaving out parenthesis in a Builder is asking for trouble. I'll show you why.]]></description>
			<content:encoded><![CDATA[<p>I recently ran into an interesting Groovy feature when demonstrating the strengths of the <a href="http://groovy.codehaus.org/Creating+XML+using+Groovy%27s+MarkupBuilder">MarkupBuilder</a>. As you probably know, parenthesis in a Groovy method call are optional, unless it's a no-args call. In that case the parenthesis are needed in order to distinguish the call from a property. However, leaving out parenthesis in a Builder is asking for trouble. Consider this:</p>
<pre>def w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)
builder.persons() {
    person(attr:'value')
}
println w
</pre>
<p>Resulting XML is:</p>
<pre>&lt;persons&gt;
  &lt;person attr=&#x27;value&#x27; /&gt;
&lt;/persons&gt;
</pre>
<p>Let's remove the seemingly redundant parenthesis on the call to 'person':</p>
<pre>def w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)
builder.persons() {
    person attr:&#x27;value&#x27;
}
println w
</pre>
<p>Resulting XML is:</p>
<pre>&lt;persons&gt;
  &lt;person attr=&#x27;value&#x27; /&gt;
&lt;/persons&gt;
</pre>
<p>Identical. Good, all is well, you think. But it's not. We add an empty closure to 'person', which really should not have any effect:</p>
<pre>def w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)
builder.persons() {
    person attr:&#x27;value&#x27; {}
}
println w
</pre>
<p>Resulting XML is:</p>
<pre>&lt;persons&gt;
  &lt;value /&gt;
  &lt;person attr=&#x27;value&#x27; /&gt;
&lt;/persons&gt;
</pre>
<p>What happened here? An element was inserted with the same name as my attribute value.</p>
<p>Now, let's add something to the empty closure:</p>
<pre>def w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)
builder.persons() {
    person attr:&#x27;value&#x27; {
        kid()
    }
}
println w
</pre>
<p>Resulting XML is:</p>
<pre>&lt;persons&gt;
  &lt;value&gt;
    &lt;kid /&gt;
  &lt;/value&gt;
  &lt;person attr=&#x27;value&#x27; /&gt;
&lt;/persons&gt;
</pre>
<p>Even more strange. The 'kid' element ended up inside the 'value' element.</p>
<p>If I add parenthesis to 'person', then everything works as expected:</p>
<pre>def w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)
builder.persons() {
    person(attr:&#x27;value&#x27;) {
        kid()
    }
}
println w
</pre>
<p>Resulting XML is:</p>
<pre>&lt;persons&gt;
  &lt;person attr=&#x27;value&#x27;&gt;
    &lt;kid /&gt;
  &lt;/person&gt;
&lt;/persons&gt;
</pre>
<p>I don't want to turn this feather into something it is not. When using Builders, use parenthesis, end of story. However, for those of us that can't let something like this pass, here follows my analysis.</p>
<p>The <a href="http://groovy.codehaus.org/Statements" title="Groovy - Statements">Groovy Statements page</a> says:</p>
<blockquote><p>    If a method takes parameters you can leave the closure outside of the parenthesis (provided that the closure parameter is the last parameter on the underlying method).</p>
<pre>
    def value = [1, 2, 3].inject(0) { count, item -&gt; count + item }
    assert value == 6
</pre>
<p>    The above code is equivalent to the following (but just neater)</p>
<pre>
    def value = [1, 2, 3].inject(0, { count, item -&gt; count + item })
    assert value == 6
</pre>
</blockquote>
<p>So what does that tell us? Well, if our closure is really the last parameter to the 'person' call, then we should be able to write this:</p>
<pre>def w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)
builder.persons() {
    person (attr:&#x27;value&#x27;, {
        kid()
    })
}
println w
</pre>
<p>Note the comma after 'value'. Let's run that code:</p>
<pre>&lt;persons&gt;
  &lt;person attr=&#x27;value&#x27;&gt;
    &lt;kid /&gt;
  &lt;/person&gt;
&lt;/persons&gt;
</pre>
<p>OK, it looks fine. However, when we skipped the parenthesis, we implicitly also skipped that crucial comma. In effect, we wrote what's equivalent to this:</p>
<pre>def w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)
builder.persons() {
    person (attr:&#x27;value&#x27; {
        kid()
    })
}
println w
</pre>
<p>This is really interesting. It looks like the only parameter to 'person' now is a single map entry <code>attr</code> that maps to ... what exactly? Running this will result in the now well-known:</p>
<pre>&lt;persons&gt;
  &lt;value&gt;
    &lt;kid /&gt;
  &lt;/value&gt;
  &lt;person attr=&#x27;value&#x27; /&gt;
&lt;/persons&gt;
</pre>
<p>Can you see it yet?</p>
<p>This whole discussion started with the claim that parenthesis are optional to method calls. And that's exactly what 'value' is: a method call with a Closure as a parameter:</p>
<pre>
&#x27;value&#x27; { kid() }
</pre>
<p>It's OK to quote method names, for example if they contain illegal characters like '-', but it's of course also OK to quote a method name that doesn't contain illegal characters.</p>
<p>So, let's define a method 'value' that takes a Closure as parameter, in order to see if it gets called:</p>
<pre>def value(Closure c) { println &#x27;inside method value&#x27;; return &#x27;returned value&#x27;}
def w = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(w)
builder.persons() {
    person (attr:&#x27;value&#x27; {
        kid()
    })
}
println w
</pre>
<p>We get this:</p>
<pre>inside method value
&lt;persons&gt;
  &lt;person attr=&#x27;returned value&#x27; /&gt;
&lt;/persons&gt;
</pre>
<p>Pretty convincing, right?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/04/24/always-use-parenthesis-in-groovy-builders/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting Coverage For Integration Tests</title>
		<link>http://blog.jayway.com/2008/12/13/getting-coverage-for-integration-tests/</link>
		<comments>http://blog.jayway.com/2008/12/13/getting-coverage-for-integration-tests/#comments</comments>
		<pubDate>Sat, 13 Dec 2008 17:59:21 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[coverage]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=565</guid>
		<description><![CDATA[Unit testing in my world is basically defined by being able to run the tests wherever and whenever; on the train, on the plane, at work, or at home. If you also have integration tests, chances are that they require some external data source or something that simply makes it impossible to run them everywhere. [...]]]></description>
			<content:encoded><![CDATA[<p>Unit testing in my world is basically defined by being able to run the tests wherever and whenever; on the train, on the plane, at work, or at home. If you also have integration tests, chances are that they require some external data source or something that simply makes it impossible to run them everywhere. If that's the case, they should probably not be included in the unit test suite.</p>
<p>Having code coverage of your unit tests is important, because it'll give you an indication of where you should focus your efforts next. The open source coverage tool <a href="http://cobertura.sourceforge.net/">Cobertura</a> gives you not only code coverage, it also shows you the <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">code complexity</a> level of packages and classes. This directs you towards the untested parts that are the most complex and most likely also the most error-prone.</p>
<h3>The Problem</h3>
<p>Rumor has it that Maven2 in an upcoming release will support having integration tests in a source folder called <code>src/it/java</code>, and run those in the integration-test phase. That would be a welcome improvement. Currently, however, Maven2 lacks good support for integration tests, and so does Cobertura. It's really a pain to get coverage on both unit tests and integration tests.</p>
<p>Let's say that you want to keep your integration tests in the same module as the unit tests. In fact, this might be a wise decision, since it's even harder to get Cobertura to provide coverage on two separate modules. Still, you do want to separate them somehow, and for now you have named the integration tests <code>IntTestSomething</code> and the unit tests <code>TestSomething</code>.</p>
<pre>
src/test/java/
`-- org
    `-- springframework
        `-- ldap
            `-- samples
                `-- article
                    |-- dao
                    |   |-- AbstractIntTestPersonDao.java
                    |   |-- IntTestPersonDaoImpl.java
                    |   `-- IntTestTraditionalPersonDaoImpl.java
                    `-- domain
                        `-- PersonTest.java
</pre>
<p>Cobertura will run the tests through Surefire, which has a <a href="http://maven.apache.org/plugins/maven-surefire-plugin/examples/inclusion-exclusion.html">default pattern</a> that picks up the unit tests, but not the integration tests. We don't want coverage on the integration tests all the time, so that's fine. But how do we include the integration tests on-demand? </p>
<h3>The Solution</h3>
<p>I will keep the unit tests in the <code>src/test/java</code> folder, but move the integration tests to a newly created <code>src/it/java</code> folder. Then I will use <a href="http://mojo.codehaus.org/build-helper-maven-plugin/">some magic</a> to incorporate that folder into the Maven build path, but only if I specify a certain profile. I will be able to do this:</p>
<pre>
% mvn test
// runs unit tests only

% mvn cobertura:cobertura
// provides coverage on unit tests only

% mvn test -Pitcov
// runs unit tests and integration tests

% mvn cobertura:cobertura -Pitcov
// provides coverage on unit tests and integration tests
</pre>
<p>Create the folder <code>src/it/java</code> and move your integration tests there. Rename them to match the Surefire default pattern, like <code>SomethingIntegrationTest</code>. That will enable Surefire to pick them up without any extra configuration.</p>
<pre>
src/it/java/
`-- org
    `-- springframework
        `-- ldap
            `-- samples
                `-- article
                    `-- dao
                        |-- AbstractPersonDaoIntegrationTest.java
                        |-- PersonDaoImplIntegrationTest.java
                        `-- TraditionalPersonDaoImplIntegrationTest.java
</pre>
<p>The unit test source folder now looks like this:</p>
<pre>
src/test/java/
`-- org
    `-- springframework
        `-- ldap
            `-- samples
                `-- article
                    `-- domain
                        `-- PersonTest.java
</pre>
<p>Now add the following profile to your Maven pom:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;profiles<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;profile<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;id<span style="font-weight: bold; color: black;">&gt;</span></span></span>itcov<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/id<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;build<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.codehaus.mojo<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>build-helper-maven-plugin<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>1.1<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;executions<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;execution<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;id<span style="font-weight: bold; color: black;">&gt;</span></span></span>add-test-source<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/id<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;phase<span style="font-weight: bold; color: black;">&gt;</span></span></span>generate-sources<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/phase<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;goals<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;goal<span style="font-weight: bold; color: black;">&gt;</span></span></span>add-test-source<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/goal<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/goals<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sources<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                          <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;source<span style="font-weight: bold; color: black;">&gt;</span></span></span>src/it/java<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/source<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/sources<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                     <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/execution<span style="font-weight: bold; color: black;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/executions<span style="font-weight: bold; color: black;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/build<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/profile<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/profiles<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Now we're ready to run coverage:</p>
<pre>
mvn cobertura:cobertura
...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running org.springframework.ldap.samples.article.domain.PersonTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.048 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
...
</pre>
<p>Here we can see that only one test was run. The coverage report reveals that we only get coverage on the unit test of the Person domain object, giving us a total coverage of 7%:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/12/unittestsonly1-1024x642.png" alt="Coverage on unit tests only" title="Coverage on unit tests only" width="1024" height="642" class="alignnone size-large wp-image-579" /></p>
<p>We clean the target folder and run again, this time with the 'itcov' profile:</p>
<pre>
mvn clean
mvn cobertura:cobertura -Pitcov
...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImplIntegrationTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.124 sec
Running org.springframework.ldap.samples.article.dao.PersonDaoImplIntegrationTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.12 sec
Running org.springframework.ldap.samples.article.domain.PersonTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec

Results :

Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
...
</pre>
<p>This time we get both the unit tests and the integration tests, and the coverage report paints quite a different picture, with 75% coverage instead of 7%:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/12/unitanditests1-1024x642.png" alt="Coverage on unit tests and integration tests" title="Coverage on unit tests and integration tests" width="1024" height="642" class="alignnone size-large wp-image-580" /></p>
<p>What we immediately see here is that we should focus our efforts on testing our web layer. But that's another story...</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/13/getting-coverage-for-integration-tests/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Encrypting Properties With Jasypt</title>
		<link>http://blog.jayway.com/2008/12/09/encrypting-properties-with-jasypt/</link>
		<comments>http://blog.jayway.com/2008/12/09/encrypting-properties-with-jasypt/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 17:08:40 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[properties]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=539</guid>
		<description><![CDATA[Properties are used in many Java applications as a simple way of separating parts that are likely to change, from the parts that are not that likely to change. Consider for example this typical bean definition in a Spring configuration file: &#160; &#60;bean id=&#34;traditionalPersonDao&#34; class=&#34;org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl&#34;&#62; &#60;property name=&#34;url&#34; value=&#34;ldap://localhost:3901&#34; /&#62; &#60;property name=&#34;base&#34; value=&#34;dc=jayway,dc=se&#34; /&#62; &#60;property name=&#34;userDn&#34; [...]]]></description>
			<content:encoded><![CDATA[<p>Properties are used in many Java applications as a simple way of separating parts that are likely to change, from the parts that are not that likely to change. Consider for example this typical bean definition in a Spring configuration file:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;traditionalPersonDao&quot;</span>
      <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap://localhost:3901&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;base&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;dc=jayway,dc=se&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;uid=admin,ou=system&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;secret&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>In order to simplify deployment and maintenance, it's quite common to extract properties related to server names, ports, and user credentials from the Spring configuration file into a separate property file, like in this <code>ldap.properties</code>:</p>
<pre>
url=ldap://localhost:3901
userDn=uid=admin,ou=system
password=secret
</pre>
<p>In the configuration file, the previously hard-coded values are replaced with "property placeholders", ie variables enclosed with <code>${}</code>:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;traditionalPersonDao&quot;</span>
      <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${url}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;base&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;dc=jayway,dc=se&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${userDn}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${password}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>In order to perform the property value substitution in a transparent way, a <code>PropertyPlaceholderConfigurer</code> is configured:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;classpath:/config/ldap.properties&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Spring will <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-extension-factory-postprocessors">pick up</a> that one has been configured and run it before any beans are instantiated. It will read the property file and replace the placeholders with the actual values. Quite handy and very simple.</p>
<p>But what if your organization dislikes having sensitive information like passwords lying around in property files, in clear text? Let's say that your boss demands that all such passwords must be encrypted. Wouldn't it be great if the password then somehow could be automatically decrypted before being used? This can quite easily be achieved using the <a href="http://jasypt.org/">Jasypt</a> library.</p>
<p>It's a two-step process. First we need to encrypt the password. Then we configure a different <code>PropertyPlaceholderConfigurer</code> that is capable of decrypting the property after it has been read.</p>
<h4>Encrypting the password</h4>
<p>The available encryption algorithms are currently limited to Password Based Encryptors (PBE). There are scripts for encrypting and decrypting in the Jasypt distribution. This is the procedure for encrypting a text (assuming the Jasypt library has been unpacked in JASYPT_HOME):</p>
<pre>
% cd $JASYPT_HOME/bin
% chmod +x *.sh
% ./encrypt.sh input="This is my message to be encrypted" password=MYPAS_WORD verbose=false
p3ZVFhK+aqQCyvSk9uWk7p/eisyPbXp3zt3sqnEZsn1Z5plr4CHNC/HHqlgRQ7I3
</pre>
<p>Let's verify that it can actually be decrypted:</p>
<pre>
% ./decrypt.sh input="p3ZVFhK+aqQCyvSk9uWk7p/eisyPbXp3zt3sqnEZsn1Z5plr4CHNC/HHqlgRQ7I3"
    password=MYPAS_WORD verbose=false
This is my message to be encrypted
</pre>
<p>Good. Note that the encryption is "salted", so you'll never get the same result twice. You'll always be able to decrypt it, though. Want to see? OK, one more time then:</p>
<pre>
% ./encrypt.sh input="This is my message to be encrypted" password=MYPAS_WORD verbose=false
Zi68CfrcLndtKg0npE9OScr+7qNJmWrcO8XI7ZGyucjFiqT9h1FnAIxyezbqNjQq

% ./decrypt.sh input="Zi68CfrcLndtKg0npE9OScr+7qNJmWrcO8XI7ZGyucjFiqT9h1FnAIxyezbqNjQq"
    password=MYPAS_WORD verbose=false
This is my message to be encrypted
</pre>
<p>Now, let's encrypt our password:</p>
<pre>
% ./encrypt.sh input="secret" password=MYPAS_WORD verbose=false
6mbJVZ6jozGYF1pjjqDQOQ==
</pre>
<p>We'll replace the password value in the properties file with the string above, surrounded by <code>ENC()</code>:</p>
<pre>
url=ldap://localhost:3901
userDn=uid=admin,ou=system
password=ENC(6mbJVZ6jozGYF1pjjqDQOQ==)
</pre>
<h4>Configure A Decrypting PropertyPlaceholderConfigurer</h4>
<p>We'll simply replace our existing <code>PropertyPlaceholderConfigurer</code> with the Jasypt <code>EncryptablePropertyPlaceholderConfigurer</code>:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.jasypt.spring.properties.EncryptablePropertyPlaceholderConfigurer&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;configurationEncryptor&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;classpath:/config/ldap.properties&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>It delegates the actual decryption to a <code>StringEncryptor</code> implementation:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;configurationEncryptor&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.jasypt.encryption.pbe.StandardPBEStringEncryptor&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;config&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;environmentVariablesConfiguration&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>The encryptor in turn needs a configuration that provides information such as the algorithm to use and the encryption password. It delegates that responsibility to a <code>PBEConfig</code> implementation that expects the password to be available in an environment variable or a system property:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;environmentVariablesConfiguration&quot;</span>
      <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;algorithm&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;PBEWithMD5AndDES&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;passwordEnvName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;APP_ENCRYPTION_PASSWORD&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Providing the encryption password as a system property is actually a good thing. A system property can be cleared just when the application has started, thereby minimizing considerably the time that the password is exposed. </p>
<h4>Running The Application</h4>
<p>It won't work with a Maven property:</p>
<pre>
% mvn test -DAPP_ENCRYPTION_PASSWORD=MYPAS_WORD
...
Tests run: 8, Failures: 0, Errors: 8, Skipped: 0
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] There are test failures.

Please refer to target/surefire-reports for the individual test results
</pre>
<p>We check the Surefire reports and find the cause of the error:</p>
<pre>
org.jasypt.exceptions.EncryptionInitializationException:
  Password not set for Password Based Encryptor
</pre>
<p>It <em>does</em> however work with an environment variable:</p>
<pre>
% export APP_ENCRYPTION_PASSWORD=MYPAS_WORD
% mvn test
...
Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...
% unset APP_ENCRYPTION_PASSWORD
</pre>
<h3>Issues With Java5</h3>
<p>If we're on Java5 (or lower), we'll need <a href="http://icu-project.org/">ICU4J</a>. Otherwise, we'll run into this:</p>
<pre>
org.jasypt.exceptions.EncryptionInitializationException:
  java.lang.NoClassDefFoundError: com/ibm/icu/text/Normalizer
</pre>
<p>There are two places where we'll need ICU4J: the command line tools and our Maven project.</p>
<h4>ICU4J With The Command Line Tools</h4>
<p>Reviewing the Jasypt scripts, we find that it's possible to customize the classpath:</p>
<pre>
export JASYPT_CLASSPATH=~/Downloads/icu4j-4_0.jar
</pre>
<h4>ICU4J With Maven</h4>
<p>Add this profile to the Maven <code>pom.xml</code> to get ICU4J in the classpath:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;profiles<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;profile<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;id<span style="font-weight: bold; color: black;">&gt;</span></span></span>jdk15<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/id<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;activation<span style="font-weight: bold; color: black;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;jdk<span style="font-weight: bold; color: black;">&gt;</span></span></span>1.5<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/jdk<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/activation<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependencies<span style="font-weight: bold; color: black;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>com.ibm.icu<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>icu4j<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>3.8<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependencies<span style="font-weight: bold; color: black;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/profile<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/profiles<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Currently, the 4.0 version is not available in the central Maven repo, but 3.8 seems to work just fine.</p>
<h3>Summary</h3>
<p>Using Jasypt, it's actually quite easy to use encrypted values in your property files. In a Spring-based application, it's simply a question of replacing the existing <code>PropertyPlaceholderConfigurer</code> with the Jasypt encrypting equivalent, plus two more beans providing encryption and configuration. Choose how to provide the encryption password, and you're set to go.</p>
<p>If running on Java5 or lower, you'll also need to add ICU4J to your classpath, for the encryption scripts as well as your build and deployment environment.</p>
<h3>References</h3>
<ul>
<li><a href="http://jasypt.org">http://jasypt.org</a></li>
<li><a href="http://www.springframework.org">http://www.springframework.org</a></li>
<li><a href="http://icu-project.org/">http://icu-project.org/</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/09/encrypting-properties-with-jasypt/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Squid, the caching proxy</title>
		<link>http://blog.jayway.com/2008/06/06/squid-the-caching-proxy/</link>
		<comments>http://blog.jayway.com/2008/06/06/squid-the-caching-proxy/#comments</comments>
		<pubDate>Fri, 06 Jun 2008 18:37:34 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[proxy]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=85</guid>
		<description><![CDATA[I just checked out the old Squid again, the worlds most famous caching proxy. If you direct all your web access through the Squid proxy server, it will cache stuff after the first access. This would simplify for example for labs where fifty people simultaneously begin retrieving stuff from a Maven repo somewhere or downloading [...]]]></description>
			<content:encoded><![CDATA[<p>I just checked out the old <a href="http://www.squid-cache.org/">Squid</a> again, the worlds most famous caching proxy. If you direct all your web access through the Squid proxy server, it will cache stuff after the first access. This would simplify for example for labs where fifty people simultaneously begin retrieving stuff from a Maven repo somewhere or downloading required libraries, and we have a very limited bandwidth.</p>
<p>On the Mac it was easy to get running (if you have <a href="http://www.macports.org/">MacPorts</a>):</p>
<pre>% sudo port install squid
% sudo squid -z (initialize stuff if you never ran Squid before)
% sudo squid -N -d 1 (no daemon, debug level 1)</pre>
<p>Then it was running on the console, and you could test it like this:</p>
<pre>% squidclient http://google.com
...
X-Cache: MISS from myhostname
Via: 1.0 myhostname:3128 (squid/2.7.STABLE2)</pre>
<p>And again, this time fetching from the cache:</p>
<pre>% squidclient http://google.com
...
X-Cache: HIT from myhostname
Via: 1.0 myhostname:3128 (squid/2.7.STABLE2)</pre>
<p>You configure your browser by simply setting proxy server to <code>localhost:3128</code>, if you are running your Squid locally, that is.</p>
<p>Maven is probably best configured in <code>~/.m2/settings.xml</code>:</p>
<pre>&lt;settings xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/xmlSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/xsd/settings-1.0.0.xsd"&gt;
  &lt;proxies&gt;
    &lt;proxy&gt;
      &lt;active&gt;true&lt;/active&gt;
      &lt;protocol&gt;http&lt;/protocol&gt;
      &lt;host&gt;localhost&lt;/host&gt;
      &lt;port&gt;3128&lt;/port&gt;
    &lt;/proxy&gt;
  &lt;/proxies&gt;
&lt;/settings&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/06/06/squid-the-caching-proxy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Amazon S3 for backup</title>
		<link>http://blog.jayway.com/2007/09/02/using-amazon-s3-for-backup/</link>
		<comments>http://blog.jayway.com/2007/09/02/using-amazon-s3-for-backup/#comments</comments>
		<pubDate>Sun, 02 Sep 2007 22:50:20 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[s3]]></category>
		<category><![CDATA[storage]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=162</guid>
		<description><![CDATA[Amazon Simple Storage Service (S3) is cheap on-line storage with a Web Service interface. You just log in with your Amazon id, sign up for S3, designate a credit card, and that's it. You now have access to pretty much unlimited storage space, managed by Amazon. The price is $0.15 per GB-Month of storage used [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://aws.amazon.com/s3">Amazon Simple Storage Service (S3)</a> is cheap on-line storage with a Web Service interface. You just log in with your Amazon id, sign up for S3, designate a credit card, and that's it. You now have access to pretty much unlimited storage space, managed by Amazon. The price is $0.15 per GB-Month of storage used (plus transfer costs). It was too tempting; I simply had to test it.</p>
<p>I used the <a href="http://jungledisk.com/">Jungle Disk</a> software to provide the mapping from the S3 web service interface to a network drive. You give Jungle Disk your S3 account information, and it provides a network disk which you can use as the backup device. I first tried my existing backup software (<a href="http://www.qdea.com/pages/pages-sprox/sprox1.html">Synchronize! Pro X</a>) and it happily began creating directories and copying files. I then tried the backup feature built into Jungle Disk, and it works fine too. It's not fast compared to a local FireWire disk. It's limited to your upload bandwidth, which often is substantially smaller than the download bandwidth.</p>
<p>Anyway, it has been tugging along today storing 5 GB of by digital photos. It feels pretty good to know that my photos are now stored encrypted and with 99.99% availability somewhere far far away, costing me only 75 cents per month after the initial $2 for the transfer.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/09/02/using-amazon-s3-for-backup/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Mocking Classes</title>
		<link>http://blog.jayway.com/2007/05/09/mocking-classes/</link>
		<comments>http://blog.jayway.com/2007/05/09/mocking-classes/#comments</comments>
		<pubDate>Wed, 09 May 2007 14:31:34 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=165</guid>
		<description><![CDATA[Mocking a class rather than an interface might present some interesting obstacles. Perhaps you have ran into the dreaded: Unexpected method call toString(): toString(): expected: 0, actual: 1 You think nothing of it and happily add an expectation for toString. Then you get: Unexpected method call toString(): toString(): expected: 1, actual: 2 The reason is [...]]]></description>
			<content:encoded><![CDATA[<p>Mocking a class rather than an interface might present some interesting obstacles. Perhaps you have ran into the dreaded:</p>
<pre>Unexpected method call toString():
  toString(): expected: 0, actual: 1</pre>
<p>You think nothing of it and happily add an expectation for toString. Then you get:</p>
<pre>Unexpected method call toString():
  toString(): expected: 1, actual: 2</pre>
<p>The reason is that EasyMock itself calls <tt>toString</tt> for each expectation, so it's a never-ending story. However, it appears only when your class under test has overridden any (or all) of <tt>toString</tt>, <tt>equals</tt> or <tt>hashCode</tt>. There is a way around it. You can tell EasyMock's <tt>MockClassControl</tt> which methods you want it to mock. Yes, you heard it right: "which methods you <em>want it</em> to mock". I know, you'd rather want to tell it which methods you <em>don't</em> want it to mock, like <tt>toString</tt>, <tt>equals</tt> and <tt>hashCode</tt>.</p>
<p>I'll show you a couple of utility classes that let you do that. We ran into this problem in a previous project and wrote the classes below. They let you get away with this neat code that should be used whenever you mock a class:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyClassTest <span style="color: #000000; font-weight: bold;">extends</span> TestCase <span style="color: #66cc66;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">private</span> MockControl myClassControl;
   <span style="color: #000000; font-weight: bold;">private</span> MyClass myClassMock;
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setUp<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
      myClassControl = TestUtils.<span style="color: #006600;">createClassControl</span><span style="color: #66cc66;">&#40;</span>MyClass.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
      myClassMock = <span style="color: #66cc66;">&#40;</span>MyClass<span style="color: #66cc66;">&#41;</span> myClassControl.<span style="color: #006600;">getMock</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
   <span style="color: #66cc66;">&#125;</span>
   ...
<span style="color: #66cc66;">&#125;</span></pre>
<p>Here are the classes:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">testutils</span>; 
&nbsp;
<span style="color: #a1a100;">import org.easymock.MockControl; </span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Various utility functions for testing.
 *
 * @author Adam Skogman
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">class</span> TestUtils <span style="color: #66cc66;">&#123;</span> 
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> TestUtils<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Get a MockClassControl for the supplied class, using the first found
     * public or protected constructor and not mocking the toString(), equals()
     * and hashCode() methods.
     *
     * @param cls
     *            the class to create a MockClassControl for.
     * @return a MockClassControl for the class.
     * @see MockClassControlHelper
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> MockControl getMockClassControl<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> cls<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> getMockClassControl<span style="color: #66cc66;">&#40;</span>
                cls,
                MockClassControlHelper.<span style="color: #006600;">DONT_MOCK_STD_METHODS</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Get a MockClassControl for the supplied class, using the first found
     * public or protected constructor. If mockStdMethods is false, the
     * toString(), equals() and hashCode() methods will not be mocked.
     *
     * @param cls
     *            the class to create a MockClassControl for.
     * @param mockStdMethods
     *            whether toString(), equals() and hashCode() will be mocked.
     * @return a MockClassControl for the class.
     * @see MockClassControlHelper
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> MockControl getMockClassControl<span style="color: #66cc66;">&#40;</span>
            <span style="color: #000000; font-weight: bold;">Class</span> cls,
            <span style="color: #993333;">boolean</span> mockStdMethods<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        MockClassControlHelper helper = <span style="color: #000000; font-weight: bold;">new</span> MockClassControlHelper<span style="color: #66cc66;">&#40;</span>
                mockStdMethods<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">return</span> helper.<span style="color: #006600;">getMockClassControl</span><span style="color: #66cc66;">&#40;</span>cls<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">testutils</span>; 
&nbsp;
<span style="color: #a1a100;">import java.lang.reflect.Constructor;</span>
<span style="color: #a1a100;">import java.lang.reflect.Method;</span>
<span style="color: #a1a100;">import java.lang.reflect.Modifier;</span>
<span style="color: #a1a100;">import java.util.Arrays;</span>
<span style="color: #a1a100;">import java.util.Collection;</span>
<span style="color: #a1a100;">import java.util.HashSet;</span>
<span style="color: #a1a100;">import java.util.Set; </span>
&nbsp;
<span style="color: #a1a100;">import org.apache.commons.logging.Log;</span>
<span style="color: #a1a100;">import org.apache.commons.logging.LogFactory;</span>
<span style="color: #a1a100;">import org.easymock.MockControl;</span>
<span style="color: #a1a100;">import org.easymock.classextension.MockClassControl; </span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Helper class to easily create mock class controls.
 *
 * EasyMockClassExtension v1.1 has a couple of undocumented 'features' which are
 * rather annoying.
 *
 * First of all, if the class we want to mock does not have any public
 * constructor, it is not possible to do
 * MockClassControl.createControl(MyClass.class), since the search for
 * constructors is limited to 'public' access modifier if class and parameter
 * values are not specified.
 *
 * Secondly, if toString(), equals() or hashCode() is overridden in the class we
 * want to mock, parameter matching on the resulting mock will not work, since
 * the above methods will be mocked by default, causing mock control validation
 * to fail.
 *
 * As a solution this helper class will by default instruct MockClassControl not
 * to mock toString(), equals() and hashCode() (alternatively any methods
 * specified by a call to setStdMethods()).
 *
 * Methods in Object will not be mocked.
 *
 * @author Mattias Arthursson
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MockClassControlHelper <span style="color: #66cc66;">&#123;</span>
    Log log = LogFactory.<span style="color: #006600;">getLog</span><span style="color: #66cc66;">&#40;</span>MockClassControlHelper.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Indicates that standard methods will be mocked.
     */</span>
    <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: #993333;">boolean</span> MOCK_STD_METHODS = <span style="color: #000000; font-weight: bold;">true</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Indicates that standard methods will be mocked.
     */</span>
    <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: #993333;">boolean</span> DONT_MOCK_STD_METHODS = <span style="color: #000000; font-weight: bold;">false</span>; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">boolean</span> mockStdMethods; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollection+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collection</span></a> stdMethods; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Initialize to not mock standard methods.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> MockClassControlHelper<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#40;</span>DONT_MOCK_STD_METHODS<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Initialize to mock standard methods depending on supplied parameter.
     *
     * @param mockStdMethods
     *            whether standard methods should be mocked.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> MockClassControlHelper<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">boolean</span> mockStdMethods<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">mockStdMethods</span> = mockStdMethods;
        stdMethods = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AArrays+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Arrays</span></a>.<span style="color: #006600;">asList</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #ff0000;">&quot;toString&quot;</span>, <span style="color: #ff0000;">&quot;equals&quot;</span>,
                <span style="color: #ff0000;">&quot;hashCode&quot;</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Get a MockClassControl for the supplied class using the first found
     * public or protected constructor. Standard methods will be mocked
     * depending on mockStdMethods.
     *
     * @param cls
     *            the class to mock.
     * @return a MockClassControl for the supplied class.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> MockControl getMockClassControl<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> cls<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AConstructor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Constructor</span></a> constructorToUse = getConstructorToUse<span style="color: #66cc66;">&#40;</span>cls<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
        <span style="color: #000000; font-weight: bold;">Class</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> parameters = constructorToUse.<span style="color: #006600;">getParameterTypes</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> values = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a><span style="color: #66cc66;">&#91;</span>parameters.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#93;</span>; 
&nbsp;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> methodsToMock = getMethodsToMock<span style="color: #66cc66;">&#40;</span>cls<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> MockClassControl.<span style="color: #006600;">createControl</span><span style="color: #66cc66;">&#40;</span>
                cls,
                parameters,
                values,
                methodsToMock<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Set the standard methods to omit if mockStdMethods is set to false
     * (default).
     *
     * @param methods
     *            Names of the methods to omit when mocking.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setStdMethods<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> methods<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        stdMethods = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AArrays+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Arrays</span></a>.<span style="color: #006600;">asList</span><span style="color: #66cc66;">&#40;</span>methods<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Set the standard methods to omit if mockStdMethods is set to false
     * (default).
     *
     * @param c
     *            Collection of names of the methods to omit when mocking.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setStdMethods<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollection+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collection</span></a> c<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        stdMethods = c;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Get the methods that will not be mocked.
     *
     * @return A collection of method names.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollection+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collection</span></a> getStdMethods<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> stdMethods;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Find a constructor to use. If public constructors are found, the first of
     * these is selected. Otherwise we check for a protected constructor, and
     * the first of these is used.
     *
     * @param cls
     *            Class to select a constructor from.
     * @return a public or protected constructor for the class.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AConstructor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Constructor</span></a> getConstructorToUse<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> cls<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AConstructor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Constructor</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> constructors = cls.<span style="color: #006600;">getConstructors</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>constructors.<span style="color: #006600;">length</span> == <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #808080; font-style: italic;">// No public constructors found.</span>
            constructors = cls.<span style="color: #006600;">getDeclaredConstructors</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>constructors.<span style="color: #006600;">length</span> == <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIllegalArgumentException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalArgumentException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Class '&quot;</span> + cls
                        + <span style="color: #ff0000;">&quot;' does not have any constructors&quot;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span> 
&nbsp;
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>; i &amp;lt; constructors.<span style="color: #006600;">length</span>; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #993333;">int</span> modifiers = constructors<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">getModifiers</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AModifier+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Modifier</span></a>.<span style="color: #006600;">isPublic</span><span style="color: #66cc66;">&#40;</span>modifiers<span style="color: #66cc66;">&#41;</span> || <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AModifier+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Modifier</span></a>.<span style="color: #006600;">isProtected</span><span style="color: #66cc66;">&#40;</span>modifiers<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
                <span style="color: #808080; font-style: italic;">// We've found a constructor which is public or</span>
                <span style="color: #808080; font-style: italic;">// protected - use that one.</span>
                <span style="color: #000000; font-weight: bold;">return</span> constructors<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span> 
&nbsp;
        <span style="color: #808080; font-style: italic;">// No public or protected constructor found.</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIllegalArgumentException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalArgumentException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Class '&quot;</span> + cls
                + <span style="color: #ff0000;">&quot;' does not have any public or protected constructors&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Figure out which methods of the class to mock. If mockStdMethods is set
     * to false, the standard methods are subtracted from all found methods for
     * the class. Otherwise all methods for the class is returned.
     *
     * @param cls
     *            The class to get methods for.
     * @return The methods to mock for the class.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> getMethodsToMock<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> cls<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
        <span style="color: #000000; font-weight: bold;">Class</span> currentClass = cls;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASet+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Set</span></a> methods = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AHashSet+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">HashSet</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
        <span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>currentClass != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> methodArray = currentClass.<span style="color: #006600;">getDeclaredMethods</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
            <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>; i &amp;lt; methodArray.<span style="color: #006600;">length</span>; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a> method = methodArray<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>;
                <span style="color: #993333;">boolean</span> isStandardMethod = stdMethods.<span style="color: #006600;">contains</span><span style="color: #66cc66;">&#40;</span>method
                        .<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
                <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>mockStdMethods || !isStandardMethod<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                    methods.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span>method<span style="color: #66cc66;">&#41;</span>;
                <span style="color: #66cc66;">&#125;</span> 
&nbsp;
                <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>method.<span style="color: #006600;">getModifiers</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &amp;amp; <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AModifier+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Modifier</span></a>.<span style="color: #000000; font-weight: bold;">FINAL</span><span style="color: #66cc66;">&#41;</span> &amp;gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                    log.<span style="color: #006600;">warn</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Final method, cannot be mocked: &quot;</span> + method<span style="color: #66cc66;">&#41;</span>;
                <span style="color: #66cc66;">&#125;</span>
            <span style="color: #66cc66;">&#125;</span> 
&nbsp;
            currentClass = currentClass.<span style="color: #006600;">getSuperclass</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>currentClass == <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                currentClass = <span style="color: #000000; font-weight: bold;">null</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span> 
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> methods.<span style="color: #006600;">toArray</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AMethod+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Method</span></a><span style="color: #66cc66;">&#91;</span>methods.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/05/09/mocking-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sweden Spring UG Birth of a new UG</title>
		<link>http://blog.jayway.com/2007/05/01/sweden-spring-ug-birth-of-a-new-ug/</link>
		<comments>http://blog.jayway.com/2007/05/01/sweden-spring-ug-birth-of-a-new-ug/#comments</comments>
		<pubDate>Tue, 01 May 2007 15:56:33 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[user group]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3829</guid>
		<description><![CDATA[Once in a while we see a new user group being born. One of those is close to many Java programmers’ hearts – the Sweden Spring User Group. We turned to Ulrik Sandberg, one of the founders of the group. Tell us how you got started with the Sweden Spring User Group. The Sweden Spring [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Once in a while we see a new user group being born. One of those is close to many Java programmers’ hearts – the Sweden Spring User Group.</strong></p>
<p>We turned to Ulrik Sandberg, one of the founders of the group.</p>
<p><strong>Tell us how you got started with the Sweden Spring User Group.</strong><br />
The Sweden Spring User Group was started in early 2007. I had spoken to Rod Johnson at The Spring Experience 2006 about creating a user group for Swedish users, and he thought that was an excellent idea. We decided to use Google Groups as the tool for collabo- ration. Jayway would be our financial backup, since we wanted to provide the group members with first-class confer- ence facilities, as well as food and drink.</p>
<p><strong>Which are your goals?</strong><br />
Our primary goal is to gather all Swedish Spring users in a community, in order to get a forum where you can ask questions and present ideas to peo- ple who share the interest for Spring. We also want to provide high-quality sessions when we meet. The sessions should be held by the community, but we also aim to get an external speaker from either Interface21 or other inter- esting companies related to Spring.</p>
<p><strong>What have you been doing so far?</strong><br />
The first meeting was held in late March, in Stockholm. We managed to get Arjen Poutsma from Interface21 to hold a session about Duck Typing in the Spring WebServices framework. Before that, there had been an Introduction to Spring and a session about the Aspect- Oriented Programming (AOP) support in Spring 2.0. It was very crowded, and people really enjoyed the short break for beer and pizza.<br />
The second meeting in early July was also in Stockholm. The main speaker at that event was Ben Alex from Inter- face21, the inventor of Spring Security, previously known as Acegi Security. He had come all the way from Australia and held a session about his Real Object- Oriented (ROO) framework. There was also a session about Spring JDBC and a very interesting case study about the use of Spring MVC at PriceRunner.<br />
The third meeting took place in Malmö in late September. The guest of honor was Jonas Bonér from Terracotta. He talked about how easy it is to clus- ter Java applications using Terracotta. There was a session about Spring and Mule, as well as a session about Declara- tive Caching Using Spring.</p>
<p><strong>So what is your final message to the readers?</strong><br />
In short, the Sweden Spring User Group arranges high-quality mini-con- ferences about Spring and related tech- nologies four times a year. For free. You should join us.</p>
<p><em>Ulrik Sandberg, Björn Granvik</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/05/01/sweden-spring-ug-birth-of-a-new-ug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sharing a Mac Internet Connection Through Airport</title>
		<link>http://blog.jayway.com/2007/01/20/sharing-a-mac-internet-connection-through-airport/</link>
		<comments>http://blog.jayway.com/2007/01/20/sharing-a-mac-internet-connection-through-airport/#comments</comments>
		<pubDate>Sat, 20 Jan 2007 22:02:03 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=183</guid>
		<description><![CDATA[I just solved a networking problem on my Macs after hours of trying. For the benefit of others, I'll describe here the problem and the solution. Setup Cable modem from ISP, network cable to a firewall, the private end of the firewall via network cable on to a switch. Pretty basic, I guess. No wireless [...]]]></description>
			<content:encoded><![CDATA[<p>I just solved a networking problem on my Macs after hours of trying. For the benefit of others, I'll describe here the problem and the solution.</p>
<h3>Setup</h3>
<p>Cable modem from ISP, network cable to a firewall, the private end of the firewall via network cable on to a switch. Pretty basic, I guess. No wireless base stations or anything. Just an iMac connected via network cable to the switch.</p>
<h3>Problem</h3>
<p>Share the iMac's network cable connection through its Airport wireless capability. The client is a MacBook Pro. Basically, I just want to get Internet access on my laptop via the iMac. Sounds simple, but hey, it took me half a day and plenty of research to figure out.</p>
<h4>Useful pieces of information gathered during this adventure</h4>
<ol>
<li>Turning on Internet Connection Sharing (ICS) will start a DHCP server.</li>
<li>Turning on ICS will create a full Airport network (not a computer-to-computer network).</li>
<li>Turning on ICS will create a new network configuration for 10.0.2.1, which I understand is the same address as the Airport base stations use.</li>
</ol>
<h3>Solution</h3>
<ol>
<li>On the iMac, set the Airport network to "Use DHCP with manual address" and set the IP to 10.0.2.1. Set the DNS servers to the ones recommended by your ISP. Apply.</li>
<li>On the iMac, go to Sharing|Internet and choose AirPort Options. Enable WEP encryption (I chose 40-bit with a 5 character password). The default network name is your computer name. I added a postfix to the network name ("-ics") so I can distinguish it from the computer-to-computer network. Apply.</li>
<li>Now start sharing your Built-in Ethernet connection to computers using Airport. As I mentioned previously, this will create the new network and also start a DHCP server.</li>
<li>On the MacBook, set the Airport network to "Use DHCP". Leave all fields blank.</li>
<li>On the MacBook, connect to the newly created network, which should be named "hostname-ics" if you followed my naming advice earlier. Watch the network configuration. Eventually it shows the IP 10.0.2.2.</li>
</ol>
<p>That's it. You should now have access to your other machines on your private network, but also to Internet.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/01/20/sharing-a-mac-internet-connection-through-airport/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Solving 403 problems with Sourceforge Subversion</title>
		<link>http://blog.jayway.com/2007/01/13/solving-403-problems-with-sourceforge-subversion/</link>
		<comments>http://blog.jayway.com/2007/01/13/solving-403-problems-with-sourceforge-subversion/#comments</comments>
		<pubDate>Sat, 13 Jan 2007 16:54:42 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[dns]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[sourceforge]]></category>
		<category><![CDATA[subversion]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=177</guid>
		<description><![CDATA[After having had severe problems when committing to the Sourceforge Subversion repos, I stumbled upon what appears to be the solution. The problem was that in the middle of a commit, one file or directory would fail with a 403 (permission denied). In desperation, I would chop up the change set and commit little pieces [...]]]></description>
			<content:encoded><![CDATA[<p>After having had severe problems when committing to the Sourceforge Subversion repos, I stumbled upon what appears to be the solution. The problem was that in the middle of a commit, one file or directory would fail with a 403 (permission denied). In desperation, I would chop up the change set and commit little pieces at the time, until only the ones with problems remained. I would then perform desperate unnamed actions with these until they eventually were committed. Pretty nerve-wrecking, time-consuming, and unproductive stuff. The worst part is that if you split the change set, you could end up splitting a move operation, which is basically a copy and a delete. Say that you commit the delete operation successfully first. Then you try to commit the copy, which will fail with a 404 (not found), since the stuff it tries to copy has been deleted. There are ways around it, but I won't describe them here. Horrible stuff.</p>
<p>I had seen somewhere that you could get the 403 error if you were using SSL (which I was) and the Sourceforge server <tt>svn.sourceforge.net</tt>. The correct server is the <tt>PROJECTNAME.svn.sourceforge.net</tt>, where <tt>PROJECTNAME</tt> in my case was <tt>springframework</tt>. So <b>the correct URL to use is <tt>https://springframework.svn.sourceforge.net/svnroot/springframework/</tt>.</b> This meant changing the checkout URL, which Subversion can do on an already checked-out working copy, using the <tt>switch</tt> command. Cool. When I tried this, it failed because it couldn't find the new server. The problem was that the DNS servers I was using at some point didn't find this server, and probably cached this negative hit. Eventually I found a DNS that could locate this server and performed the switch. Things have been working much better since.</p>
<p>Using the incorrect server, which most likely is a proxy server of some sort, could possibly have resulted in different physical servers being used for different requests during the Subversion transaction. It's not allowed to perform a <tt>svn copy</tt> operation between repositories. You'll get a 403 if you try it. Perhaps that rule applied to my situation as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/01/13/solving-403-problems-with-sourceforge-subversion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A cool GMail feature</title>
		<link>http://blog.jayway.com/2007/01/03/a-cool-gmail-feature/</link>
		<comments>http://blog.jayway.com/2007/01/03/a-cool-gmail-feature/#comments</comments>
		<pubDate>Wed, 03 Jan 2007 16:34:37 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[mail]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=172</guid>
		<description><![CDATA[Google Mail will deliver a mail even though the recipient address ends with '+' and some more text, like john.doe+msn@gmail.com for example. This feature can be used to create an unlimited number of mail addresses that can be used for registration purposes. For example, say that the MSN web site requires your email address for [...]]]></description>
			<content:encoded><![CDATA[<p>Google Mail will deliver a mail even though the recipient address ends with '+' and some more text, like <tt>john.doe+msn@gmail.com</tt> for example. This feature can be used to create an unlimited number of mail addresses that can be used for registration purposes. For example, say that the MSN web site requires your email address for you to download some stuff you need. You don't want to give up your real email, since you're afraid you'll be spammed. Yet you need to give a valid email since they might send registration information to it, like the password. The solution is to use <tt>john.doe+msn@gmail.com</tt> and the mails will still be delivered to the <tt>john.doe</tt> mailbox. However, you can now quickly identify if the address you gave when you registered at MSN has been used for spam, and create a filter to handle them. GMail filters allow you to perform any or all of the following actions: archive, delete, label, forward, mark with a star.</p>
<p>Note that although this follows the Internet standard for email addresses (<a href="http://www.ietf.org/rfc/rfc0822.txt">RFC 822</a>), some sites simply ignore this and incorrectly disallows addresses with plus signs.</p>
<p>Read more <a href="http://21st.blogspot.com/2006/09/use-gmail-generate-unlimited-e-mail.html">here</a>. More cool mail tips can be found <a href="http://www.howtohut.com/tag/email">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/01/03/a-cool-gmail-feature/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Indented Tracing Using AspectJ</title>
		<link>http://blog.jayway.com/2006/12/15/indented-tracing-using-aspectj/</link>
		<comments>http://blog.jayway.com/2006/12/15/indented-tracing-using-aspectj/#comments</comments>
		<pubDate>Fri, 15 Dec 2006 15:36:14 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tracing]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=188</guid>
		<description><![CDATA[Given inspiration from the book "AspectJ In Action", I wrote a little aspect that provides indented tracing of method executions. This means that the aspect keeps track of the current indentation level in a call flow, giving an output like the following: Entering [org.springframework.ldap.LdapTemplateListTest.] Exiting [org.springframework.ldap.LdapTemplateListTest.] Entering [org.springframework.ldap.LdapTemplateListTest.setUp] Entering [org.springframework.ldap.LdapTemplate.] Entering [org.springframework.ldap.DefaultNamingExceptionTranslator.] Exiting [org.springframework.ldap.DefaultNamingExceptionTranslator.] Exiting [...]]]></description>
			<content:encoded><![CDATA[<p>Given inspiration from the book "AspectJ In Action", I wrote a little aspect that provides indented tracing of method executions. This means that the aspect keeps track of the current indentation level in a call flow<span id="more-188"></span>, giving an output like the following:</p>
<pre>Entering [org.springframework.ldap.LdapTemplateListTest.]
Exiting [org.springframework.ldap.LdapTemplateListTest.]
Entering [org.springframework.ldap.LdapTemplateListTest.setUp]
  Entering [org.springframework.ldap.LdapTemplate.]
    Entering [org.springframework.ldap.DefaultNamingExceptionTranslator.]
    Exiting [org.springframework.ldap.DefaultNamingExceptionTranslator.]
  Exiting [org.springframework.ldap.LdapTemplate.]
  Entering [org.springframework.ldap.LdapTemplate.setExceptionTranslator]
  Exiting [org.springframework.ldap.LdapTemplate.setExceptionTranslator]
Exiting [org.springframework.ldap.LdapTemplateListTest.setUp]
Entering [org.springframework.ldap.LdapTemplateListTest.testList_Name]
  Entering [org.springframework.ldap.LdapTemplateListTest.expectGetReadOnlyContext]
  ...</pre>
<p>The part that keeps track of the indentation level was written as a reusable aspect:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> org.<span style="color: #006600;">springframework</span>.<span style="color: #006600;">ldap</span>.<span style="color: #006600;">aspects</span>; 
&nbsp;
<span style="color: #a1a100;">import org.apache.commons.logging.Log;</span>
<span style="color: #a1a100;">import org.apache.commons.logging.LogFactory;</span>
<span style="color: #a1a100;">import org.aspectj.lang.JoinPoint; </span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Abstract logging aspect for producing indented logging. Override the
 * &lt;code&gt;loggingOperations&lt;/code&gt; pointcut in order to provide the joinpoints
 * where you would like the logging to be applied. Also override the methods
 * &lt;code&gt;beforeLog&lt;/code&gt; and &lt;code&gt;afterLog&lt;/code&gt; to provide the actual
 * logging statements. The current indentation string will be provided to these
 * methods, along with an instance of &lt;code&gt;JoinPoint&lt;/code&gt;.
 *
 * @author Ulrik Sandberg
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> aspect IndentedLogging <span style="color: #66cc66;">&#123;</span>
    Log log = LogFactory.<span style="color: #006600;">getLog</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;trace&quot;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * The current number of indentation levels.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">int</span> indentationlevel = <span style="color: #cc66cc;">0</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Override and provide pointcut to log.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> pointcut loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Override and provide the actual logging statement for when the logged
     * method is entered.
     *
     * @param indent
     *            The string of spaces that provides the current indentation.
     * @param joinPoint
     *            Information about the current joinpoint.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #993333;">void</span> beforeLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #808080; font-style: italic;">/**
     * Override and provide the actual logging statement for when the logged
     * method is exited.
     *
     * @param indent
     *            The string of spaces that provides the current indentation.
     * @param joinPoint
     *            Information about the current joinpoint.
     */</span>
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #993333;">void</span> afterLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> around<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>: loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a> sb = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>log.<span style="color: #006600;">isInfoEnabled</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            indentationlevel++;
            <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>, spaces = indentationlevel * <span style="color: #cc66cc;">2</span>; i &amp;lt; spaces; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot; &quot;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
            beforeLog<span style="color: #66cc66;">&#40;</span>sb.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, thisJoinPoint<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> result;
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #66cc66;">&#123;</span>
            result = proceed<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>log.<span style="color: #006600;">isInfoEnabled</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                afterLog<span style="color: #66cc66;">&#40;</span>sb.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, thisJoinPoint<span style="color: #66cc66;">&#41;</span>;
                indentationlevel--;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> result;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>Since the reusable aspect does all the grunt work, the actual tracing aspect becomes rather small:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> org.<span style="color: #006600;">springframework</span>.<span style="color: #006600;">ldap</span>.<span style="color: #006600;">aspects</span>; 
&nbsp;
<span style="color: #a1a100;">import org.aspectj.lang.JoinPoint; </span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> aspect TraceAspect <span style="color: #000000; font-weight: bold;">extends</span> IndentedLogging <span style="color: #66cc66;">&#123;</span>
    declare precedence: TraceAspect, *; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> pointcut loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:
        <span style="color: #66cc66;">&#40;</span>execution<span style="color: #66cc66;">&#40;</span>* *.<span style="color: #006600;">*</span><span style="color: #66cc66;">&#40;</span>..<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> || execution<span style="color: #66cc66;">&#40;</span>*.<span style="color: #000000; font-weight: bold;">new</span><span style="color: #66cc66;">&#40;</span>..<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        &amp;amp;&amp;amp; !within<span style="color: #66cc66;">&#40;</span>IndentedLogging+<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> beforeLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span>indent + <span style="color: #ff0000;">&quot;Entering [&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringTypeName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;.&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;]&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> afterLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span>indent + <span style="color: #ff0000;">&quot;Exiting [&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringTypeName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;.&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;]&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>Now, let's say we don't want to trace each and every method and constructor execution, but rather a small subset, like for example only the normal methods (no constructors) in any subclass of <code>NameClassPairCallbackHandler</code>. We'll remove the execution of <code>new</code> from the pointcut and add the handler subclass condition:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> aspect TraceAspect <span style="color: #000000; font-weight: bold;">extends</span> IndentedLogging <span style="color: #66cc66;">&#123;</span>
    declare precedence: TraceAspect, *; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> pointcut loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:
        execution<span style="color: #66cc66;">&#40;</span>* *.<span style="color: #006600;">*</span><span style="color: #66cc66;">&#40;</span>..<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// just plain methods</span>
        &amp;amp;&amp;amp; !within<span style="color: #66cc66;">&#40;</span>IndentedLogging+<span style="color: #66cc66;">&#41;</span>
        &amp;amp;&amp;amp; within<span style="color: #66cc66;">&#40;</span>org.<span style="color: #006600;">springframework</span>.<span style="color: #006600;">ldap</span>.<span style="color: #006600;">NameClassPairCallbackHandler</span>+<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// added</span>
    ...</pre>
<p>The output becomes:</p>
<pre>Entering [org.springframework.ldap.CollectingNameClassPairCallbackHandler.handleNameClassPair]
  Entering [org.springframework.ldap.LdapTemplate$MappingCollectingNameClassPairCallbackHandler.getObjectFromNameClassPair]
  Exiting [org.springframework.ldap.LdapTemplate$MappingCollectingNameClassPairCallbackHandler.getObjectFromNameClassPair]
Exiting [org.springframework.ldap.CollectingNameClassPairCallbackHandler.handleNameClassPair]
Entering [org.springframework.ldap.CollectingNameClassPairCallbackHandler.getList]
Exiting [org.springframework.ldap.CollectingNameClassPairCallbackHandler.getList]</pre>
<p>You might argue that it would be good to see the arguments to each call. That could easily be done by using <code>JoinPoint.getArgs()</code> in the tracing aspect. It would look like this:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> org.<span style="color: #006600;">springframework</span>.<span style="color: #006600;">ldap</span>.<span style="color: #006600;">aspects</span>; 
&nbsp;
<span style="color: #a1a100;">import org.aspectj.lang.JoinPoint; </span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> aspect TraceAspect <span style="color: #000000; font-weight: bold;">extends</span> IndentedLogging <span style="color: #66cc66;">&#123;</span>
    declare precedence: TraceAspect, *; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> pointcut loggingOperations<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:
        <span style="color: #66cc66;">&#40;</span>execution<span style="color: #66cc66;">&#40;</span>* *.<span style="color: #006600;">*</span><span style="color: #66cc66;">&#40;</span>..<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        &amp;amp;&amp;amp; !within<span style="color: #66cc66;">&#40;</span>IndentedLogging+<span style="color: #66cc66;">&#41;</span>
        &amp;amp;&amp;amp; within<span style="color: #66cc66;">&#40;</span>*..<span style="color: #006600;">NameClassPairCallbackHandler</span>+<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> beforeLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span>indent + <span style="color: #ff0000;">&quot;Entering [&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringTypeName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;.&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
                + createParameterMessage<span style="color: #66cc66;">&#40;</span>indent, joinPoint<span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;]&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> afterLog<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span>indent + <span style="color: #ff0000;">&quot;Exiting [&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringTypeName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;.&quot;</span>
                + joinPoint.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
                + createParameterMessage<span style="color: #66cc66;">&#40;</span>indent, joinPoint<span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;]&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> createParameterMessage<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> indent, JoinPoint joinPoint<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a> sb = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AStringBuffer+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">StringBuffer</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;(&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> args = joinPoint.<span style="color: #006600;">getArgs</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>args.<span style="color: #006600;">length</span> &amp;gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>    &quot;</span> + indent<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>; i &amp;lt; args.<span style="color: #006600;">length</span>; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>i != args.<span style="color: #006600;">length</span> - <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">','</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span>
        sb.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;)&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000000; font-weight: bold;">return</span> sb.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>And the output would be this:</p>
<pre>Entering [org.springframework.ldap.CollectingNameClassPairCallbackHandler.handleNameClassPair(
    o=example.com: com.example.SomeClass)]
  Entering [org.springframework.ldap.LdapTemplate$MappingCollectingNameClassPairCallbackHandler.getObjectFromNameClassPair(
      o=example.com: com.example.SomeClass)]
  Exiting [org.springframework.ldap.LdapTemplate$MappingCollectingNameClassPairCallbackHandler.getObjectFromNameClassPair(
      o=example.com: com.example.SomeClass)]
Exiting [org.springframework.ldap.CollectingNameClassPairCallbackHandler.handleNameClassPair(
    o=example.com: com.example.SomeClass)]
Entering [org.springframework.ldap.CollectingNameClassPairCallbackHandler.getList()]
Exiting [org.springframework.ldap.CollectingNameClassPairCallbackHandler.getList()]</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2006/12/15/indented-tracing-using-aspectj/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Tired of Date and Calendar?</title>
		<link>http://blog.jayway.com/2006/09/16/tired-of-date-and-calendar/</link>
		<comments>http://blog.jayway.com/2006/09/16/tired-of-date-and-calendar/#comments</comments>
		<pubDate>Sat, 16 Sep 2006 12:56:39 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[User Experience]]></category>
		<category><![CDATA[calendar]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[jodatime]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=250</guid>
		<description><![CDATA[It's not always easy to decide whether to add yet another dependency to yet another framework. It's especially hard when it's about a very central part of the JDK, like Date and Calendar. They are not great, there's little doubt about that. However, the benefits of a new framework would have to be numerous in [...]]]></description>
			<content:encoded><![CDATA[<p>It's not always easy to decide whether to add yet another dependency to yet another framework. It's especially hard when it's about a very central part of the JDK, like Date and Calendar. They are not great, there's little doubt about that. However, the benefits of a new framework would have to be numerous in order for us to make the switch. It must also be simple to convert between the standard classes and the framework classes. The impact on our project must be minimal. Ideally, it would be a question of dropping in a single jar-file. This article not only finds the weak spots of Date and Calendar, but also presents a compelling alternative.</p>
<h3>How bad are Date and Calendar?</h3>
<p>Consider <code>java.util.Date</code>. It has been around since JDK 1.0, and it's actually not a date, but a date and a time. In order to get the date (and the time), you call the <code>getTime()</code> method. It uses two-digit years from 1900, day-of-month is one-based, while month and hours are zero-based, it should have been immutable, and most methods have been deprecated in JDK 1.1. Since it's not final, it's possible to hack it by overriding critical methods, like for example <code>after</code>.</p>
<p>The state of <code>java.util.Calendar</code> is not much better. Month is zero-based, it should have been immutable, and it allows only one hour offset for daylight savings time. Some years have more, you know. British timezone in 1943, 1944 and 1945, for example, had two hours. The worst part is that it uses two different representations internally: a value for each field, and milliseconds since 1970. The scary part is that these two representations are not continuously kept in synch. Instead they are resynched as a side effect of other method calls, like <code>equals</code> for example. Wouldn't that be something? You call <code>equals</code> on your <code>Calendar</code> and suddenly it changes to a different date.</p>
<p>Then we have <code>java.util.SimpleDateFormat</code>. It requires a <code>Date</code> object, it's not very fast, and it's not thread-safe. If concurrent threads call its <code>format</code> method on a shared instance, it can produce bizarre results.</p>
<h4>They can't be that bad, can they?</h4>
<p>Let's print out a date. We want July 2, 1945 and the time should be 12.30 PM. Here we go:</p>
<pre class="java">&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a> date = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1945</span>, <span style="color: #cc66cc;">7</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">12</span>, <span style="color: #cc66cc;">30</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>date.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Sat Aug 02 12:30:00 CEST 3845</span>
&nbsp;</pre>
<p>Oops. Forgot the two-digit year and the zero-based month. Let's try again:</p>
<pre class="java">&nbsp;
<span style="color: #993333;">int</span> year = <span style="color: #cc66cc;">1945</span> - <span style="color: #cc66cc;">1900</span>;
<span style="color: #993333;">int</span> month = <span style="color: #cc66cc;">7</span> - <span style="color: #cc66cc;">1</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a> date = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a><span style="color: #66cc66;">&#40;</span>year, month, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">12</span>, <span style="color: #cc66cc;">30</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>date.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Mon Jul 02 12:30:00 CEST 1945</span>
&nbsp;</pre>
<p>Yes, I know that the constructor used above is deprecated. This is how it really should be done:</p>
<pre class="java">&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a> tz = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a>.<span style="color: #006600;">getTimeZone</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/Tokyo&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a> cal = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a>.<span style="color: #006600;">getInstance</span><span style="color: #66cc66;">&#40;</span>tz<span style="color: #66cc66;">&#41;</span>;
cal.<span style="color: #006600;">set</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1945</span>, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a>.<span style="color: #006600;">JULY</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">12</span>, <span style="color: #cc66cc;">30</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADateFormat+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">DateFormat</span></a> f= <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASimpleDateFormat+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">SimpleDateFormat</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;yyyy-MM-dd hh:mm&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>f.<span style="color: #006600;">format</span><span style="color: #66cc66;">&#40;</span>cal<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// java.lang.IllegalArgumentException: Cannot format given Object as a Date</span>
<span style="color: #808080; font-style: italic;">// at java.text.DateFormat.format(DateFormat.java:279)</span>
<span style="color: #808080; font-style: italic;">// at java.text.Format.format(Format.java:133)</span>
&nbsp;</pre>
<p>Oops. <code>DateFormat</code> cannot take a <code>Calendar</code>. Let's try with a <code>Date</code>:</p>
<pre class="java">&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a> tz = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a>.<span style="color: #006600;">getTimeZone</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/Tokyo&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a> cal = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a>.<span style="color: #006600;">getInstance</span><span style="color: #66cc66;">&#40;</span>tz<span style="color: #66cc66;">&#41;</span>;
cal.<span style="color: #006600;">set</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1945</span>, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a>.<span style="color: #006600;">JULY</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">12</span>, <span style="color: #cc66cc;">30</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADateFormat+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">DateFormat</span></a> f= <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASimpleDateFormat+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">SimpleDateFormat</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;yyyy-MM-dd hh:mm&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a> date = cal.<span style="color: #006600;">getTime</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>f.<span style="color: #006600;">format</span><span style="color: #66cc66;">&#40;</span>date<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// 1945-07-02 06:30</span>
&nbsp;</pre>
<p>Well, almost right. I asked for the time to be 12.30, not 6.30. Ah, of course. It's not enough to set the timezone on the <code>Calendar</code> that we used to get the <code>Date</code> that we want to print. The <code>DateFormat</code> that prints the <code>Date</code> also needs the timezone. Silly me.</p>
<pre class="java">&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a> tz = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a>.<span style="color: #006600;">getTimeZone</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/Tokyo&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a> cal = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a>.<span style="color: #006600;">getInstance</span><span style="color: #66cc66;">&#40;</span>tz<span style="color: #66cc66;">&#41;</span>;
cal.<span style="color: #006600;">set</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1945</span>, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Calendar</span></a>.<span style="color: #006600;">JULY</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">12</span>, <span style="color: #cc66cc;">30</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADateFormat+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">DateFormat</span></a> f= <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASimpleDateFormat+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">SimpleDateFormat</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;yyyy-MM-dd hh:mm&quot;</span><span style="color: #66cc66;">&#41;</span>;
f.<span style="color: #006600;">setTimeZone</span><span style="color: #66cc66;">&#40;</span>cal.<span style="color: #006600;">getTimeZone</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a> date = cal.<span style="color: #006600;">getTime</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>f.<span style="color: #006600;">format</span><span style="color: #66cc66;">&#40;</span>date<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// 1945-07-02 12:30</span>
&nbsp;</pre>
<p>Finally.</p>
<h3>The Contender: Joda-Time</h3>
<p>There is a candidate that has all the characteristics we mentioned earlier, and more: <a href="http://joda-time.sourceforge.net/index.html">Joda-Time</a>. It's a single jar of 518k with no other dependencies. It replaces <code>Date</code>, <code>Calendar</code> and <code>TimeZone</code>. It has interfaces for datetimes, intervals and durations. The key classes are immutable. It has a pluggable calendar system where the default is ISO8601. And one more thing: it's easy to use.</p>
<h4>DateTime</h4>
<p>The most useful class in Joda-Time is the <code>DateTime</code>, which is immutable and thread-safe. It is measured in milliseconds since 1970, and it has simple getters for all fields. It supports timezones and multiple calendar systems. Its main purpose is to fill the most common needs as simple as possible:</p>
<pre class="java">&nbsp;
DateTime now = <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #993333;">int</span> y = now.<span style="color: #006600;">getYear</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> hour = now.<span style="color: #006600;">getHourOfDay</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> sec = now.<span style="color: #006600;">getSecondOfMinute</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #993333;">boolean</span> leap = now.<span style="color: #006600;">year</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">isLeap</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> daysInMonth = now.<span style="color: #006600;">dayOfMonth</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getMaximumValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Since it's immutable, all mutating methods return new objects:</p>
<pre class="java">&nbsp;
DateTime now = <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
DateTime yesterday = now.<span style="color: #006600;">minusDays</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">plusHours</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h4>Partial</h4>
<p>Partially defined datetimes have no timezone; they use local time. They are called "partial" because they don't have all the fields of a <code>DateTime</code>. We have <code>YearMonthDay</code>, <code>TimeOfDay</code> (hour, minute, second, and millisecond), and <code>Partial</code> (can store any fields). They can easily be converted to <code>DateTime</code>:</p>
<pre class="java">&nbsp;
YearMonthDay ymd = <span style="color: #000000; font-weight: bold;">new</span> YearMonthDay<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2005</span>, <span style="color: #cc66cc;">9</span>, <span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// September 20, 2005</span>
TimeOfDay tod = <span style="color: #000000; font-weight: bold;">new</span> TimeOfDay<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">14</span>, <span style="color: #cc66cc;">15</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
DateTimeZone zone = DateTimeZone.<span style="color: #006600;">forID</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/Tokyo&quot;</span><span style="color: #66cc66;">&#41;</span>;
DateTime dt = ymd.<span style="color: #006600;">toDateTimeAtCurrentTime</span><span style="color: #66cc66;">&#40;</span>zone<span style="color: #66cc66;">&#41;</span>;
DateTime dt2 = ymd.<span style="color: #006600;">toDateTime</span><span style="color: #66cc66;">&#40;</span>tod<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h4>Period</h4>
<p>A <code>Period</code> represents a period of time, like "5 years, 3 months, 2 days and 12 hours":</p>
<pre class="java">&nbsp;
Period period = <span style="color: #000000; font-weight: bold;">new</span> Period<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">12</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> years = period.<span style="color: #006600;">getYears</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> days = period.<span style="color: #006600;">getDays</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h4>Interval</h4>
<p>The class <code>Interval</code> represents an interval of time, represented by a start <code>DateTime</code> (included) and an end <code>DateTime</code> (excluded). Let's say we want to know how many complete weeks an interval is. To do that, we convert the <code>Interval</code> to a <code>Period</code> of the specific type we want. Using <code>PeriodType</code>, we can deduce that the interval below is 9 complete weeks (<code>P9W</code> is ISO8601-standard for a 9 week period):</p>
<pre class="java">&nbsp;
DateMidnight start = <span style="color: #000000; font-weight: bold;">new</span> DateMidnight<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2005</span>, <span style="color: #cc66cc;">7</span>, <span style="color: #cc66cc;">12</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// July 12, 2005</span>
DateMidnight end = <span style="color: #000000; font-weight: bold;">new</span> DateMidnight<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2005</span>, <span style="color: #cc66cc;">9</span>, <span style="color: #cc66cc;">15</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// September 15, 2005</span>
Interval interval = <span style="color: #000000; font-weight: bold;">new</span> Interval<span style="color: #66cc66;">&#40;</span>start, end<span style="color: #66cc66;">&#41;</span>;
Period period = interval.<span style="color: #006600;">toPeriod</span><span style="color: #66cc66;">&#40;</span>PeriodType.<span style="color: #006600;">weeks</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>period<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// P9W</span>
&nbsp;</pre>
<h4>Chronology</h4>
<p>Joda-Time features a pluggable calendar system based on the <code>Chronology</code> class. There are for example ISO9601, Gregorian, Julian, GJ, Buddhist, Ethiopic, and Coptic. The default is <code>ISOChronology</code>. A <code>Chronology</code> can be passed in as extra parameter whenever needed, as in the following example where we print the year 2006 as the Buddhists see it:</p>
<pre class="java">&nbsp;
Chronology buddhist = BuddhistChronology.<span style="color: #006600;">getInstance</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
DateTime now = <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span>buddhist<span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> year = now.<span style="color: #006600;">getYear</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// 2006</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>year<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// 2549</span>
&nbsp;</pre>
<h4>Time Zone</h4>
<p>The <code>DateTimeZone</code> class encapsulates a time zone that contains not only the timezones in the current JDK implementations, but is also up to date with the most current time zone data available at the <a href="http://www.twinsun.com/tz/tz-link.htm">time zone database</a>.</p>
<pre class="java">&nbsp;
DateTimeZone.<span style="color: #006600;">UTC</span>;
DateTimeZone.<span style="color: #006600;">forID</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/Tokyo&quot;</span><span style="color: #66cc66;">&#41;</span>;
DateTimeZone.<span style="color: #006600;">forOffsetHours</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#41;</span>;
DateTimeZone.<span style="color: #006600;">forTimeZone</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a>.<span style="color: #006600;">getTimeZone</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Europe/Stockholm&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>One problem with the JDK <code>TimeZone</code> is that it returns timezone UTC (also known as GMT) if the full name cannot be understood:</p>
<pre class="java">&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a> validTz = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a>.<span style="color: #006600;">getTimeZone</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/Tokyo&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>validTz<span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a> invalidTz = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ATimeZone+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">TimeZone</span></a>.<span style="color: #006600;">getTimeZone</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/SomeUnknownCity&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>invalidTz<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// sun.util.calendar.ZoneInfo[id=&quot;Asia/Tokyo&quot;,offset=32400000,dstSavings=0,useDaylight=false,...</span>
<span style="color: #808080; font-style: italic;">// sun.util.calendar.ZoneInfo[id=&quot;GMT&quot;,offset=0,dstSavings=0,useDaylight=false,...</span>
&nbsp;</pre>
<p>By contrast, Joda-Time's <code>DateTimeZone</code> throws an <code>IllegalArgumentException</code> if it cannot understand the time zone name:</p>
<pre class="java">&nbsp;
DateTimeZone validTz = DateTimeZone.<span style="color: #006600;">forID</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/Tokyo&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>validTz<span style="color: #66cc66;">&#41;</span>;
DateTimeZone invalidTz = DateTimeZone.<span style="color: #006600;">forID</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Asia/SomeUnknownCity&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>invalidTz<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Asia/Tokyo</span>
<span style="color: #808080; font-style: italic;">// java.lang.IllegalArgumentException: The datetime zone id is not recognised: Asia/SomeUnknownCity</span>
<span style="color: #808080; font-style: italic;">// at org.joda.time.DateTimeZone.forID(DateTimeZone.java:198)</span>
&nbsp;</pre>
<h4>Interoperability</h4>
<p>One of our requirements for a new framework was that it should be easy to convert to and from the standard classes. Constructors in Joda-Time take <code>Date</code>, <code>Calendar</code>, <code>String</code>, and <code>long</code>. From <code>DateTime</code> we can easily get JDK <code>Date</code> and <code>Calendar</code>. The <code>DateTimeZone</code> class can be constructed from a <code>TimeZone</code> and also return a <code>TimeZone</code>. In the example below, we easily convert from a standard <code>Date</code> to Joda-Time's <code>DateTime</code> to a <code>GregorianCalendar</code>, and from the <code>DateTime</code> back to a <code>Date</code>:</p>
<pre class="java">&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a> date = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">106</span>, <span style="color: #cc66cc;">8</span>, <span style="color: #cc66cc;">19</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// Sep 19, 2006</span>
DateTime dt = <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span>date<span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AGregorianCalendar+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">GregorianCalendar</span></a> c = dt.<span style="color: #006600;">toGregorianCalendar</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADate+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Date</span></a> d = dt.<span style="color: #006600;">toDate</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h4>Formatting</h4>
<p>What about formatting then? Compared to <code>SimpleDateFormat</code>, the <code>DateTimeFormatter</code> is fast, flexible, thread-safe, and immutable. Formatting can be done in several ways: using a pattern, a style, or a format builder. You can either pass a formatter to the <code>toString</code> method for <code>DateTime</code>, or you can ask the formatter to print the <code>DateTime</code>:</p>
<pre class="java">&nbsp;
DateTimeFormatter f = DateTimeFormat.<span style="color: #006600;">longDateTime</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
DateTime dateTime = <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>dateTime.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span>f<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>f.<span style="color: #006600;">print</span><span style="color: #66cc66;">&#40;</span>dateTime<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// May 25, 2006 9:45:09 PM CEST</span>
<span style="color: #808080; font-style: italic;">// May 25, 2006 9:45:09 PM CEST</span>
&nbsp;</pre>
<h4>DateTimeUtils</h4>
<p>If you need to stop time, or go back or forward in time, you can use the <code>DateTimeUtils</code> class. This code shows that it's possible to stop time:</p>
<pre class="java">&nbsp;
DateTime now = <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
DateTimeUtils.<span style="color: #006600;">setCurrentMillisFixed</span><span style="color: #66cc66;">&#40;</span>now.<span style="color: #006600;">getMillis</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// time has stopped!</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a>.<span style="color: #006600;">sleep</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2000</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// 2006-05-25T23:21:37.562+02:00</span>
<span style="color: #808080; font-style: italic;">// 2006-05-25T23:21:37.562+02:00</span>
&nbsp;</pre>
<p>Turning back the clock is also possible:</p>
<pre class="java">&nbsp;
DateTime now = <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
Period period = Period.<span style="color: #006600;">months</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">-1</span><span style="color: #66cc66;">&#41;</span>;
Duration dur = period.<span style="color: #006600;">toDurationFrom</span><span style="color: #66cc66;">&#40;</span>now<span style="color: #66cc66;">&#41;</span>;
DateTimeUtils.<span style="color: #006600;">setCurrentMillisOffset</span><span style="color: #66cc66;">&#40;</span>dur.<span style="color: #006600;">getMillis</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// we've gone back in time!</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// 2006-04-25T23:24:03.796+02:00</span>
&nbsp;</pre>
<p>Don't forget to reset to system time:</p>
<pre class="java">&nbsp;
DateTimeUtils.<span style="color: #006600;">setCurrentMillisSystem</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// we're back to normal</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// 2006-05-25T23:29:41.281+02:00</span>
&nbsp;</pre>
<h3>Where were we?</h3>
<p>Oh, yes. Printing dates. Let's print out the same date using Joda-Time. It was 12.30 PM on July 2, 1945:</p>
<pre class="java">&nbsp;
DateTime date = <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1945</span>, <span style="color: #cc66cc;">7</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">12</span>, <span style="color: #cc66cc;">30</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
DateTimeFormatter formatter = DateTimeFormat.<span style="color: #006600;">forPattern</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;yyyy-MM-dd HH:mm&quot;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>date.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span>formatter<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// 1945-07-02 12:30</span>
&nbsp;</pre>
<p>Couldn't be simpler.</p>
<h3>Conclusion</h3>
<p>The existing classes for date and time have drawbacks, some of them serious. The contender is Joda-Time, which is a complete rewrite and represents a mature API with a strong focus on usability, interoperability, stability and performance. What are you waiting for? Now is the time.</p>
<p>Update: <a href="http://tech.puredanger.com/java7/#jsr310">It seems</a> Java7 will be using JSR310, which basically is Joda-Time.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2006/09/16/tired-of-date-and-calendar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JXPath simplifies Java queries</title>
		<link>http://blog.jayway.com/2006/08/04/jxpath-simplifies-java-queries/</link>
		<comments>http://blog.jayway.com/2006/08/04/jxpath-simplifies-java-queries/#comments</comments>
		<pubDate>Fri, 04 Aug 2006 10:30:52 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=259</guid>
		<description><![CDATA[Consider a company that contains many departments. Those departments contain employees, those employees have names, telephone numbers, and so on. To query a collection of companies and find, for example, all departments of companies in California with more than 10 employees, you could write something like this: &#160; for &#40;Iterator companies = database.getCompanies&#40;&#41;.iterator&#40;&#41;; companies.hasNext&#40;&#41;;&#41; &#123; [...]]]></description>
			<content:encoded><![CDATA[<p>Consider a company that contains many departments. Those departments contain employees, those employees have names, telephone numbers, and so on. To query a collection of companies and find, for example, all departments of companies in California with more than 10 employees, you could write something like this:</p>
<pre class="java">&nbsp;
<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Iterator</span></a> companies =
      database.<span style="color: #006600;">getCompanies</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">iterator</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      companies.<span style="color: #006600;">hasNext</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
   Company company = <span style="color: #66cc66;">&#40;</span>Company<span style="color: #66cc66;">&#41;</span>companies.<span style="color: #006600;">next</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
   <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>company.<span style="color: #006600;">getLocation</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">equals</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;CA&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
      <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Iterator</span></a> departments =
            company.<span style="color: #006600;">getDepartments</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">iterator</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
            departments.<span style="color: #006600;">hasNext</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
         Department department = <span style="color: #66cc66;">&#40;</span>Department<span style="color: #66cc66;">&#41;</span>departments.<span style="color: #006600;">next</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; 
&nbsp;
         <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>department.<span style="color: #006600;">getEmployees</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &gt; <span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>department<span style="color: #66cc66;">&#41;</span>;
         <span style="color: #66cc66;">&#125;</span>
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Using <a href="http://commons.apache.org/jxpath/">JXPath</a> you can simplify this:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// only needed once</span>
JXPathContext context = JXPathContext.<span style="color: #006600;">newContext</span><span style="color: #66cc66;">&#40;</span>database<span style="color: #66cc66;">&#41;</span>; 
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Iterator</span></a> departments = context.<span style="color: #006600;">iterate</span><span style="color: #66cc66;">&#40;</span>
      <span style="color: #ff0000;">&quot;/companies[location='CA']&quot;</span> +
      <span style="color: #ff0000;">&quot;/departments[count(employees) &gt; 10]&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>departments.<span style="color: #006600;">hasNext</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
   <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>departments.<span style="color: #006600;">next</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Two points should be noted from this example:</p>
<ul>
<li>The code using JXPath is considerably shorter. The query is concisely expressed in one statement.</li>
<li>You can take that expression out of the code and parameterize it, or put it in a configuration file.</li>
</ul>
<h3>Perfect for Unit Testing</h3>
<p>Unit testing often requires checking object hierarchies for particular values. You can use JXPath to express the components to be tested. For example, you can write a helper method in a JUnit test:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * tests using a JXPath to express the required
 * component to test against. Note that nulls
 * aren't catered for!
 * @param path the path to find the object to
 *        test against
 * @param testable the base object to test
 * @param required the required result
 */</span>
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">void</span> assertFromPath<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> path,
                            <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> testable,
                            <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> required<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
   JXPathContext context = JXPathContext.<span style="color: #006600;">newContext</span><span style="color: #66cc66;">&#40;</span>testable<span style="color: #66cc66;">&#41;</span>;
   assertTrue<span style="color: #66cc66;">&#40;</span>required.<span style="color: #006600;">equals</span><span style="color: #66cc66;">&#40;</span>context.<span style="color: #006600;">getValue</span><span style="color: #66cc66;">&#40;</span>path<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>and then you can use this in tests:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testBankAccount<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 
&nbsp;
   <span style="color: #808080; font-style: italic;">// you get a bank account object from some operation...</span>
   Account account = .... 
&nbsp;
   <span style="color: #808080; font-style: italic;">// then test against it</span>
   assertFromPath<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/accountHolder/name&quot;</span>, account, <span style="color: #ff0000;">&quot;John Smith&quot;</span><span style="color: #66cc66;">&#41;</span>;
   assertFromPath<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/accountHolder/opened&quot;</span>, account, DATE_OPENED<span style="color: #66cc66;">&#41;</span>;
   assertFromPath<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/accountHolder&quot;</span> + <span style="color: #ff0000;">&quot;/transactions[1]/amount&quot;</span>,
         account, INITIAL_PAYMENT<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Read more in <a href="http://today.java.net/pub/a/today/2006/08/03/java-object-querying-using-jxpath.html">this java.net article</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2006/08/04/jxpath-simplifies-java-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
