<?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>Xebia Blog &#187; Jeroen van Erp</title>
	<atom:link href="http://blog.xebia.com/author/jvanerp/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com</link>
	<description>Software development done right!</description>
	<lastBuildDate>Wed, 01 Feb 2012 00:30:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Which Generic Swallow</title>
		<link>http://blog.xebia.com/2010/08/12/which-generic-swallow/</link>
		<comments>http://blog.xebia.com/2010/08/12/which-generic-swallow/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 10:02:49 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/blog.xebia.com/www/wp-content/plugins/autometa/autometa.php</b> on line <b>303</b><br />
		<category><![CDATA[General]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[generics]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=5144</guid>
		<description><![CDATA[Scene opens&#8230; An idyllic landscape unfolds before our eyes, in yonder distance we see a figure approaching us. He goes by the name of Arthur, King of the Britons&#8230; public class Arthur { // Some internals or Arthur, will be revisited later. } When we turn around, we see a gorge. Over the gorge lies [...]]]></description>
			<content:encoded><![CDATA[<p>Scene opens&#8230;<br />
An idyllic landscape unfolds before our eyes, in yonder distance we see a figure approaching us. He goes by the name of Arthur, King of the Britons&#8230;<br />
<span id="more-5144"></span></p>
<pre lang="java">public class Arthur {
	// Some internals or Arthur, will be revisited later.
}
</pre>
<p><img src="http://blog.xebia.com/wp-content/uploads/2010/08/bridge_of_death-150x150.jpg" alt="bridge_of_death" title="bridge_of_death" width="150" height="150" class="size-thumbnail wp-image-5172" style="float:right; padding-left: 5px;"/>When we turn around, we see a gorge. Over the gorge lies an old rope-bridge with wooden steps and on this side of the bridge, we see the BridgeKeeper.</p>
<pre lang="java">public class BridgeKeeper {
	// Some internals of the BridgeKeeper, will be revisited later.
}
</pre>
<p>When Arthur approaches the BridgeKeeper, the BridgeKeeper speaks: &#8220;Stop! Who would cross the Bridge of Death must answer me these questions three, ere the other side he see.&#8221;.</p>
<pre lang="java">public class Question {

	public <S> S answer(Answer<S> a) {
		return a.doAnswer();
	}

	public interface Answer<S> {
		S doAnswer();
	}
}
</pre>
<p><img src="http://blog.xebia.com/wp-content/uploads/2010/08/southafricanswallow.gif" alt="southafricanswallow" title="southafricanswallow" class="size-full wp-image-5167" style="float: right;" /><img src="http://blog.xebia.com/wp-content/uploads/2010/08/europeanswallow.gif" alt="europeanswallow" title="europeanswallow" class="size-full wp-image-5168" style="float:right;" />After Arthur answers the first two questions correctly, the BridgeKeeper asks him the third and final question: &#8220;What is the air-speed velocity of an unladen swallow&#8221;. Now our Arthur hasn&#8217;t been made king without a good reason, and knows about the <a href="http://www.style.org/unladenswallow/">differences</a> between swallows:</p>
<pre lang="java">public class Swallow {}

public class EuropeanSwallow extends Swallow {}

public class AfricanSwallow extends Swallow {}
</pre>
<p>So Arthur asks the BridgeKeeper: &#8220;What do you mean, an African or a European one?&#8221;</p>
<pre lang="java">public class Arthur {
	public void query(BridgeKeeper keeper) {
		Question whichSwallow = new Question();
		Swallow s = keeper.answer(whichSwallow);
	}
}
</pre>
<p>To which the BridgeKeeper responds with: &#8220;Uhmm&#8230;. I don&#8217;t know&#8221;, after which he is cast into the gorge&#8230;</p>
<pre lang="java">public class BridgeKeeper {
	public <S extends Swallow> S answer(Question question) {
		return question.answer(new Question.Answer<S>() {
			public S doAnswer() {
				return determineSwallow();
			}
		});
	}

	private <S extends Swallow> S determineSwallow() {
		return null;
	}
}
</pre>
<p>Though this code actually looks clean, it won&#8217;t compile with your Java compiler. Though both IntelliJ and Eclipse show no errors, compiling it using the real JDK yields the following error</p>
<p><code>type parameters of &lt;S&gt;S cannot be determined; no unique maximal instance exists for type variable S with upper bounds S,Swallow<br />
</code></p>
<p>There is actually something fundamental here. The compiler cannot infer the correct generic type for the return value of determineSwallow(). The reasoning behind this is that the return types of determineSwallow and answer are independent. There is a long outstanding <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954">bug</a> for this in the JDK which will now finally be fixed in Java7. </p>
<p>The fix is simple enough, either do an explicit cast, or call the method with the generic return type present as shown below and just ignore the warning your IDE gives you that the generic type can be inferred&#8230;</p>
<pre lang="java">public class BridgeKeeper {
	public <S extends Swallow> S answer(Question question) {
		return question.answer(new Question.Answer<S>() {
			public S doAnswer() {
				return BridgeKeeper.this.<S>determineSwallow();
			}
		});
	}

	private <S extends Swallow> S determineSwallow() {
		return null;
	}
}
</pre>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2010/08/12/which-generic-swallow/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2010%2F08%2F12%2Fwhich-generic-swallow%2F&amp;title=Which%20Generic%20Swallow" id="wpa2a_2"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2010/08/12/which-generic-swallow/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Google Code Jam 2009 &#8211; Qualification</title>
		<link>http://blog.xebia.com/2009/09/04/google-code-jam-2009-qualification/</link>
		<comments>http://blog.xebia.com/2009/09/04/google-code-jam-2009-qualification/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 05:18:26 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[google code jam]]></category>
		<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=3113</guid>
		<description><![CDATA[Aliens sending messages, Water flowing over a map and finding the hidden Welcome message in a String&#8230; Yes, Google Code Jam has returned for the 2009 edition! I participated in the Qualification Round and managed to solve all but 1 input set&#8230;. Sounds like fun? It sure was! As I have been busy learning some [...]]]></description>
			<content:encoded><![CDATA[<p>Aliens sending messages, Water flowing over a map and finding the hidden Welcome message in a String&#8230; Yes, Google Code Jam has returned for the 2009 edition! I participated in the Qualification Round and managed to solve all but 1 input set&#8230;.<br />
<span id="more-3113"></span><br />
Sounds like fun? It sure was! As I have been busy learning some Scala, I thought I&#8217;d try that and see how it worked out during the contest. I think it saved me at least some lines of code.</p>
<p>For the first problem, Google has intercepted some alien communications but the signal has weakened so much that some of the words are unclear. They now need our help to devise a clever algorithm that can tell them how many different words the signal can represent. For this they constructed the full dictionary of the alien language. As a sample they provided us with the following alien language which consists of 5 3-letter words, and 4 received signals.</p>
<p><code>3 5 4<br />
abc<br />
bca<br />
dac<br />
dbc<br />
cba<br />
(ab)(bc)(ca)<br />
abc<br />
(abc)(abc)(abc)<br />
(zyx)bc<br />
</code></p>
<p>For my solution I decided to read the dictionary of all the words, and subsequently convert each of the signals to a regular expression by doing</p>
<pre class="brush: scala; title: ; notranslate">
val pattern = &quot;(ab)(bc)(ca)&quot;.replaceAll(&quot;\\(&quot;, &quot;[&quot;).replaceAll(&quot;\\)&quot;, &quot;]&quot;).r
</pre>
<p>This lead to the following code:</p>
<pre class="brush: scala; title: ; notranslate">
object AlienLanguage {

	def main(args: Array[String]) = {
		if (args.length == 0) {
			throw new IllegalArgumentException(&quot;Could not find input file in arguments&quot;)
		}

		val input = args(0)
		val outputFile = new File((input substring(0, input lastIndexOf(&quot;.&quot;))) + &quot;.out&quot;)
		val reader = Source fromFile(input) getLines
		val ar = reader nextIntArray
		val (tokens, nrWords, nrProblems) = (ar(0), ar(1), ar(2))
		val results = new Array[String](nrProblems)

		val words = (1 to nrWords).map(x =&gt; reader.trimmedLine).toList
		for (val i &lt;- 1 to nrProblems) {
			results(i - 1) = &quot;Case #&quot; + i + &quot;: &quot; + solveProblem(reader, words)
		}
		outputFile write results
	}

	def solveProblem(reader : Iterator[String], words : List[String]) : String = {
		val pattern = reader.trimmedLine
		val regex = pattern.replaceAll(&quot;\\(&quot;, &quot;[&quot;).replaceAll(&quot;\\)&quot;, &quot;]&quot;).r

		matchWords(regex, words.head, words.tail).toString
	}

	def matchWords(regex : scala.util.matching.Regex, word: String, words : List[String]) : Int = {
		words.isEmpty match {
		  	case true =&gt; matchWord(regex, word)
		  	case false =&gt; matchWord(regex, word) + matchWords(regex, words.head, words.tail)
		}
	}

	def matchWord(regex : scala.util.matching.Regex, word: String) : Int = {
		regex.findFirstIn(word) match {
		  case Some(x) =&gt; 1
		  case None =&gt; 0
		}
	}
}
</pre>
<p>The code uses two helper classes which use implicits to add methods to a File and to an Iterator[String]. These can be found in my GitHub repository (see bottom). This code was able to solve the large input set (max. 5000 15-letter words and 500 signals) within 2,5 seconds.</p>
<p>For the second problem we were given an elevation map for which we had to calculate drainage basins, based on a a set of rules:<br />
* From each cell water flows to at most one neighbour cell<br />
* Water always flows to the lowest neighbour, in case of a tie, water prefers North, West, East, South in this order<br />
* If no neighbour has a lower altitude, water stays in this cell, we call this a sink<br />
* drainage systems are identified by a single unique lowercase letter, such that when all rows are concatenated, the string is lexographically smallest.</p>
<p>A sample input with 1 5&#215;5 map<br />
<code>1<br />
5 5<br />
1 2 3 4 5<br />
2 9 3 9 6<br />
3 3 0 8 7<br />
4 9 8 9 8<br />
5 6 7 8 9<br />
</code></p>
<p>My solution consists of first building the map and then converting that to a &#8220;flow map&#8221;, in which every cell points to the index of the cell to which the cell drains. This flow map can then easily be transformed to a &#8220;basin map&#8221; by starting in the top-left corner and going from left-to-right and top-to-bottom through the map, assigning a unique letter to the drainage system. The code is:</p>
<pre class="brush: scala; title: ; notranslate">
object Watersheds extends CodeJam {

	def solveProblem(reader : Iterator[String]) : String = {
		val ar = reader.nextIntArray
		val (h, w) = (ar(0), ar(1))

		val theMap = (1 to h).map(x =&gt; reader.nextIntArray).toArray

		val shed = new Shed(h, w, theMap)
		val basins : Array[String] = shed.solve
		printRecursive(basins, w)
	}

	def printRecursive(basins : Array[String], length : Int) : String = {
		basins.size match {
		  	case 0 =&gt; &quot;&quot;
		  	case _ =&gt; &quot;\n&quot; + basins.take(length).reduceLeft(_+&quot; &quot;+_) + printRecursive(basins.drop(length), length)
		}
	}
}

class Shed(val h : Int, val w : Int, val theMap : Array[Array[Int]]) {
	val flowMap = (for (hPos &lt;- 0 until h; wPos &lt;- 0 until w) yield determineFlowTo(hPos, wPos)).toArray
	val basins : Array[Int] = Array.make(h * w, -1)

	def determineFlowTo(hPos : Int, wPos : Int) : Int = {
		val north = determineAltitude(hPos - 1, wPos)
		val west = determineAltitude(hPos, wPos - 1)
		val east = determineAltitude(hPos, wPos + 1)
		val south = determineAltitude(hPos + 1, wPos)
		val me = determineAltitude(hPos, wPos)
		val minAltitude = List(me, north, west, east, south).sort(_&lt;_).head

		if (me &gt; north &amp;&amp; north == minAltitude) {
			convertToIndex(hPos - 1, wPos)
		} else if (me &gt; west &amp;&amp; west == minAltitude) {
			convertToIndex(hPos, wPos - 1)
		} else if (me &gt; east &amp;&amp; east == minAltitude) {
			convertToIndex(hPos, wPos + 1)
		} else if (me &gt; south &amp;&amp; south == minAltitude) {
			convertToIndex(hPos + 1, wPos)
		} else {
			convertToIndex(hPos, wPos)
		}
	}

 	def determineAltitude(hPos : Int, wPos : Int) : Int = {
		if (hPos == h || hPos &lt; 0) {
			10001 // more than max altitude in large map because out of range
		} else if (wPos == w || wPos &lt; 0) {
			10001 // more than max altitude in large map because out of range
		} else {
			theMap(hPos)(wPos)
		}
	}

	def convertToIndex(hPos : Int, wPos : Int) = {
		hPos * w + wPos
	}

	/*
     * Solve methods
	 */
	def solve() : Array[String] = {
		val basinString = &quot;abcdefghijklmnopqrstuvwxyz&quot;.split(&quot;&quot;)
		var currentHighestBasin = -1
		(0 until h * w).foreach(i =&gt; if (basins(i) == -1) currentHighestBasin = fillFlow(i, currentHighestBasin))
		basins.map(i =&gt; basinString(i + 1)).toArray
	}

  	def fillFlow(index : Int, currentHighestBasin : Int) : Int = {
		val flowTo = flowMap(index)
		if (basins(flowTo) != -1) {
			basins(index) = basins(flowTo)
			currentHighestBasin
		} else {
			val basinValue = findBasinValue(index)
			if (basinValue != -1) {
				fillTheFlow(index, basinValue)
				currentHighestBasin
			} else {
				fillTheFlow(index, currentHighestBasin + 1)
				currentHighestBasin + 1
			}
		}
	}

	def findBasinValue(index : Int) : Int = {
		flowMap(index) match {
		  	case `index` =&gt; basins(index)
		  	case _ =&gt; findBasinValue(flowMap(index))
		}
	}

	def fillTheFlow(index : Int, basin : Int) {
		basins(index) = basin
		val flowTo = flowMap(index)
		if (flowTo != index &amp;&amp; basins(flowTo) == -1) fillTheFlow(flowTo, basin)
	}
}
</pre>
<p>Note that the CodeJam trait which is extended provides a main method, much alike the one from the first problem. The output that is generated by the code looks for the sample input given above as<br />
<code>Case #1:<br />
a a a a a<br />
a a b b a<br />
a b b b a<br />
a b b b a<br />
a a a a a<br />
</code><br />
The program was able to solve both the large and small datasets in under 1 second. </p>
<p>The last problem was (at least for me) a hard nut to crack, though the small input was easy to solve, my program didn&#8217;t finish the large input within the scheduled 8 minutes. The problem statement was as follows:<br />
<em>Given a text string, you are to determine how many times the string &#8220;welcome to code jam&#8221; appears as a sub-sequence of that string. In other words, find a sequence s of increasing indices into the input string such that the concatenation of input[s[0]], input[s[1]], &#8230;, input[s[18]] is the string &#8220;welcome to code jam&#8221;.</em></p>
<p>My approach consisted of the following steps:</p>
<ul>
<li>first filter out all characters from the string that do not belong to the &#8220;welcome to code jam&#8221; message</li>
<li>do a simple kind of run-length-encoding trick to decrease the length of the string even further (while maintaining the information)</li>
<li>loop over the string and calculate the number of occurrences</li>
<ul>
<pre class="brush: scala; title: ; notranslate">
object WelcomeToCodeJam extends CodeJam {
	def solveProblem(reader : Iterator[String]) : String = {
		val expr = &quot;welcome to code jam&quot;
		val line = reader.trimmedLine

		// first filter all characters not occurring in pattern
		val filteredLine = makeHisto(line.toList.filter(x =&gt; expr.contains(x)))
		val exprList = expr.toList
		(solve(filteredLine, exprList) % 10000) formatted (&quot;%04d&quot;)
	}

	def makeHisto(line : List[Char]) : List[(Char, Long)] = {
		if (line.isEmpty) {
			List[(Char, Long)]()
		} else {
			val h = histoLetter(line.tail, line.head)
			val newLine = line.drop(h._2.toInt)
			newLine.isEmpty match {
			  case true =&gt; List(h)
			  case false =&gt; List(h) ++ makeHisto(newLine)
			}
		}
	}

	def histoLetter(line : List[Char], c : Char) : (Char, Long) = {
		(c, (line takeWhile (_ == c)).size + 1)
	}

	def solve(line : List[(Char, Long)], expr : List[Char]) : Long = {
		var count : Long = 0L
		if (!expr.isEmpty) {
			var restLine = findNext(line, expr)
			while (!restLine.isEmpty) {
				count += (restLine.head._2 * solve(restLine.tail, expr.tail))
				restLine = findNext(restLine.tail, expr)
			}
		} else {
		  count = 1
		}
		count
	}

	def findNext(line : List[(Char, Long)], expr : List[Char]) = {
		line.dropWhile(_._1 != expr.head)
	}
}
</pre>
<p>Now, given the fact that some people actually managed to do this in a very small amount of time, my guess is that I completely missed something which is why it couldn&#8217;t finish the large input set (lines of 500 characters). The small input set was correctly generated however. I&#8217;ve been busy this last day refactoring the third program to improve its speed, the latest version is the one shown above, who can tell me what I missed, or how it can be done faster?</p>
<p>For the code of the 2009 edition, and some of the problems of the 2008 edition, you can also visit my GitHub repository at: <a href="http://github.com/hierynomus">http://github.com/hierynomus</a>. Who else competed, or who has a better solution in Scala?</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/09/04/google-code-jam-2009-qualification/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F09%2F04%2Fgoogle-code-jam-2009-qualification%2F&amp;title=Google%20Code%20Jam%202009%20%26%238211%3B%20Qualification" id="wpa2a_4"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/09/04/google-code-jam-2009-qualification/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>ShuntingYard algorithm in Scala</title>
		<link>http://blog.xebia.com/2009/07/02/shuntingyard-algorithm-in-scala/</link>
		<comments>http://blog.xebia.com/2009/07/02/shuntingyard-algorithm-in-scala/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 10:21:16 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/blog.xebia.com/www/wp-content/plugins/autometa/autometa.php</b> on line <b>303</b><br />
		<category><![CDATA[General]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[kata]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[shunting]]></category>
		<category><![CDATA[yard]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=2331</guid>
		<description><![CDATA[Last week I came across an interesting &#8220;coding kata&#8221; by Brett Schuchert on the Object Mentor blog. The trick of a kata is that you grow the program step-by-step using tests, just like a kata in karate is tought to a student. The problem of this kata was the Shunting Yard algorithm of Dijkstra. I [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I came across an interesting &#8220;coding kata&#8221; by Brett Schuchert on the <a href="http://blog.objectmentor.com/articles/2009/06/24/shunting-yard-algorithm-kata">Object Mentor blog</a>. The trick of a kata is that you grow the program step-by-step using tests, just like a <a href="http://en.wikipedia.org/wiki/Kata">kata</a> in karate is tought to a student. The problem of this kata was the <a href="http://en.wikipedia.org/wiki/Shunting_yard_algorithm">Shunting Yard algorithm</a> of <a href="http://en.wikipedia.org/wiki/Edsger_Dijkstra">Dijkstra</a>. I wanted to see if I could implement this kata in Scala.<br />
<span id="more-2331"></span><br />
Instead of writing the algorithm as described, the trick in a coding kata is that you first write a test, and then make the test pass. And subsequently each time adding a test and keeping it all in the green. Brett described the test-cases in his blog entry.</p>
<p>The Shunting Yard algorithm is used to convert a mathematical function in infix notation to a reverse polish or postfix notation. For instance, it can convert an expression like <em>3+4</em> to <em>3 4 +</em>.</p>
<p>In order to implement this algorithm, one needs to do string parsing to break up the infix string. Scala has the <a href="http://www.codecommit.com/blog/scala/the-magic-behind-parser-combinators">parser combinators</a> that can do just this. Using a parser I build an Abstract Syntax Tree (AST) which is a representation of the formula in a tree form. An AST for 3 + 4 and (3 + 4) * 4 looks like:<br />
<img src="http://blog.xebia.com/wp-content/uploads/2009/07/ast.png" alt="ast" title="ast" width="374" height="207" class="aligncenter size-full wp-image-2336" /></p>
<p>The AST representation of the formula can then easily be printed in a reverse polish notation, as the code shows. The final Parser looks like this:</p>
<pre class="brush: scala; title: ; notranslate">
import scala.util.parsing.combinator.syntactical._

abstract class Expr {
  def rpn:String
}
case class BinaryOperator(lhs:Expr, op:String, rhs:Expr) extends Expr {
	def rpn:String = lhs.rpn + &quot; &quot; + rhs.rpn + &quot; &quot; + op
}
case class Number(v:String) extends Expr { def rpn:String = v }
case class Variable(v:String) extends Expr { def rpn:String = v }
case class Function(f:String, e:List[Expr]) extends Expr { def rpn:String = {
	var s = &quot;&quot;
	e.foreach { x =&gt; s += x.rpn + &quot; &quot; }
	s += f
	return s
  }
}
object ShuntingYard extends StandardTokenParsers {
    lexical.delimiters ++= List(&quot;+&quot;,&quot;-&quot;,&quot;*&quot;,&quot;/&quot;, &quot;^&quot;,&quot;(&quot;,&quot;)&quot;,&quot;,&quot;)

    def value <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> arser[Expr] = numericLit ^^ { s =&gt; Number(s) }
    def variable:Parser[Expr] =  ident ^^ { s =&gt; Variable(s) }
    def parens:Parser[Expr] = &quot;(&quot; ~&gt; expr &lt;~ &quot;)&quot;

    def argument:Parser[Expr] = expr &lt;~ (&quot;,&quot;?)
    def func:Parser[Expr] = ( ident ~ &quot;(&quot; ~ (argument+) ~ &quot;)&quot; ^^ { case f ~ _ ~ e ~ _ =&gt; Function(f, e) })

    def term = (value | parens | func | variable)

    // Needed to define recursive because ^ is right-associative
    def pow <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> arser[Expr] = ( term ~ &quot;^&quot; ~ pow ^^ {case left ~ _ ~ right =&gt; BinaryOperator(left, &quot;^&quot;, right) }|
    			term)
    def factor = pow * (&quot;*&quot; ^^^ { (left:Expr, right:Expr) =&gt; BinaryOperator(left, &quot;*&quot;, right) } |
                        &quot;/&quot; ^^^ { (left:Expr, right:Expr) =&gt; BinaryOperator(left, &quot;/&quot;, right) } )
    def sum =  factor * (&quot;+&quot; ^^^ { (left:Expr, right:Expr) =&gt; BinaryOperator(left, &quot;+&quot;, right) } |
    					&quot;-&quot; ^^^ { (left:Expr, right:Expr) =&gt; BinaryOperator(left, &quot;-&quot;, right) } )
    def expr = ( sum | term )

    def parse(s:String) = {
        val tokens = new lexical.Scanner(s)
        phrase(expr)(tokens)
    }

    def shunt(exprstr: String) : String = exprstr match {
      case null =&gt; return &quot;&quot;
      case &quot;&quot; =&gt; return &quot;&quot;
      case _ =&gt;
    	parse(exprstr) match {
            case Success(tree, _) =&gt;
                println(&quot;Tree: &quot;+tree)
                val v = tree.rpn
                println(&quot;RPN: &quot;+v)
                return v
            case e: NoSuccess =&gt; Console.err.println(e)
            	return e.toString
        }
    }
}
</pre>
<p>Of course I tested this using the following unit test, of which I will show only a small part, one can easily complete this by looking at Brett&#8217;s examples:</p>
<pre class="brush: scala; title: ; notranslate">
import org.junit.Test
import org.junit.Assert._

class ShuntingYardTest {
  @Test
  def test_11() {
    assertEquals(&quot;4 g f&quot;, ShuntingYard.shunt(&quot;f(g(4))&quot;))
  }

  @Test
  def test_12() {
    assertEquals(&quot;3 4 19 f&quot;, ShuntingYard.shunt(&quot;f(3, 4, 19)&quot;))
  }

  @Test
  def test_13() {
    assertEquals(&quot;3 4 2 * 1 5 - 2 3 ^ ^ / +&quot;, ShuntingYard.shunt(&quot;3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3&quot;))
  }

  @Test
  def test_14 () {
    assertEquals(&quot;4 5 + 1 a 2 ^ + 8 b + 10 * f&quot;, ShuntingYard.shunt(&quot;f(4+5,1+a^2,(8+b)*10)&quot;))
  }
}
</pre>
<p>Of all the tests that Brett defined, only one doesn&#8217;t pass, can you spot which one? Of course as this is one of my first exercises in Scala, it probably isn&#8217;t optimal yet, any improvements are welcome in the comments!</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/07/02/shuntingyard-algorithm-in-scala/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F07%2F02%2Fshuntingyard-algorithm-in-scala%2F&amp;title=ShuntingYard%20algorithm%20in%20Scala" id="wpa2a_6"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/07/02/shuntingyard-algorithm-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Beware of transitive dependencies&#8230; For they can be old and leaky</title>
		<link>http://blog.xebia.com/2008/09/15/beware-of-transitive-dependencies-for-they-can-be-old-and-leaky/</link>
		<comments>http://blog.xebia.com/2008/09/15/beware-of-transitive-dependencies-for-they-can-be-old-and-leaky/#comments</comments>
		<pubDate>Mon, 15 Sep 2008 11:54:15 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[eclipse memory analyzer]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[maven2]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[OutOfMemoryError]]></category>
		<category><![CDATA[XML]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=746</guid>
		<description><![CDATA[In many JEE apps today, you almost cannot forgo XML. Whether it is in configuration, data structures or service interfaces, you will certainly use a number of XML files. In a recent project we had to deal with a number of external services which used an XML interface. Little did we know that we introduced [...]]]></description>
			<content:encoded><![CDATA[<p>In many JEE apps today, you almost cannot forgo XML. Whether it is in configuration, data structures or service interfaces, you will certainly use a number of XML files. In a recent project we had to deal with a number of external services which used an XML interface. Little did we know that we introduced a potential time-bomb in our application&#8230;<span id="more-746"></span></p>
<p>Each of the accessed XML services in our application provided data for the same domain. So instead of writing or generating a great number of Java classes, we decided to use XSLT to transform the XML into a common format we could easily unmarshall. During performance and stress tests, this solution performed very well and showed no signs of degradation.</p>
<p>However&#8230;. Once we hit production, the application went OutOfMemory after a few days on a heap of 1GB. This was bad, how come our performance and stress tests didn&#8217;t show this? We decided to do the only sensible thing, and create a heapdump as soon as the application showed signs of stress. We started monitoring the java process using the jstat utility found in the JDK.</p>
<pre>$ jstat -gcutil &lt;processid&gt; 1s 10000
  S0     S1     E      O      P     YGC     YGCT    FGC    FGCT     GCT
  0.00   0.00  99.98 100.00  26.66   2896  119.886  6000 32234.945 32354.831
  0.00   0.00 100.00 100.00  26.66   2896  119.886  6001 32234.945 32354.831
  0.00   0.00 100.00 100.00  26.66   2896  119.886  6001 32234.945 32354.831
  0.00   0.00 100.00 100.00  26.66   2896  119.886  6001 32234.945 32354.831
  0.00   0.00 100.00 100.00  26.66   2896  119.886  6001 32234.945 32354.831
  0.00   0.00 100.00 100.00  26.66   2896  119.886  6001 32234.945 32354.831
  0.00   0.00 100.00 100.00  26.66   2896  119.886  6001 32234.945 32354.831
  0.00   0.00 100.00 100.00  26.66   2896  119.886  6002 32240.277 32360.163
 </pre>
<p>As soon as we saw the old space utilization hitting 100% and the Full Garbage Collector being unable to clean things up, we created a heapdump</p>
<pre>$ jmap -dump:format=b,file=/tmp/heap.hprof &lt;processid&gt;</pre>
<p>Using the <a href="http://www.eclipse.org/mat/" title="Eclipse Memory Analyzer">Eclipse Memory Analyzer</a> we looked into the heap dump, to see what was causing our memory to grow. This generated the following picture.</p>
<p><a href='http://blog.xebia.com/wp-content/uploads/2008/09/picture-2.png'><img src="http://blog.xebia.com/wp-content/uploads/2008/09/picture-2-300x269.png" alt="" title="Eclipse-MemoryAnalyzer" width="300" height="269" class="alignnone size-medium wp-image-747" /></a></p>
<p>Clicking on the &#8220;Leak Hunter&#8221; link in the analyzer, quickly showed the possible culprit. The XMLReaderManager class from Xalan somehow had taken up a big chunk of available memory.</p>
<p><a href='http://blog.xebia.com/wp-content/uploads/2008/09/picture-3.png'><img src="http://blog.xebia.com/wp-content/uploads/2008/09/picture-3-300x269.png" alt="" title="Eclipse-LeakHunter" width="300" height="269" class="alignnone size-medium wp-image-748" /></a></p>
<p>Searching through our Maven2 pom files showed no explicit dependency upon Xalan, but the dependency graph in the generated maven site showed it as a transitive dependency. One of our dependencies had xalan-2.6.0 noted down as a dependency. Googling around for this quickly showed us that there were two bugs against xalan, which described this exact problem: <a href="https://issues.apache.org/jira/browse/XALANJ-2178" title="XALANJ-2178">XALANJ-2178</a> and <a href="https://issues.apache.org/jira/browse/XALANJ-2195" title="XALANJ-2195">XALANJ-2195</a>.</p>
<p>Looking at the source code for Xalan 2.6.0 we could indeed clearly notice the memory leak, whereas in 2.7.0 they updated it to prevent the class from keeping references around for too long. But why didn&#8217;t our stress tests on a similar machine and configuration show this?</p>
<p>The answer for this can also be found in the XMLReaderManager. It tries to cache the XMLReader in a ThreadLocal, so that it can give the same XMLReader to the Thread if it requests a new one. However in a JEE system, you normally have threadpools which scale up and down depending on system load at a given time. In our stress tests, we only simulated full loads for a prolonged time, and with this load, the XMLReaders weren&#8217;t leaked, as threads were being reused from the ThreadPool. If we had simulated a more varying load over a larger amount of time, we would have seen this occurring before we hit production.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/09/15/beware-of-transitive-dependencies-for-they-can-be-old-and-leaky/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F09%2F15%2Fbeware-of-transitive-dependencies-for-they-can-be-old-and-leaky%2F&amp;title=Beware%20of%20transitive%20dependencies%26%238230%3B%20For%20they%20can%20be%20old%20and%20leaky" id="wpa2a_8"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/09/15/beware-of-transitive-dependencies-for-they-can-be-old-and-leaky/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JavaOne 2008 Day Two</title>
		<link>http://blog.xebia.com/2008/05/08/javaone-2008-day-two/</link>
		<comments>http://blog.xebia.com/2008/05/08/javaone-2008-day-two/#comments</comments>
		<pubDate>Thu, 08 May 2008 08:31:16 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Closures]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[JavaOne]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Web Beans]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=550</guid>
		<description><![CDATA[Today was the second day of the JavaOne 2008. Besides doing a lot of chatting in the JavaOne pavillion, and visiting all the cool parties this night, we also went to a number of sessions. Also today the NLJug had the James Gosling meeting we won for being the biggest JUG out here. After a [...]]]></description>
			<content:encoded><![CDATA[<p>Today was the second day of the JavaOne 2008. Besides doing a lot of chatting in the JavaOne pavillion, and visiting all the cool parties this night, we also went to a number of sessions. Also today the NLJug had the James Gosling meeting we won for being the biggest JUG out here. After a long day of work, we finally had time to relax at the Adobe party and at the SDN party. </p>
<p>Todays topics included:</p>
<ul>
<li>Closures</li>
<li>JavaFx, Groovy and Google Android</li>
<li>Swing GUI testing</li>
<li>Scripting</li>
</ul>
<p><span id="more-550"></span></p>
<p><strong>Mischa on part of his day @JavaOne</strong><br />
<em>Closures Cookbook</em><br />
Neal Gafter showed in his presentation a bunch of examples that should simplify coding and minimize use of boilerplate code using the &#8220;<em>BGGA</em> closure&#8221; proposal.</p>
<p>There are a few examples in which I would love to use closures for example like:</p>
<p>Adding a listener to a swing component.</p>
<pre lang="java">ItemSelectable = ...;
is.addItemListener( { ItemEvent e => doSomething(e,is); });
</pre>
<p>or Aggregate Operations like ie. getting the highest Gpa from a list of Students.</p>
<pre lang="java">final double highestGpa =
  students
  .filter({ Student s => s.graduationYear==THIS_YEAR })
  .map({ Student s => s.getGpa() })
  .max();
</pre>
<p>Though the impact of the BGGA closure proposal seems to be massive and the usage could result in very complex code, especially when combining closures with generics.</p>
<p>ie.
<pre lang="java">void for eachEntry(Map<K,V> m, { K, V ==> void throws X } block) {
    for (Map.Entry<K,V> e : m.entrySet()) {
        block.invoke(e.getKey(), e.getValue());
    }
}
</pre>
<p>All considered, it will result in cleaner code. But I am not convinced yet. </p>
<p><em>Going Mobile with JavaFx Script Technology, Groovy, and Google Android</em><br />
Mike Mannion and Dierk König of Canoo shared there experiences on the JavaFx, Groovy and Google android.<br />
Their experiences with the development of JavaFx were both negative and positive. Negative points were mainly about the development tools and the different syntax compared to Java.<br />
On the other hand due to the declarative approach, the learning curve is quite low and productivity high.</p>
<p>Their experiences with Google android are quite positive. It has no real GUI restrictions, includes a lot of standard functionality and can be easily extended with Java libraries. The only<br />
downside they found was the xml based GUI layout. Though the learning curve is quite steap.</p>
<p><em>Swing GUI testing made Easy</em><br />
Testing GUIs can be difficult. This is due to a couple of things:</p>
<ul>
<li> Test should be automated, but GUIs are designed for humans</li>
<li> Guis are usually composed of more then one class</li>
<li> The number GUI interactions can be huge</li>
<li> Conventional test coverage is not enough to cover all user interaction scenarios.</li>
</ul>
<p>For testing Swing GUIs you have to meet a couple of requirements:</p>
<ul>
<li>The ability to simulate user input</li>
<li>The need to have a reliable mechanism for finding GUI components..</li>
<li>The ability to tolerate changes in position, size, layout etc..</li>
</ul>
<p><a href="http://fest.easytesting.org">Fest</a> is an open source library that gives you these abilities. It has a good API, supports component lookup by name and type, integrates with JUnit and TestNG. </p>
<p>What is really nice is that Fest can automatically embed a screenshot of the desktop so you can see what the GUI looked like when the test failed. </p>
<p><strong>Erik Jan on Web Beans</strong><br />
Web Beans is a framework that Gavin King wrote to be able to bind all kinds of java objects together. It came out of Seam but developed further there is a JSR for it. Oracle also has a similar solution for it.</p>
<p>Web Beans aims to be able to use &#8216;loose coupling with strong typing&#8217;. To be able to do this it has to use anotations in a special way. A simple example of a Webbean:</p>
<pre lang="java">
public
@Component
class Hello {
   public String hello(String name) {
      return “hello “ + name;
   }
}
</pre>
<p>A simple client
<pre lang="java">
public
@Component
class Printer {
   @Current Hello hello;
   public void hello() {
      System.out.println( hello.hello(“world”) );
   }
}
</pre>
<p>The Web Beans container will now look for a component that is a Hello object and inject it it can also use constructor injection or an initializer injection with a parameter. But what if we have two implementations of the same interface, for instance one for testing and one for production. For this particular case Web Beans will have the ability to specify deployment types, this is done in a xml document.</p>
<p>It will also contain a way to add scope to beans and he created an extension on the EJB 3 listeners and a lot more. There will even be Spring support when it&#8217;s done&#8230; so take a look at his blog to find out what the status is&#8230;</p>
<p><strong>Jeroen on Scripting</strong><br />
I had the privilege today of being in the close presence of some of the scripting gurus of the JVM. Today the scripting language shootout, the &#8220;Script Bowl&#8221; was being held. The format was an American Idol style format consisting of 3 rounds, the competitors were:</p>
<ul>
<li>Guillaume LaForge (Grails)</li>
<li>Charles Nutter (JRuby)</li>
<li>Frank Wierzbecki (Jython)</li>
<li>Jorge Ortiz (Scala)</li>
</ul>
<p>In the first round all the script gurus had to show a Twitter client in the scripting language of their choice and browse through the code. The richest clients were written in Groovy and JRuby, however Charles admittedly did not write his client himself. Jython and JRuby fell behind but they had working solutions. The jury, consisting of amongst others Ola Bini, considered Groovy the best, with a JRuby a runner up. The crowd sent the highest marks to JRuby followed by Groovy.</p>
<p>The second assignment was to build a web app based on the sample MySQL database. Guillaume used the Grails framework, whereas Charles presented a Rails application. Frank however didn&#8217;t implement all the functionality using Jython, and Jorge failed to implement anything at all and consequently showed us something else in Scala.Here highest marks were agin given to JRuby and Groovy.</p>
<p>The third round was the &#8220;Show your coolness&#8221; round. Guillaume showed us a HTML page from the JBoss Seam project which contained the documentation for the Seam and Groovy integration. Charles however showed 2 brilliant demos with cool graphical effects! The app he showed was called &#8220;A face for Stephen Hawking&#8221;, Google that if you&#8217;re interested. Here Jorge showed us how easy it is to write multithreaded applications using Scala. Using the <em>actor</em> keyword it is easy to spawn off new threads which share no mutable state whatsoever. The end result was that Charles won the shootout with JRuby, but Guillaume was a close second with Groovy.</p>
<p>If you want to follow a more blow by blow report, try following my Twitter stream. You can find me at: http://www.twiter.com/hierynomus.</p>
<p><strong>Marco on his day @JavaOne</strong><br />
<em>Oracle keynote</em><br />
Actually I had planned to skip this one to catch some extra z’s but I just couldn’t bear to leave my companions in the cold by having them walk the dangerous streets of San Francisco all by themselves. We were treated to a nice stage play which reminded me of a tell sell commercial. “Wow Mike, so you say that if I process these orders those cool 3d bars will be updated right away?”  Their product seemed cool though, worth taking a closer look at. If only I could remember it’s name ..</p>
<p><em>Creating a Java Platform, Enterprise Edition (Java EE Platform) Appliance, Using the GlassFish, OpenSolaris and Indiana Projects</em><br />
Somewhere between naming this session and actually presenting it, the speakers probably decided they didn’t want to run the risk of a lawsuit, as the name ‘Indiana’ wasn’t mentioned even once. A good thing too, ‘coz mr. Jones still knows how to use that whip! This was about running web applications on appliances, using ZFS (a new kind of openSolaris file system) as a means to rollback, so there won’t be any need for hard-to-do reinstallations. A cool idea, but somehow I think I’ve heard it all before. Also, they used GlassFish v2 for this, and kept on saying how unfortunate it was that it wasn’t modular, Ehm, switch to the new version?</p>
<p><em>Open-Source Service-Oriented Architecture with Service Component Architecture and Apache Tuscany</em><br />
Presented by somebody who looked a lot like a young Martin Sheen and the follow-up to a session I visited yesterday, this managed to make me even more interested in the topic at hand. For those not in the know: SCA is a development &#038; deployment tool for SOA, based around assembled components called composites, and it may very well become the next big thing in the world of SOA.  Or maybe it already is, who can keep track?</p>
<p><em>It’s all about the SOA: RESTful Service-Oriented Architecture at Overstock.com</em><br />
Confession time: I had enrolled for an entirely different session (Java Persistence 2.0) but at the last minute decided to jump ship in what may well be the brightest moment I had all week. My reward was a nice story about how one of the biggest online retailers (it says so in the abstract, so it must be true) made the change from dreadful C to the wonderful delight that is Java in a very short period of time. Glad to know that after all that hard work they can finally enjoy some REST now.</p>
<p>Nothing? Wow, tough crowd ..</p>
<p><em>Creating a Compelling User Experience</em><br />
As all Dutch will probably agree, SOA is nothing to laugh about, which is why this session served as a welcome relief. By far the most fun I had up until now it also gave me some fresh insight on interaction designers and the delicate relationship they hold with those people that just want things to look pretty. Two thumbs and a big toe up for this one.</p>
<p><em>JSR 303: From a World of Constraints to Constrain the World</em><br />
Another non-SOA session, this one took me back to when I used the Struts Validation Framework to model the business logic of a large insurance company,  resulting in several huge xml files. Ah, those were the days .. No big surprises here, which kind of disappointed me to be honest. Nice presentation though, even with the heavy French accent.</p>
<p><em>Epilogue</em><br />
Some nice sessions, two of those that flew by, one which seemed to last forever (mental note: next time after gulping an entire can of soda go to the toilet first before attending a session). SCA was again the highlight of the day, but the presentation about user experience still gives me chuckles thinking about it. Anyway, halfway there, let’s see what tomorrow will bring.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/05/08/javaone-2008-day-two/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F05%2F08%2Fjavaone-2008-day-two%2F&amp;title=JavaOne%202008%20Day%20Two" id="wpa2a_10"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/05/08/javaone-2008-day-two/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>DateTime and TimeZone pains</title>
		<link>http://blog.xebia.com/2008/03/31/datetime-and-timezone-pains/</link>
		<comments>http://blog.xebia.com/2008/03/31/datetime-and-timezone-pains/#comments</comments>
		<pubDate>Mon, 31 Mar 2008 18:46:36 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
				<category><![CDATA[Java]]></category>

	<!-- AutoMeta Start -->
	<category>date</category>
	<category>nuisances</category>
	<category>peculiarities</category>
	<category>calendar</category>
	<category>util</category>
	<category>interpretation</category>
	<category>surprise</category>
	<category>stored</category>
	<category>joda</category>
	<category>time</category>
	<category>datetime</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2008/03/31/datetime-and-timezone-pains/</guid>
		<description><![CDATA[For as long as Java has been around, java.util.Date and java.util.Calendar have been nuisances. This will hopefully very soon be a thing of the past with the addition of JSR-310, the Date and Time API, to the Java API. At the basis of JSR-310 lies the Joda time library, which has been around for quite [...]]]></description>
			<content:encoded><![CDATA[<p>For as long as Java has been around, java.util.Date and java.util.Calendar have been nuisances. This will hopefully very soon be a thing of the past with the addition of <a href="https://jsr-310.dev.java.net/">JSR-310</a>, the Date and Time API, to the Java API. At the basis of JSR-310 lies the <a href="http://joda-time.sourceforge.net">Joda time</a> library, which has been around for quite some time as a replacement for the standard Date and Calendar classes. However that this API is not without its own peculiarities need not come as a surprise, given the complexity of the human interpretation of time all over the world.<br />
<span id="more-479"></span></p>
<p>In our current project we have a value in the database that contains a timestamp in the UTC or &#8220;Zulu&#8221; timezone. This timestamp is fetched from the database using a java.sql.Timestamp instance. Our application however deals with org.joda.time.DateTime instances in the local time zone, which for the Netherlands are either CET (UTC+0100) or CEST (UTC+0200) depending on Daylight Savings Time.</p>
<p>So in a nutshell our problem encompasses converting a UTC java.sql.Timestamp to an org.joda.time.DateTime in the correct time zone, which represents the correct time. Let&#8217;s start off with writing a small skeleton JUnit test:</p>
<pre lang="java">public class DateTimePainsTest extends TestCase {

    private static final String WRONG_TIME = "2008-03-26T20:13:39.059+01:00";
    private static final String CORRECT_TIME = "2008-03-26T21:13:39.059+01:00";
    private long millis;
    private Timestamp timestamp;

    protected void setUp() throws Exception {
        millis = new Date(1206558819059L).getTime(); // 2008-03-26T20:13:39.059+00:00
        timestamp = new Timestamp(millis);
    }

    public void testMillisAndTimestamp() {
        assertEquals(millis, timestamp.getTime());
        assertEquals("2008-03-26 20:13:39.059", timestamp.toString());
    }
}</pre>
<p>Now we want to convert this timestamp to a DateTime object representing the following string: 2008-03-26T21:13:39.059+01:00. We first try the most simple option we can think of:</p>
<pre lang="java">public void testDateTimeConversion1() {
        DateTime dateTime = new DateTime(timestamp.getTime(),
                DateTimeZone.forOffsetHours(1));
        assertEquals(CORRECT_TIME, dateTime.toString());
}</pre>
<p>This test fails. In order to make the test succeed, we have to expect WRONG_TIME in there. Though according to the JavaDoc of DateTime this should have been a step in the right direction:<br />
<code>DateTime(long instant, DateTimeZone zone)<br />
Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z using ISOChronology in the specified time zone.</code><br />
Maybe we should first force the time zone to UTC before converting the DateTime to a European time zone. Let&#8217;s give that a try:</p>
<pre lang="java">public void testDateTimeConversion2() {
        DateTime dateTime = new DateTime(timestamp.getTime(), DateTimeZone.UTC)
                .withZone(DateTimeZone.forOffsetHours(1));
        assertEquals(CORRECT_TIME, dateTime.toString());
}</pre>
<p>This test also fails, substituting WRONG_TIME for CORRECT_TIME yields a green bar, but an undesired result, so we should take a different approach. LocalDateTime is a Joda time class which does not take into account any time zone information. May we can convert this to a DateTime in the correct time zone. Let&#8217;s write a new test case:</p>
<pre lang="java">public void testDateTimeConversion3() {
        DateTime dateTime = new LocalDateTime(timestamp)
                .toDateTime(DateTimeZone.forOffsetHours(1));
        assertEquals(CORRECT_TIME, dateTime.toString());
}</pre>
<p>Again, this test fails. We need to expect the WRONG_TIME in there to get a green bar. What seems to do the trick is converting the LocalDateTime to a DateTime in the UTC time zone, and then assigning the correct time zone to that. Lo and behold, the following test case works:</p>
<pre lang="java">public void testDateTimeConversion4() {
        DateTime try3 = new LocalDateTime(timestamp).toDateTime(DateTimeZone.UTC)
                .withZone(DateTimeZone.forOffsetHours(1));
        assertEquals(CORRECT_TIME, try3.toString());
}</pre>
<p>Though this solution works, I think it is not the most optimal solution. Does anyone know of a better solution? If so, please add a comment.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/03/31/datetime-and-timezone-pains/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F03%2F31%2Fdatetime-and-timezone-pains%2F&amp;title=DateTime%20and%20TimeZone%20pains" id="wpa2a_12"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/03/31/datetime-and-timezone-pains/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Maven2 Dashboard Plugin Released</title>
		<link>http://blog.xebia.com/2008/03/27/maven2-dashboard-plugin-released/</link>
		<comments>http://blog.xebia.com/2008/03/27/maven2-dashboard-plugin-released/#comments</comments>
		<pubDate>Wed, 26 Mar 2008 22:28:38 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Quality Assurance]]></category>
		<category><![CDATA[Maven]]></category>

	<!-- AutoMeta Start -->
	<category>dashboard</category>
	<category>maven2</category>
	<category>released</category>
	<category>plugin</category>
	<category>quality</category>
	<category>hefty</category>
	<category>buildsystem</category>
	<category>metrics</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2008/03/27/maven2-dashboard-plugin-released/</guid>
		<description><![CDATA[Quality is an everyday part of the life of a Xebia software developer. One of the ways to get insight into quality is by looking at metrics like FindBugs, PMD, Simian, Code Coverage, etc. With large software products consisting of different modules, quality assurance can become quite a trying task. This means that tools which [...]]]></description>
			<content:encoded><![CDATA[<p>Quality is an everyday part of the life of a Xebia software developer. One of the ways to get insight into quality is by looking at metrics like FindBugs, PMD, Simian, Code Coverage, etc. With large software products consisting of different modules, quality assurance can become quite a trying task. This means that tools which alleviate this burden are a welcome addition to our toolbox.<br />
<span id="more-260"></span></p>
<p>The Maven 1.x dashboard is such a tool. The Maven site is integrated into our continuous integration process, and the dashboard that is generated provides a birds-eye view of a lot of our quality metrics. This is especially useful when dealing with multi-module projects. For the Maven2 build system a similar plugin is currently available on <a href="http://mojo.codehaus.org/dashboard-maven-plugin">Codehaus</a>. However this plugin is not final yet and in the past we had some trouble to get it to work. Therefore we decided to try and build our own plugin. </p>
<p>As our toolbox heavily leans on a lot of open source products, we decided to give something back to the community and release this plugin as an open source product. The dashboard plugin can be found at the following URL: <a href="http://mojo.os.xebia.com/maven-dashboard-plugin">http://mojo.os.xebia.com/maven-dashboard-plugin</a>. On the site you can find many configuration examples.</p>
<p>In order to use the plugin in your pom, you&#8217;ll have to do some basic configuration. The following example shows what you need to add to your <i>pom.xml</i></p>
<pre lang="xml">
<project>
  ...
<pluginRepositories>
<pluginRepository>
      <id>xebia-maven2</id>
      <name>Xebia Maven2 Repository</name>
      <url>http://mojo.os.xebia.com/repository</url>
      </pluginRepository>
  </pluginRepositories>
  ....
  <build>
<plugins>
      ...
<plugin>
        <groupId>com.xebia.mojo</groupId>
        <artifactId>maven-dashboard-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
</pre>
<p>This configuration will generate a full dashboard when you run the build using the following command line:</p>
<pre>mvn site dashboard:dashboard site:deploy</pre>
<p>The result of the execution of this command for the maven dashboard plugin itself looks like <a href="http://mojo.os.xebia.com/maven-dashboard-plugin/maven-dashboard-report.html">this</a><br />
<img id="image480" src="http://blog.xebia.com/wp-content/uploads/2008/03/Picture 4.png" alt="Sample of Maven Dashboard Plugin" width="600" /></p>
<p>The source code for the plugin is released in <a href="https://os.xebia.com/svn/mojo/maven-dashboard-plugin/trunk/">Subversion</a>, and the Jira issuetracker can be found <a href="http://os.xebia.com/jira/browse/MDP">here</a>.</p>
<p>Now that we&#8217;ve got a Dashboard for Maven2 projects, we can finally get the quality overview and focus on fixing quality assurance issues instead of finding them throughout the different modules of our projects.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/03/27/maven2-dashboard-plugin-released/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F03%2F27%2Fmaven2-dashboard-plugin-released%2F&amp;title=Maven2%20Dashboard%20Plugin%20Released" id="wpa2a_14"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/03/27/maven2-dashboard-plugin-released/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>JavaOne 2008 Scripting preview</title>
		<link>http://blog.xebia.com/2008/03/13/javaone-2008-scripting-preview/</link>
		<comments>http://blog.xebia.com/2008/03/13/javaone-2008-scripting-preview/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 19:45:49 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[JavaOne]]></category>

	<!-- AutoMeta Start -->
	<category>scripting</category>
	<category>panel</category>
	<category>languages</category>
	<category>javaone</category>
	<category>groovy</category>
	<category>javascript</category>
	<category>language</category>
	<category>ruby</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2008/03/13/javaone-2008-scripting-preview/</guid>
		<description><![CDATA[The biggest Java event of the year is coming up again, the JavaOne. For me this is a place of inspiration. Seeing the newest technologies in action and talking to some of the great minds in the Java world, how can one not become inspired! One of the big subjects this year, which has been [...]]]></description>
			<content:encoded><![CDATA[<p>The biggest Java event of the year is coming up again, the JavaOne. For me this is a place of inspiration. Seeing the newest technologies in action and talking to some of the great minds in the Java world, how can one not become inspired!<br />
<span id="more-462"></span></p>
<p>One of the big subjects this year, which has been getting bigger over the past few years is the scripting support on the Java Platform. There are numerous talks on all the different scripting languages. Let&#8217;s get some numbers for an overview:</p>
<table>
<tr>
<td></td>
<td>Technical Session</td>
<td>Panel Session</td>
<td>Birds of a Feather</td>
</tr>
<tr>
<td>Scala</td>
<td>1</td>
<td></td>
<td>1</td>
</tr>
<tr>
<td>Groovy / Grails</td>
<td>7</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>(J)Ruby / Rails</td>
<td>7</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>Jython</td>
<td>1</td>
<td></td>
<td>1</td>
</tr>
</table>
<p>These numbers are based on whether the subject contains the scripting language, or whether the presenters show examples in the language. One of the languages I didn&#8217;t mention is the JavaScript language. JavaScript is a real scripting language, which is supported on the Java platform, but almost every talk on some Webby subject intrinsically deals with JavaScript. This would severely pollute the count.</p>
<p>What we can see from the above table is that Groovy and (J)Ruby are almost equally represented. Whether the organization did this on purpose, or whether it is purely coincidental is unknown to us of course. What is noticeable though is that just one BOF in which Groovy examples are used is presented by a Sun employee, whereas many Technical Sessions on (J)Ruby are presented by Sun employees.</p>
<p>At the JavaOne we&#8217;ll see what direction the community will take with regards to the scripting languages on the JVM. Especially the panel session on Wednesday will provide some insight in how the different languages relate and how the community regards them. I&#8217;ll be there during the panel session to hear and see what the community deems the ideal scripting language.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/03/13/javaone-2008-scripting-preview/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F03%2F13%2Fjavaone-2008-scripting-preview%2F&amp;title=JavaOne%202008%20Scripting%20preview" id="wpa2a_16"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/03/13/javaone-2008-scripting-preview/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Leaking Memory in Java</title>
		<link>http://blog.xebia.com/2007/10/04/leaking-memory-in-java/</link>
		<comments>http://blog.xebia.com/2007/10/04/leaking-memory-in-java/#comments</comments>
		<pubDate>Thu, 04 Oct 2007 10:20:17 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Performance]]></category>

	<!-- AutoMeta Start -->
	<category>testgc</category>
	<category>beginindex</category>
	<category>endindex</category>
	<category>substring</category>
	<category>offset</category>
	<category>substrings</category>
	<category>getsubstring</category>
	<category>char</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2007/10/04/leaking-memory-in-java/</guid>
		<description><![CDATA[Don&#8217;t we all remember the days when we programmed C or C++? You had to use new and delete to explicitly create and remove objects. Sometimes you even had to malloc() an amount of memory. With all these constructs you had to take special care that you cleaned up afterwards, else you were leaking memory. [...]]]></description>
			<content:encoded><![CDATA[<p>Don&#8217;t we all remember the days when we programmed C or C++? You had to use <strong>new</strong> and <strong>delete</strong> to explicitly create and remove objects. Sometimes you even had to <strong>malloc()</strong> an amount of memory. With all these constructs you had to take special care that you cleaned up afterwards, else you were leaking memory.<br />
<span id="more-300"></span></p>
<p>Now however, in the days of Java, most people aren&#8217;t that concerned with memory leaks anymore. The common line of thought is that the Java Garbage Collector will take care of cleaning up behind you. This is of course totally true in all normal cases. But sometimes, the Garbage Collector can&#8217;t clean up, because you still have a reference, even though you didn&#8217;t know that.</p>
<p>I stumbled across this small program while reading <a href="http://www.javapedia.nl">JavaPedia</a>, which clearly shows that Java is also capable of inadvertent memory leaks.</p>
<pre lang="java">
public class TestGC {
  private String large = new String(new char[100000]);

  public String getSubString() {
    return this.large.substring(0,2);
  }

  public static void main(String[] args) {
    ArrayList<String> subStrings = new ArrayList<String>();
    for (int i = 0; i < 1000000; i++) {
      TestGC testGC = new TestGC();
      subStrings.add(testGC.getSubString());
    }
  }
}
</pre>
<p>Now, if you run this, you'll see that it crashes with something like the following stacktrace:</p>
<p><code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space<br />
	at java.lang.String.<init>(String.java:174)<br />
	at TestGC.<init>(TestGC.java:4)<br />
	at TestGC.main(TestGC.java:13)<br />
</code></p>
<p>Why does this happen? We should only be storing 1,000,000 Strings of length 2 right? That would amount to about 40Mb, which should fit in the PermGen space easily. So what happened here? Let's have a look at the substring method in the String class.</p>
<pre lang="java">
public class String {
  // Package private constructor which shares value array for speed.
  String(int offset, int count, char value[]) {
    this.value = value;
    this.offset = offset;
    this.count = count;
  }

  public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
      throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > count) {
      throw new StringIndexOutOfBoundsException(endIndex);
    }
    if (beginIndex > endIndex) {
      throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
    }
    return ((beginIndex == 0) &#038;&#038; (endIndex == count)) ? this :
      new String(offset + beginIndex, endIndex - beginIndex, value);
  }
</pre>
<p>We see that the substring call creates a new String using the given package protected constructor. And the one liner comment immediately shows what the problem is. The character array is shared with the large string. So instead of storing very small substrings, we were storing the large string every time, but with a different offset and length.</p>
<p>This problem extends to other operations, like <em>String.split()</em> and <em?java.util.regex.Matcher.group()</em>. The problem can be easily avoided by adapting the program as follows:</p>
<pre lang="java">
public class TestGC {
  private String large = new String(new char[100000]);

  public String getSubString() {
    return new String(this.large.substring(0,2)); // <-- fixes leak!
  }

  public static void main(String[] args) {
    ArrayList<String> subStrings = new ArrayList<String>();
    for (int i = 0; i < 1000000; i++) {
      TestGC testGC = new TestGC();
      subStrings.add(testGC.getSubString());
    }
  }
}
</pre>
<p>I have many times heard, and also shared this opinion that the String copy constructor is useless and causes problems with not interning Strings. But in this case, it seems to have a right of existence, as it effectively trims the character array, and keeps us from keeping a reference to the very large String.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2007/10/04/leaking-memory-in-java/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2007%2F10%2F04%2Fleaking-memory-in-java%2F&amp;title=Leaking%20Memory%20in%20Java" id="wpa2a_18"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2007/10/04/leaking-memory-in-java/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Testing with(out) aspects</title>
		<link>http://blog.xebia.com/2007/09/26/testing-without-aspects/</link>
		<comments>http://blog.xebia.com/2007/09/26/testing-without-aspects/#comments</comments>
		<pubDate>Wed, 26 Sep 2007 20:59:04 +0000</pubDate>
		<dc:creator>Jeroen van Erp</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Spring]]></category>

	<!-- AutoMeta Start -->
	<category>thief</category>
	<category>jail</category>
	<category>victim</category>
	<category>itemsinposession</category>
	<category>steal</category>
	<category>putinjail</category>
	<category>policeagentaspect</category>
	<category>1000</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2007/09/26/testing-without-aspects/</guid>
		<description><![CDATA[Recently I wanted to add an aspect to some domain object, so that it was saved, the moment it changed state. However, after adding this aspect, the whole build of course failed, because a lot of the unit tests weren&#8217;t expecting the calls which were now woven into the domain object. Of course I could [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I wanted to add an aspect to some domain object, so that it was saved, the moment it changed state. However, after adding this aspect, the whole build of course failed, because a lot of the unit tests weren&#8217;t expecting the calls which were now woven into the domain object.<br />
<span id="more-296"></span></p>
<p>Of course I could alter all the unit tests so that they reflected the change in code.  But this seems to defy the whole purpose of the aspect. Another option is of course postponing the weaving until after the unit tests. This didn&#8217;t seem to be the correct solution either, because I did want to write at least some tests to test that the aspect was doing its job.</p>
<p>So how did I get around this? The answer lay in Spring AOP. It shares much of the syntax of AspectJ, though it doesn&#8217;t (yet) offer all of the functionality. I&#8217;ve created a small sample for your reading pleasure.</p>
<p>At first we&#8217;ll look at a simple domain without aspects.</p>
<p><em>Victim.java</em></p>
<pre lang="java">
public class Victim {
    private int itemsInPosession;

    public Victim(int itemsInPosession) {
        this.itemsInPosession = itemsInPosession;
    }

    public void itemStolen() {
        if (itemsInPosession > 0) {
            itemsInPosession--;
        }
    }

    public int getItemsInPosession() {
        return itemsInPosession;
    }
}
</pre>
<p>And <em>Thief.java</em></p>
<pre lang="java">
public class Thief {
    public void steal(Victim victim) {
        victim.itemStolen();
    }
}
</pre>
<p>Of course we have a unit test to test that the Thief indeed steals from a Victim:</p>
<pre lang="java">
public class ThievingTest extends TestCase {
    public void testShouldSucceedInStealing() {
        Victim victim = new Victim(1000);
        Thief thief = new Thief();
        thief.steal(victim);
        assertEquals(999, victim.getItemsInPosession());
    }
}
</pre>
<p>Running this test shows that the Thief succeeds in stealing an item from the Victim. But of course, we can&#8217;t let Thiefs randomly steal from Victims. We need to introduce a PoliceAgent who can put the Thief in Jail. Let&#8217;s add an interface to Jail, and write a new test asserting that the Thief is put in Jail for stealing.</p>
<p><em>Jail.java</em></p>
<pre lang="java">
public interface Jail {
    public void putInJail(Thief thief);
}
</pre>
<p>And the second unit test class:</p>
<pre lang="java">
public class ThievingJailTest extends TestCase {
    private Jail jail;

    public void setUp() {
        jail = EasyMock.createMock(Jail.class);
    }

    public void testShouldLandInJailForStealing() {
        Victim victim = new Victim(1000);
        Thief thief = new Thief();
        jail.putInJail(thief);
        EasyMock.replay(jail);
        thief.steal(victim);
        EasyMock.verify(jail);
        assertEquals(1000, victim.getItemsInPossession());
    }
}
</pre>
<p>Of course, this test fails, because there is no way to put the Thief in Jail yet. Let&#8217;s add the PoliceAgent as an aspect, because we want to intercept the Thief that is stealing:</p>
<p><em>PoliceAgentAspect.java</em></p>
<pre lang="java">
@Aspect
public class PoliceAgentAspect {
    private Jail jail;

    @Around("execution(void *Thief.steal(..))")
    public void arrestThief(ProceedingJoinPoint joinPoint) {
        Thief thief = (Thief) joinPoint.getThis();
        jail.putInJail(thief);
    }

    public void setJail(Jail jail) {
        this.jail = jail;
    }
}
</pre>
<p>In order for Spring AOP to notice the aspect, and do the wiring, we need to add an applicationContext.xml with the correct beans. In this simple example, the following suffices (I&#8217;ve stripped the namespace declarations for readability):</p>
<pre lang="xml">
<beans>
	<bean id="jail" class="org.easymock.classextension.EasyMock" factory-method="createMock">
		<constructor-arg value="com.xebia.aspects.example.Jail" />
	</bean>

	<bean class="com.xebia.aspects.example.PoliceAgentAspect">
<property name="jail" ref="jail" />
	</bean>

	<bean id="thief" class="com.xebia.aspects.example.Thief"/>
	<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
</pre>
<p>You can see that in the Spring context I&#8217;ve mocked the Jail. This code previously was in the unit test. Also I&#8217;ve added the Thief as a bean which can be injected. This ensures that Spring can intercept the Thief with the PoliceAgentAspect. The modified test looks like this:</p>
<pre lang="java">
public class ThievingJailTest extends AbstractDependencyInjectionSpringContextTests {
    private Jail jail;
    private Thief thief;

    @Override
    protected String[] getConfigLocations() {
        setAutowireMode(AUTOWIRE_BY_NAME);
        return new String[] {"applicationContext.xml"};
    }

    public void testShouldBePutInJailByPoliceAgentAspect() {
        Victim v = new Victim(1000);
        jail.putInJail(thief);

        EasyMock.replay(jail);
        thief.steal(v);
        EasyMock.verify(jail);
        assertEquals(1000, v.getItemsInPosession());
    }

    public void setJail(Jail jail) { this.jail = jail; }
    public void setThief(Thief thief) { this.thief = thief; }
</pre>
<p>When we now run this test it succeeds. Also our old test still runs perfectly and provides a green light. Using Spring AOP, we can ensure that our code works when not using aspects, and that the adding of aspects to our code gives the intended results.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2007/09/26/testing-without-aspects/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2007%2F09%2F26%2Ftesting-without-aspects%2F&amp;title=Testing%20with%28out%29%20aspects" id="wpa2a_20"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2007/09/26/testing-without-aspects/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.xebia.com/author/jvanerp/feed/ ) in 2.23615 seconds, on Feb 9th, 2012 at 3:58 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 9th, 2012 at 4:58 pm UTC -->
