<?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>Sat, 28 Jan 2012 15:53:55 +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>Getting ShowOff source code high-lighting for Clojure</title>
		<link>http://blog.jayway.com/2011/09/10/getting-showoff-source-code-high-lighting-for-clojure/</link>
		<comments>http://blog.jayway.com/2011/09/10/getting-showoff-source-code-high-lighting-for-clojure/#comments</comments>
		<pubDate>Fri, 09 Sep 2011 22:50:29 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[User Experience]]></category>
		<category><![CDATA[clojure source highlight]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9274</guid>
		<description><![CDATA[ShowOff is a presentation software where you create your slides by writing simple text files containing markdown formatting. Styling is done using CSS. The slides are served by a web server and can be displayed in a web browser. With a simple command, a presentation can be deployed on Heroku for everyone to see. ShowOff [...]]]></description>
			<content:encoded><![CDATA[<p><a href="https://github.com/schacon/showoff">ShowOff</a> is a presentation software where you create your slides by writing simple text files containing <a href="http://daringfireball.net/projects/markdown/">markdown</a> formatting. Styling is done using CSS. The slides are served by a web server and can be displayed in a web browser. With a simple command, a presentation can be deployed on <a href="http://www.heroku.com/">Heroku</a> for everyone to see. ShowOff can even execute code and show the result (currently that's possible for Ruby and JavaScript).</p>
<p>ShowOff is great if you are fed up with the bloated presentation applications that make a mess of your source code. Text files means that presentations can be properly version controlled. It's easy to re-arrange slides and sections. ShowOff uses <a href="http://shjs.sourceforge.net/">SHJS</a> to highlight code blocks. It supports many languages, but currently not <a href="http://clojure.org/">Clojure</a>. Searching around for a while revealed <a href="https://gist.github.com/265810/78857041d922c21488415a9b7ec0300aece47009">a Gist of SHJS styling code</a> that I wanted to try out:</p>
<pre>
# Clojure syntax highlighting for GNU source-highlight
# rocks with SHJS
comment start ";"
include "number.lang"
vardef SPECIALCHAR = '\\.'
environment string delim "\"" "\"" begin
  specialchar = $SPECIALCHAR
end
type = "int|byte|boolean|char|long|float|double|short|void"
vardef FUNCTION = '\(([[:alpha:]]|_)[[:word:]]*(?=[[:blank:]]*)'
function = $FUNCTION
include "symbols.lang"
</pre>
<p>This is what I did on my MacOSX Snow Leopard to get ShowOff to high-light Clojure source code:</p>
<p>1. Install some pre-requisites. I use <a href="http://mxcl.github.com/homebrew/">HomeBrew</a>, but you can use MacPorts or whatever package manager you prefer.</p>
<pre>
gem install showoff</code>
brew install yuicompressor
brew install source-highlight
brew install unix2dos
</pre>
<p>2. Download the <a href="http://sourceforge.net/projects/shjs/files/shjs/0.6/shjs-0.6-src.zip/download">shjs source distro</a>.</p>
<p>3. Unzip shjs-0.6-src.zip somewhere which we will call SHJS_HOME</p>
<p>4. cd SHJS_HOME</p>
<p>5. touch source-highlight-lang/clojure.lang</p>
<p>6. Edit source-highlight-lang/clojure.lang and paste <a href="https://gist.github.com/265810/78857041d922c21488415a9b7ec0300aece47009">this Clojure source code high-lighting spec</a> (that's the same as displayed above).</p>
<p>7. My Perl installation needed a recursive descent parser, so I did this: <code><br />
cpan install Parse::RecDescent</code></p>
<p>8. make</p>
<p>9. I then copied the resulting minified JavaScript file to where my ShowOff gem keeps the language style files. I use the <a href="http://beginrescueend.com/">RVM</a> Ruby manager, so this is where I needed it:</p>
<pre>
cp lang/sh_clojure.min.js ~/.rvm/gems/ruby-1.9.2-p290/gems/showoff-0.4.2/public/js/sh_lang/
</pre>
<p>Should you discover that you need some more tools installed, you can clean up with <code>make maintainer-clean</code>. After you installed whatever you were missing, run <code>make</code> again.</p>
<h2>Testing Clojure high-lighting</h2>
<p>In order to test this, we will create a simple presentation called "mypres":</p>
<pre>
showoff init mypres
</pre>
<p>This creates a new directory <code>mypres</code>. We go to that directory and look around:</p>
<pre>
.
├── one
│   └── 01_slide.md
└── showoff.json
</pre>
<p>OK, so we have now the skeleton of a presentation, containing a section folder named <code>one</code> and a set of slides in the <code>01_slide.md</code> file. Looking closer at that file, we see this:</p>
<pre>
!SLIDE
# My Presentation #

!SLIDE bullets incremental
# Bullet Points #

* first point
* second point
* third point
</pre>
<p>We will now add to this file a slide definition with some Clojure source code, formatted as a code block by indenting it. Note that we have preceded the code with <code>@@@ clojure</code>, in order to tell ShowOff what language we want to format the block as:</p>
<pre>
!SLIDE encode-symbol
# Huffman encoding #

	@@@ clojure
	(defn encode
	  "takes as arguments a message and a tree
	 and produces the list of bits that gives
	 the encoded message"
	[[first & rest :as message] tree]
	  (when (seq message)
	    (concat (encode-symbol first tree)
	            (encode rest tree))))
</pre>
<p>We serve the presentation:</p>
<pre>
$ showoff serve
</pre>
<p>Finally we can watch the presentation by browsing to http://localhost:9090</p>
<div id="attachment_9288" class="wp-caption alignnone" style="width: 310px"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/ShowOff-with-Clojure1.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/ShowOff-with-Clojure1-300x187.png" alt="" title="ShowOff with Clojure" width="300" height="187" class="size-medium wp-image-9288" /></a><p class="wp-caption-text">ShowOff source code high-lighting for Clojure</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/10/getting-showoff-source-code-high-lighting-for-clojure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Clojure third language officially supported on Heroku</title>
		<link>http://blog.jayway.com/2011/07/07/clojure-third-language-officially-supported-on-heroku/</link>
		<comments>http://blog.jayway.com/2011/07/07/clojure-third-language-officially-supported-on-heroku/#comments</comments>
		<pubDate>Thu, 07 Jul 2011 00:34:11 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[heroku]]></category>
		<category><![CDATA[official]]></category>
		<category><![CDATA[support]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9012</guid>
		<description><![CDATA[According to this blog entry on Heroku, Clojure becomes the third language officially supported on the Cedar stack, after Ruby and Node.js. They write: - "Clojure combines the expressiveness of Lisp, the agility of a dynamic language, the performance of a compiled language, and the wide applicability of the JVM in a robust, production-ready package. [...]]]></description>
			<content:encoded><![CDATA[<p>According to <a href="http://blog.heroku.com/archives/2011/7/5/clojure_on_heroku/">this blog entry</a> on Heroku, Clojure becomes the third language officially supported on the Cedar stack, after Ruby and Node.js. They write:</p>
<p>- "Clojure combines the expressiveness of Lisp, the agility of a dynamic language, the performance of a compiled language, and the wide applicability of the JVM in a robust, production-ready package. Clojure is a practical language designed to support high-performance, concurrent applications which efficiently interoperate with other software in the JVM ecosystem. All of this combines to make it an ideal tool for the programmer to quickly build robust programs."</p>
<p>And motivate why they chose to support Clojure:</p>
<p>- "Clojure covers a new use case on the Heroku platform: components which demand correctness, performance, composability; and optionally, access to the Java ecosystem."</p>
<p>Ladies and gentlemen, it's time to consider moving the parenthesis from the end of the method name to the beginning of the function call. Try it, you'll like it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/07/07/clojure-third-language-officially-supported-on-heroku/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deploying a Clojure web app on Heroku</title>
		<link>http://blog.jayway.com/2011/06/13/deploying-a-clojure-web-app-on-heroku/</link>
		<comments>http://blog.jayway.com/2011/06/13/deploying-a-clojure-web-app-on-heroku/#comments</comments>
		<pubDate>Mon, 13 Jun 2011 13:56:05 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[heroku]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8712</guid>
		<description><![CDATA[<p><a href="http://www.heroku.com/">Heroku</a> is a cloud application platform for Ruby/Rails and Node.js. However, the <a href="http://devcenter.heroku.com/articles/cedar">Cedar stack</a> on Heroku makes it possible to deploy other types of applications. In this blog entry, I will first describe how to write a simple <a href="http://clojure.org">Clojure</a> web app using the <a href="https://github.com/mmcgrana/ring">Ring library</a> and the build tool <a href="https://github.com/technomancy/leiningen">Leiningen</a>. Then I will show how to deploy this Clojure web app on Heroku, using nothing but Git. I will make a change and see how to deploy that. I will also show how to easily roll back to a previous release.</p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.heroku.com/">Heroku</a> is a cloud application platform for Ruby/Rails and Node.js. However, the <a href="http://devcenter.heroku.com/articles/cedar">Cedar stack</a> on Heroku makes it possible to deploy other types of applications. In this blog entry, I will first describe how to write a simple <a href="http://clojure.org">Clojure</a> web app using the <a href="https://github.com/mmcgrana/ring">Ring library</a> and the build tool <a href="https://github.com/technomancy/leiningen">Leiningen</a>. Then I will show how to deploy this Clojure web app on Heroku, using nothing but Git. I will make a change and see how to deploy that. I will also show how to easily roll back to a previous release.</p>
<h2>Clojure maps</h2>
<p>A map is a data structure that associates keys to values. Maps are very important in Clojure, because they are used to store entity data, much like custom classes with fields and setters/getters are used in traditional object-oriented languages like Java. In the Java world, we have java.util.Map. They are somewhat cumbersome to work with, mostly due to the static, generic typing, but also because there is no literal map syntax, plus the fact that you can't initialize it with elements. You must first create it, then mutate it:</p>
<pre class="brush: java;gutter: false;">
import java.util.Map;
import java.util.HashMap;

Map&lt;String,Object&gt; map = new HashMap&lt;String,Object&gt;();
map.put("somekey", "somevalue");
</pre>
<p>Clojure maps, on the other hand, have a very concise literal syntax. Zero or more key-value pairs between curly braces. That's it.</p>
<pre class="brush: clojure;gutter: false;">
(def map {:somekey "somevalue"})
</pre>
<p>The key <code>:somekey</code> in the map above is a Clojure <code>keyword</code>. Keywords are symbolic identifiers that always evaluate to themselves, and they have a very fast equality check. For those reasons (and others, as we will see), keywords are often used, rather than strings, as keys in maps.</p>
<p>A Clojure map is not only a data structure, it is also a function. When a map is called with a key, it will return the corresponding value (or nil if no key was found). It can look like this when testing it from the <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a>:</p>
<pre class="brush: clojure;gutter: false;">
user&gt; (def animal {:species :lion, :name "Leo", :age 3})
user&gt; (animal :name)
"Leo"
</pre>
<p>In fact, keywords are functions too. When a keyword is called with a map as argument, it will look itself up in the map and return the matching value:</p>
<pre class="brush: clojure;gutter: false;">
user&gt; (:name animal)
"Leo"
</pre>
<p>This form is more common in idiomatic Clojure.</p>
<h2>The Ring library</h2>
<p>Ring is a Clojure web applications library inspired by Ruby's Rack. Ring abstracts the <span class="caps">HTTP</span> request and response as maps, and expects handlers to be functions that take a map as argument and returns a map. The returned map is transformed by Ring into a <span class="caps">HTTP</span> response, which is sent back to the caller. This is a simple, but powerful abstraction. It means that web handlers can be written as regular functions, which can be tested in isolation. Web libraries like <a href="https://github.com/weavejester/compojure/wiki">Compojure</a> build on top of the Ring abstraction and provide more high-level constructs, like routing. In order to not complicate this example, however, we will stick to plain Ring.</p>
<p>Let's say that we have a <span class="caps">HTTP</span> request that looks like this:</p>
<pre class="brush: plain;gutter: false;">
GET /welcome HTTP/1.1
HOST: www.sayhello.com
</pre>
<p>Ring transforms this into a Clojure map that looks like this:</p>
<pre class="brush: clojure;">
{:protocol        :http
 :request-method  :get
 :uri             "/welcome"
 :server-name     "www.sayhello.com"}
</pre>
<p>Let's further assume that we want to generate a corresponding <span class="caps">HTTP</span> response:</p>
<pre class="brush: plain;gutter: false;">
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 11

Hello world
</pre>
<p>In order to produce that <span class="caps">HTTP</span> response, Ring expects this map:</p>
<pre class="brush: clojure;">
{:status 200
 :headers
    {"Content-Type" "text/plain"
     "Content-Length" 11}
 :body "Hello world"}
</pre>
<p>So all we need to do is to provide a function that returns the above map, like this:</p>
<pre class="brush: clojure;highlight:1">
(defn app [req]
  {:status 200
   :headers
      {"Content-Type" "text/plain"
       "Content-Length" 11}
   :body "Hello world"})
</pre>
<p>Ring provides a <code>response</code> convenience function that returns a skeletal response map with status 200, no headers, and the given argument as body:</p>
<pre class="brush: clojure;highlight:[1,3]">
(use 'ring.util.response)
(defn app [req]
  (response "Hello world"))
</pre>
<p>We'll use the <code>response</code> function in our example later.</p>
<h2>Leiningen</h2>
<p>In order to manage our dependencies, we will use the <a href="https://github.com/technomancy/leiningen">Leiningen</a> build tool. The simplest way to install it is to download the <a href="https://github.com/technomancy/leiningen/raw/stable/bin/lein">stable release</a> of the script and place it somewhere in the <span class="caps">PATH</span>, like ~/bin. Then run <code>lein self-install</code>:</p>
<pre class="brush: plain;gutter: false;">
$ lein self-install
Downloading Leiningen now...
...

$ lein version
Leiningen 1.5.2 on Java 1.6.0_24 Java HotSpot(TM) 64-Bit Server VM
</pre>
<h2>Building the web application</h2>
<p>We create a new project and go there:</p>
<pre class="brush: plain;gutter: false;">
$ lein new cljheroku
$ cd cljheroku
</pre>
<p>The newly created directory contains the following files:</p>
<pre class="brush: plain;gutter: false;">
cljheroku/
├── README
├── project.clj
├── src
│   └── cljheroku
│       └── core.clj
└── test
    └── cljheroku
        └── test
            └── core.clj
</pre>
<p>First we need to create a Procfile for Heroku:</p>
<pre class="brush: plain;gutter: false;">
$ echo "web: lein run -m cljheroku.core" &gt; Procfile
</pre>
<p>This will have Leiningen start the web application by running the function called <code>-main</code> in the namespace cljheroku.core, ie the file <code>src/cljheroku/core.clj</code>. We'll change that file to contain this:</p>
<pre class="brush: clojure;">
(ns cljheroku.core
  (:use ring.util.response
        ring.adapter.jetty))

(defn app [req]
  (response "Hello World"))

(defn -main []
  (let [port (Integer/parseInt (get (System/getenv) "PORT" "8080"))]
    (run-jetty app {:port port})))
</pre>
<p>Let's look at this code in more detail. We begin with the first chunk:</p>
<pre class="brush: clojure; first-line: 01;">
(ns cljheroku.core
  (:use ring.util.response
        ring.adapter.jetty))
</pre>
<p>The <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/ns">ns macro</a> will create a namespace cljheroku.core and load all functions in the namespaces ring.util.response and ring.adapter.jetty. Since we used <code>:use</code> and not <code>:require</code>, these functions can be referenced by name, without any prefix or namespace qualifier. This enables us to write <code>(response ...)</code> instead of <code>(ring.util.response/response ...)</code>.</p>
<p>Then we define our Ring handler called <code>app</code>.</p>
<pre class="brush: clojure; first-line: 05;">
(defn app [req]
  (response "Hello World"))
</pre>
<p>As you can see, it's just a regular function that takes one argument: a <span class="caps">HTTP</span> request map, and returns the result of the response function: a <span class="caps">HTTP</span> response map. If we wanted to set the Content-Type header, we could use the <code>content-type</code> function, another function from ring.util.response. Instead of <code>(response "Hello world")</code>, we would pass the response through the <code>content-type</code> function: <code>(content-type (response "Hello world") "text/plain")</code>. But here we will just use <code>response</code>.</p>
<p>Finally we specify a <code>-main</code> function.</p>
<pre class="brush: clojure; first-line: 8;">
(defn -main []
  (let [port (Integer/parseInt (get (System/getenv) "PORT" "8080"))]
    (run-jetty app {:port port})))
</pre>
<p>It will serve the same purpose as the Java main method, namely provide an entry point from the outside world. It gets the value of the <span class="caps">PORT</span> environment variable, or uses 8080 as default. It can be enlightening to analyze that part in detail. <code>(System/getenv)</code> is simply Clojure's way of calling Java's static method <code>System.getenv()</code>, which returns a java.util.Map. The <code>get</code> function takes a map (yes, it works with Java maps too), a key and a default value, and returns the matching value. So, <code>(get (System/getenv) "PORT" "8080")</code> will get the <span class="caps">PORT</span> variable from the environment, and if there is no <span class="caps">PORT</span> set there, it will return "8080". The resulting string value of the port is parsed into an integer, and is stored as the local variable <code>port</code>. This value is then passed in to the Jetty adapter as part of a configuration map. All this in two lines. If you're not used to Clojure's lack of ceremony, you might find it overwhelming. I personally find it refreshingly to-the-point.</p>
<p>OK, that was the source code for our handler. We now need to adjust the project.clj file slightly, and provide a dependency to Ring. We'll also add an exclusion of a duplicate dependency that Jetty has. Here is the resulting project.clj:</p>
<pre class="brush: clojure;">
(defproject cljheroku "1.0.0-SNAPSHOT"
  :description "Example Ring app running on Heroku"
  :dependencies [[org.clojure/clojure "1.2.1"]
                 [ring/ring-core "0.3.8"]
                 [ring/ring-jetty-adapter "0.3.8"]]
  :exclusions [org.mortbay.jetty/servlet-api])
</pre>
<p>Before we do anything else, though, we should add this baby to Git:</p>
<pre class="brush: plain;gutter: false;">
$ git init
Initialized empty Git repository in /Users/john/Source/cljheroku/.git/

$ git add .

$ git commit -m "Initial commit"
</pre>
<p>We should probably push this to a maintained repository somewhere, but for our purposes, we have now stored this in Git.</p>
<h2>Testing locally</h2>
<p>Before we test it, we will ask Leiningen to retrieve the dependencies:</p>
<pre class="brush: plain;gutter: false;">
$ lein deps
</pre>
<p>The lib directory now contains a list of jars that we need. Leiningen will make sure they all get on the classpath without you ever having to see it. You <em>can</em> ask Leiningen for the classpath, though, should you really like to see it:</p>
<pre class="brush: plain;gutter: false;">
$ lein classpath
</pre>
<p>You can also have Leiningen create a pom file for you, which can be handy if you need to look at the dependency:tree, import the project into an <span class="caps">IDE</span> that only knows Maven; things like that:</p>
<pre class="brush: plain;gutter: false;">
$ lein pom
</pre>
<p>Anyway, we can now start this web application using the same command as we placed in the Procfile for Heroku. It will start Clojure with the correct classpath, find and make available the given namespace (cljheroku.core), and call its <code>-main</code> function with any given arguments (none, in our case):</p>
<pre class="brush: plain;gutter: false;">
$ lein run -m cljheroku.core
2011-06-12 18:41:24.927:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2011-06-12 18:41:24.928:INFO::jetty-6.1.26
2011-06-12 18:41:24.959:INFO::Started SocketConnector@0.0.0.0:8080
</pre>
<p>Browsing to localhost:8080 shows a page with "Hello world" on it. Good. It works.</p>
<p>We now change the handler function to instead respond with, say, "Hello everyone" and save it. When we reload the page, the new message appears. Excellent. It reloads automatically.</p>
<p>OK. We're happy with our web application and want to deploy it into the cloud. What do we do?</p>
<h2>Deploying on Heroku</h2>
<p>Heroku is, as I mentioned at the beginning, mainly a Ruby application platform. The command line tool for working with Heroku is a Ruby Gem. We first need to install Ruby and RubyGems. Assuming that has been done, we need to get the heroku gem:</p>
<pre class="brush: plain;gutter: false;">
$ sudo gem install heroku
</pre>
<p>Now we can create an app on the Cedar stack:</p>
<pre class="brush: plain;gutter: false;">
$ heroku create --stack cedar
Enter your Heroku credentials.
Email: john.doe@example.com
Password:
Found existing public key: /Users/john/.ssh/id_rsa.pub
Would you like to associate it with your Heroku account? [Yn]
Uploading ssh public key /Users/john/.ssh/id_rsa.pub
Creating furious-sword-794... done, stack is cedar
http://furious-sword-794.herokuapp.com/ | git@heroku.com:furious-sword-794.git
Git remote heroku added
</pre>
<p>We can list the remote repositories to see what the last sentence above meant:</p>
<pre class="brush: plain;gutter: false;">
$ git remote -v
heroku	git@heroku.com:furious-sword-794.git (fetch)
heroku	git@heroku.com:furious-sword-794.git (push)
</pre>
<p>And finally, in order to deploy our first verison of the web app, we push everything to heroku:</p>
<pre class="brush: plain;gutter: false;">
$ git push heroku master
The authenticity of host 'heroku.com (50.19.85.156)' can't be established.
RSA key fingerprint is 8b:48:5e:67:0e:c9:16:47:32:f2:87:0c:1f:c8:60:ad.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'heroku.com,50.19.85.156' (RSA) to the list of known hosts.
Counting objects: 13, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (13/13), 1.27 KiB, done.
Total 13 (delta 0), reused 0 (delta 0)

-----&gt; Heroku receiving push
-----&gt; Clojure app detected
-----&gt; Installing Leiningen
       Downloading: leiningen-1.5.2-standalone.jar
       Writing: lein script
-----&gt; Installing dependencies with Leiningen
       Running: lein deps :skip-dev
       Downloading: org/clojure/clojure/1.2.1/clojure-1.2.1.pom from central
       Downloading: ring/ring-core/0.3.8/ring-core-0.3.8.pom from clojars
       ...
       Copying 10 files to /tmp/build_19juox87ngduz/lib
-----&gt; Discovering process types
       Procfile declares types -&gt; web
-----&gt; Compiled slug size is 11.0MB
-----&gt; Launching... done, v4
       http://furious-sword-794.herokuapp.com deployed to Heroku

To git@heroku.com:furious-sword-794.git
 * [new branch]      master -&gt; master
</pre>
<p>We browse to http://furious-sword-794.herokuapp.com, and we see the text "Hello world" (if you remembered to change back from "Hello everyone"). Now we make a small change:</p>
<pre class="brush: plain;gutter: false;">
-  (response "Hello World"))
+  (response "Hello World, I tell you!"))
</pre>
<p>All we need to do to deploy the change is to commit it, and then push to heroku:</p>
<pre class="brush: plain;gutter: false;">
$ git ci -a
$ git push heroku master
</pre>
<p>When we reload the page, the new text is there.</p>
<h2>Roll back to previous release</h2>
<p>We can list the releases that have been pushed:</p>
<pre class="brush: plain;gutter: false;">
$ heroku releases
Rel   Change                          By                    When
----  ----------------------          ----------            ----------
v5    Deploy 34516b0                  john.doe@examp..  3 minutes ago
v4    Deploy e471ca1                  john.doe@examp..  5 minutes ago
</pre>
<p>Let's say there was a problem with the release that was just deployed, and we want to roll back. With Heroku, it's trivial to roll back to the previous release:</p>
<pre class="brush: plain;gutter: false;">
$ heroku rollback
Rolled back to v4
</pre>
<p>When we're done with this web app completely, we can destroy it like this:</p>
<pre class="brush: plain;gutter: false;">
$ heroku apps:destroy
</pre>
<p>It's even possible to roll back to earlier releases, but I won't show that here. This concludes the Clojure-on-Heroku guide. Thank you for your time.</p>
<h2>References</h2>
<ol>
<li>Heroku: <a href="http://www.heroku.com/">http://www.heroku.com/</a></li>
<li>Clojure: <a href="http://clojure.org/">http://clojure.org/</a></li>
<li>Ring library: <a href="https://github.com/mmcgrana/ring">https://github.com/mmcgrana/ring</a></li>
<li>Leiningen: <a href="https://github.com/technomancy/leiningen">https://github.com/technomancy/leiningen</a></li>
<li>Compojure: <a href="https://github.com/weavejester/compojure/wiki">https://github.com/weavejester/compojure/wiki</a></li>
<li><a href="http://flightcaster.com/">FlightCaster</a> uses Clojure and Heroku: <a href="http://www.infoq.com/articles/flightcaster-clojure-rails">http://www.infoq.com/articles/flightcaster-clojure-rails</a></li>
<li>I got the idea for this blog from this Gist: <a href="https://gist.github.com/1001206">https://gist.github.com/1001206</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/06/13/deploying-a-clojure-web-app-on-heroku/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Numerical Integration (With Precision)</title>
		<link>http://blog.jayway.com/2011/04/02/numerical-integration-with-precision/</link>
		<comments>http://blog.jayway.com/2011/04/02/numerical-integration-with-precision/#comments</comments>
		<pubDate>Sat, 02 Apr 2011 09:00:16 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[bigdecimal]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[numerical]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7665</guid>
		<description><![CDATA[In a <a href="http://blog.jayway.com/2011/03/20/the-substitution-model-a-tool-for-understanding-recursion/">previous blog entry</a>, I explained the higher-order function <code>sum</code> and how to use the Substitution Model to follow the execution of a function. In this entry, I will use the <code>sum</code> function to perform numerical integration, and in the process run into some pitfalls of Java's <a href="http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html">BigDecimal</a>. I will show how the language <a href="http://clojure.org/">Clojure</a> provides an elegant solution to the "exact quotient cannot be represented" problem of BigDecimal.]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://blog.jayway.com/2011/03/20/the-substitution-model-a-tool-for-understanding-recursion/">previous blog entry</a>, I explained the higher-order function <code>sum</code> and how to use the Substitution Model to follow the execution of a function. In this entry, I will use the <code>sum</code> function to perform numerical integration, and in the process run into some pitfalls of Java's <a href="http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html">BigDecimal</a>. I will show how the language <a href="http://clojure.org/">Clojure</a> provides an elegant solution to the "exact quotient cannot be represented" problem of BigDecimal.</p>
<p>We will once again look at <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_sec_1.3">Section 1.3</a> of <a href="http://mitpress.mit.edu/sicp/">Structure and Interpretation of Computer Programs</a>, <em>Formulating Abstractions with Higher-Order Procedures</em>. To recap, the <code>sum</code> function is an abstraction of a sum of some sequence. It takes a <code>term</code> function for calculating the current term, a start value <code>a</code>, a <code>next</code> function for calculating the next value of <code>a</code>, and an end value <code>b</code>:</p>
<pre class="brush: clojure;">
(defn sum [term a next b]
  (if (> a b)
    0
    (+ (term a)
       (sum term (next a) next b))))
</pre>
<p>After introducing the <code>sum</code> function, the authors describe a simple sum for calculating the integral of a function:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/04/eqn178750.gif" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/04/eqn178750.gif" alt="" title="eqn178750" width="466" height="43" class="alignnone size-full wp-image-7863" /></a></p>
<p>Looking at the first term, we see that <code>(a+dx/2)</code> is the start value, ie what we will pass as the <code>a</code> parameter to <code>sum</code>. The <code>term</code> function for calculating the value of the current term is obviously <code>f</code>. </p>
<p>We can also see that each term has one <code>dx</code> added to it. The first term has no <code>dx</code>, the second term has one <code>dx</code>, the third term has <code>2dx</code>, etc. A simple function adding <code>dx</code> to its argument will be perfect as the <code>next</code> function. We'll define it as a private function using <code>defn-</code>, to not clutter the namespace with internal functions. However, it needs to know the <code>dx</code>, so we'll define it inside the <code>integral</code> function, like this:</p>
<pre class="brush: clojure; highlight: 2">
(defn integral [f a b dx]
  (defn- add-dx [x] (+ x dx))
  ...
</pre>
<p>Finally, we need to multiply the result of calling <code>sum</code> by <code>dx</code>. Here is the implementation of the <code>integral</code> function:</p>
<pre class="brush: clojure; highlight: [3,4]">
(defn integral [f a b dx]
  (defn- add-dx [x] (+ x dx))
  (* (sum f (+ a (/ dx 2)) add-dx b)
     dx))
</pre>
<p>We'll need a function that we can pass as <code>f</code>, so we can do some interesting integration. Let's use <code>cube</code>:</p>
<pre class="brush: clojure;">
(defn cube [x] (* x x x))
</pre>
<p>The integral of <code>x^3</code> is <code>x^4/4</code>. Integrating from <code>0</code> to <code>1</code> results in <code>(1^4)/4 = 1/4 = 0.25</code>. That's what we will compare with.</p>
<p>Let's test our <code>integral</code> function using a <code>dx</code> of, say <code>0.01</code>:</p>
<pre class="brush: clojure; gutter: false;">
user> (integral cube 0 1 0.01)
0.24998750000000042
</pre>
<p>Not that bad. However, in <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_thm_1.29">Exercise 1.29</a>, the authors suggest using Simpson's Rule, which is a more accurate method of numerical integration.</p>
<h2>Simpson's Rule</h2>
<p>Simpson's Rule for numerical integration goes like this:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/eqn178228.gif" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/eqn178228.gif" alt="" title="eqn178228" width="451" height="41" class="alignnone size-full wp-image-7773" /></a><br />
&nbsp;<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/eqn177402.gif" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/eqn177402.gif" alt="" title="eqn177402" width="105" height="18" class="alignnone size-full wp-image-7771" /></a><br />
&nbsp;<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/eqn177403.gif" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/eqn177403.gif" alt="" title="eqn177403" width="257" height="37" class="alignnone size-full wp-image-7772" /></a></p>
<p>OK, so how do we squeeze this into the <code>sum</code> function? First we note that <code>h</code> is used in more than one place, so we'll begin by creating a local binding <code>h</code>. We'll also multiply the result of <code>sum</code> with <code>h/3</code>:</p>
<pre class="brush: clojure;">
(defn simpson-sum [f a b n]
  (let [h (/ (- b a) n)]
	...
    (* (sum ... ... ... ...)
       (/ h 3))))
</pre>
<p>Next, we see that the factor of each term is alternating between 4 and 2, except the first and the last one, which are 1. This can be implemented as a conditional:</p>
<pre class="brush: clojure;">
(cond (zero? k) y
      (= k n) y
      (odd? k) (* 4 y)
      (even? k) (* 2 y))
</pre>
<p>The <code>k</code> will be provided as a parameter, as we'll see in a second, but we're missing the <code>y</code>. So let's add the expression of <code>y</code> and package it all up in a function inside <code>simpson-sum</code>:</p>
<pre class="brush: clojure; highlight: [3,4,5,6,7,8]">
(defn simpson-sum [f a b n]
  (let [h (/ (- b a) n)]
  (defn- simpson-term [k]
    (let [y (f (+ a (* k h)))]
      (cond (zero? k) y
            (= k n) y
            (odd? k) (* 4 y)
            (even? k) (* 2 y))))
    (* (sum ... ... ... ...)
       (/ h 3))))
</pre>
<p>OK, so now we have something that, given a <code>k</code>, provides the corresponding term in the sum, with the correct factor. The sequence for the sum is from <code>0</code> to <code>n</code>, so all we need to do now is to call <code>sum</code> with <code>simpson-term</code> as the <code>term</code> function, zero as the start value of the sequence, <code>inc</code> as the <code>next</code> function, and <code>n</code> as the end of the sequence:</p>
<pre class="brush: clojure; highlight: 9">
(defn simpson-sum [f a b n]
  (let [h (/ (- b a) n)]
    (defn- simpson-term [k]
      (let [y (f (+ a (* k h)))]
        (cond (zero? k) y
              (= k n) y
              (odd? k) (* 4 y)
              (even? k) (* 2 y))))
    (* (sum simpson-term 0 inc n)
       (/ h 3))))
</pre>
<p>The test run on <code>cube</code> using <code>n=100</code> gives some impressive results:</p>
<pre class="brush: clojure; gutter: false;">
user> (simpson-sum cube 0 1 100)
1/4
user> (simpson-sum cube 0 2 100)
4
user> (simpson-sum cube 3 4 100)
175/4
</pre>
<p>Not bad at all. Clojure's use of Ratio enables us to get accurate precision. But what happens if I select a floating point interval?</p>
<pre class="brush: clojure; gutter: false;">
user> (simpson-sum cube 0 0.5 100)
0.015624999999999995
</pre>
<p>Pretty good that too.</p>
<h3>Using BigDecimal</h3>
<p>Now, what if I want to use BigDecimal in order to get really high precision in my floating points? In Clojure, the letter M on a number indicates that it's a BigDecimal literal:</p>
<pre class="brush: clojure; gutter: false;">
user> (simpson-sum cube 0 0.5M 100)
Non-terminating decimal expansion; no exact representable decimal result.
  [Thrown class java.lang.ArithmeticException]
Backtrace:
  0: java.math.BigDecimal.divide(BigDecimal.java:1603)
  1: clojure.lang.Numbers$BigDecimalOps.divide(Numbers.java:1067)
  2: clojure.lang.Numbers.divide(Numbers.java:139)
  3: user$simpson_sum.invoke(NO_SOURCE_FILE:1)
</pre>
<p>What happened here? Actually, this is something that can potentially happen whenever using BigDecimal divison, whether it's from Java, Clojure or something else. The JavaDoc for <code>BigDecimal.divide</code> states:</p>
<blockquote><p>divide(BigDecimal divisor)<br />
Returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() - divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.
</p></blockquote>
<p>Could it be that division of <code>h</code> by 3 that messes things up? Division by 3 is always troublesome when using floating point numbers. Anyway, in order to solve this, we need to use a version of <code>BigDecimal.divide</code> that takes a scale (we'll use 10) and a rounding mode. Only line 10 needs to be changed:</p>
<pre class="brush: clojure; highlight: [10];">
(defn simpson-sum [f a b n]
  (let [h (/ (- b a) n)]
    (defn- simpson-term [k]
      (let [y (f (+ a (* k h)))]
        (cond (zero? k) y
              (= k n) y
              (odd? k) (* 4 y)
              (even? k) (* 2 y))))
    (* (sum simpson-term 0 inc n)
       (.divide (bigdec h) 3M 10 java.math.RoundingMode/HALF_UP))))
</pre>
<p>Ugly as hell, but what can you do? (Plenty, actually, as we'll see soon) Let's test it:</p>
<pre class="brush: clojure; gutter: false;">
user> (simpson-sum cube 0 0.5M 100)
0.0156250031250000000000M
</pre>
<p>OK, so it works. Are we happy now? Not really. Look what happens if we use an <code>n</code> that is a multiple of 3:</p>
<pre class="brush: clojure; gutter: false;">
user> (simpson-sum cube 0 0.5M 6)
Non-terminating decimal expansion; no exact representable decimal result.
  [Thrown class java.lang.ArithmeticException]
Backtrace:
  0: java.math.BigDecimal.divide(BigDecimal.java:1603)
  1: clojure.lang.Numbers$BigDecimalOps.divide(Numbers.java:1067)
  2: clojure.lang.Numbers.divide(Numbers.java:139)
  3: user$simpson_sum.invoke(NO_SOURCE_FILE:1)
</pre>
<p>This time it's the other division that is the problem. We'll change line 2 as well:</p>
<pre class="brush: clojure; highlight: 2;">
(defn simpson-sum [f a b n]
  (let [h (.divide (bigdec (- b a)) (bigdec n) 10 java.math.RoundingMode/HALF_UP)]
    (defn- simpson-term [k]
      (let [y (f (+ a (* k h)))]
        (cond (zero? k) y
              (= k n) y
              (odd? k) (* 4 y)
              (even? k) (* 2 y))))
    (* (sum simpson-term 0 inc n)
       (.divide (bigdec h) 3M 10 java.math.RoundingMode/HALF_UP))))
</pre>
<pre class="brush: clojure; gutter: false;">
user> (simpson-sum cube 0 0.5M 6)
0.0156249999937499999925000000049999999992M
</pre>
<p>So, we're good now? No, Clojure has actually a much better way of handling this than resorting to the above. Let's look at the documentation for the function <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/with-precision">with-precision</a>:</p>
<pre class="brush: plain; gutter: false;">
user> (doc with-precision)
-------------------------
clojure.core/with-precision
([precision & exprs])
Macro
  Sets the precision and rounding mode to be used for BigDecimal operations.               

  Usage: (with-precision 10 (/ 1M 3))
  or:    (with-precision 10 :rounding HALF_DOWN (/ 1M 3))                                  

  The rounding mode is one of CEILING, FLOOR, HALF_UP, HALF_DOWN,
  HALF_EVEN, UP, DOWN and UNNECESSARY; it defaults to HALF_UP.
</pre>
<p>OK, so we simply call <code>with-precision</code> with the expression we want precision on. Pretty elegant. Here is the final implementation:</p>
<pre class="brush: clojure; highlight: 2;">
(defn simpson-sum [f a b n]
  (with-precision 10
    (let [h (/ (- b a) n)]
      (defn- simpson-term [k]
        (let [y (f (+ a (* k h)))]
          (cond (zero? k) y
                (= k n) y
                (odd? k) (* 4 y)
                (even? k) (* 2 y))))
      (* (sum simpson-term 0 inc n)
         (/ h 3)))))
</pre>
<p>We're now getting even better results than when manually providing a scale to <code>BigDecimal.divide</code>. Here is a run with <code>n=6</code>:</p>
<pre class="brush: clojure; gutter: false;">
user> (simpson-sum cube 0 0.5M 6)
0.01562500000M
</pre>
<p>Compare that with the <code>integral</code> function that we implemented first. That would have given us this result:</p>
<pre class="brush: clojure; gutter: false;">
user> (integral cube 0 0.5 0.01)
0.015621875000000023
</pre>
<p>The exact integral of <code>x^3</code> between <code>0</code> and <code>0.5</code> is <code>(0.5^4)/4 = 0.015625</code>, so it's clear that Simpson's Rule is very good for numerical integration. The code becomes really elegant even when using BigDecimal arithmetic, thanks to Clojure's support for BigDecimal precision.</p>
<h2>References</h2>
<ul>
<li>Equations were rendered using the LaTeX Equation Editor: <a href="http://www.hamline.edu/~arundquist/equationeditor/">http://www.hamline.edu/~arundquist/equationeditor/</a>
</li>
<li>My previous blog entry about the sum function: <a href="http://blog.jayway.com/2011/03/20/the-substitution-model-a-tool-for-understanding-recursion/">http://blog.jayway.com/2011/03/20/the-substitution-model-a-tool-for-understanding-recursion/</a>
</li>
<li>Structure and Interpretation of Computer Programs: <a href="http://mitpress.mit.edu/sicp/">http://mitpress.mit.edu/sicp/</a>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/04/02/numerical-integration-with-precision/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Substitution Model: A Tool For Understanding Recursion</title>
		<link>http://blog.jayway.com/2011/03/20/the-substitution-model-a-tool-for-understanding-recursion/</link>
		<comments>http://blog.jayway.com/2011/03/20/the-substitution-model-a-tool-for-understanding-recursion/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 13:12:31 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Dynamic languages]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7556</guid>
		<description><![CDATA[Section 1.3 in Structure and Interpretation of Computer Programs is about Formulating Abstractions with Higher-Order Procedures. As an example, the authors use three simple sums: a sum of an integer range a sum of the cubes of an integer range a sum of a series that converges to &#960;/8 The purpose is to highlight what [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_sec_1.3">Section 1.3</a> in <a href="http://mitpress.mit.edu/sicp/">Structure and Interpretation of Computer Programs</a> is about Formulating Abstractions with Higher-Order Procedures. As an example, the authors use three simple sums:</p>
<ul>
<li>a sum of an integer range
</li>
<li>a sum of the cubes of an integer range
</li>
<li>a sum of a series that converges to &pi;/8
</li>
</ul>
<p>The purpose is to highlight what is common between them and what differs. The differences boil down to:</p>
<ol>
<li>calculating the current term
</li>
<li>calculating the next value
</li>
</ol>
<p>The authors show that all three functions can be expressed as calls to a higher-order function. Here is the <code>sum</code> function in <a href="http://clojure.org">Clojure</a>:</p>
<pre class="brush: clojure">
(defn sum [term a next b]
  (if (> a b)
    0
    (+ (term a)
       (sum term (next a) next b))))
</pre>
<p>The function takes four parameters: <code>[term a next b]</code>. <code>term</code> is the function for calculating the current term, <code>a</code> is the start of the range to perform the sum on, <code>next</code> is the function for calculating the next value in the sequence, and <code>b</code> is the end of the range. The <code>sum</code> function first calculates the current term by applying <code>term</code> to <code>a</code>, then adds that to the result of calling itself again, but this time not with <code>a</code>, but the next value in the sequence: <code>(next a)</code>. It keeps doing that until <code>a</code> is greater than <code>b</code>, then the upper bound is reached and the function is done. It doesn't call itself any more, but instead returns zero.</p>
<h1>sum-integers</h1>
<p>Using <code>sum</code> to calculate a sum of integers is easy. Each number in the sequence will itself be the actual term. We use the <code>identity</code> function as <code>term</code>, since it returns its input unchanged. The <code>inc</code> function increments its argument by one, so that is ideal for <code>next</code>. Here is the implementation:</p>
<pre class="brush: clojure">
(defn sum-integers [a b]
  (sum identity a inc b))
</pre>
<p>I'll test the function in my <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a> (<code>user></code> is the prompt):</p>
<pre class="brush: clojure; gutter: false;">
user> (sum-integers 1 10)
55
</pre>
<h1>sum-cubes</h1>
<p>The second example is summing up the cubes of an integer range. We define the <code>cube</code> function:</p>
<pre class="brush: clojure">
(defn cube [x] (* x x x))
</pre>
<p>The implementation of <code>sum-cubes</code> is very similar to <code>sum-integers</code>. We simply replace <code>identity</code> with <code>cube</code>, so the current term will be the cube of the integer, rather than just the integer:</p>
<pre class="brush: clojure">
(defn sum-cubes [a b]
  (sum cube a inc b))
</pre>
<pre class="brush: clojure; gutter: false;">
user> (sum-cubes 1 10)
3025
</pre>
<h1>pi-sum</h1>
<p>The third example is a series that happens to converge to &pi;/8:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/eqn177331.gif" alt="" title="Sum that converges to &pi;/8" width="174" height="35" class="alignnone size-full wp-image-7574" /></p>
<p>In order to be able to apply the generic <code>sum</code> tool to this problem, we need to write two helper functions: one function for calculating the current term: <code>pi-term</code>, and one function for calculating the next value in the sequence: <code>pi-next</code>. We can see, by looking at the series above, that each term is <code>1/(x*(x+2))</code>, and that the next term has an <code>x</code> that is 4 greater than the previous term:</p>
<pre class="brush: clojure">
(defn- pi-term [x] (/ 1 (* x (+ x 2))))
(defn- pi-next [x] (+ x 4))
</pre>
<p>Note that I didn't use <code>defn</code> to define the functions, I used <code>defn-</code>. That is a Clojure feature for making the helper functions private, so we don't clutter up the namespace with internal stuff. Now we have what we need to call <code>sum</code>. </p>
<pre class="brush: clojure">
(defn pi-sum [a b]
  (sum pi-term a pi-next b))
</pre>
<p>We'll test this function with the range 1 to 10, multiplying with 8 so we'll get π (remember that the series converges to π/8):</p>
<pre class="brush: clojure; gutter: false;">
user> (* 8 (pi-sum 1 10))
10312/3465
</pre>
<p>Here we can see that the output is Clojure's built-in type Ratio. Division of integers that can't be reduced to an integer yields a ratio, rather than a floating point or truncated value. This can be really useful, but when the numbers get large, it can be hard to see what the ratio represents:</p>
<pre class="brush: clojure; gutter: false;">
user> (* 8 (pi-sum 1 100))
3400605476464206445954873476681150352328/1089380862964257455695840764614254743075
</pre>
<p>Any numeric operation on a Ratio involving Doubles, will yield a Double. That means we can skip the Ratio and go directly to Double by using 1.0 as the starting point:</p>
<pre class="brush: clojure; gutter: false;">
user> (* 8 (pi-sum 1. 1000))
3.139592655589783
</pre>
<h1>The Substitution Model</h1>
<p>If it's not immediately obvious to you how <code>sum</code> works, you can always use the <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1.5">Substitution Model</a>. Evaluate the body of the procedure with each formal parameter replaced by the corresponding argument. Let's evaluate the call <code>(sum-integers 1 3)</code>:</p>
<p>Retrieve the body of <code>sum-integers</code>:</p>
<pre class="brush: clojure">
(sum identity a inc b)
</pre>
<p>Replace the formal parameters <code>a</code> and <code>b</code> by the arguments <code>1</code> and <code>3</code>:</p>
<pre class="brush: clojure">
(sum identity 1 inc 3)
</pre>
<p>The problem is reduced to evaluating a call to <code>sum</code> with four arguments. So let's retrieve the body of <code>sum</code>:</p>
<pre class="brush: clojure">
(if (> a b)
  0
  (+ (term a)
     (sum term (next a) next b)))
</pre>
<p>Now we replace <code>sum</code>'s formal parameters <code>[term a next b]</code> with our arguments <code>identity</code>, <code>1</code>, <code>inc</code>, and <code>3</code>:</p>
<pre class="brush: clojure; highlight: [1,3,4]">
(if (> 1 3)
  0
  (+ (identity 1)
     (sum identity (inc 1) inc 3)))
</pre>
<p>1 is not greater than 3, so it reduces to:</p>
<pre class="brush: clojure; highlight: 2">
(+ (identity 1)
   (sum identity (inc 1) inc 3))
</pre>
<p><code>(identity 1)</code> evaluates to <code>1</code>, and <code>(inc 1)</code> evaluates to  <code>2</code>, so it reduces to:</p>
<pre class="brush: clojure; highlight: 2">
(+ 1
   (sum identity 2 inc 3))
</pre>
<p>We'll evaluate the call to <code>sum</code> again, directly replacing this time:</p>
<pre class="brush: clojure; highlight: [2,3,4,5]">
(+ 1
  (if (> 2 3)
    0
    (+ (identity 2)
       (sum identity (inc 2) inc 3))))
</pre>
<p>2 is not greater than 3, so this reduces to:</p>
<pre class="brush: clojure; highlight: [2,3]">
(+ 1
  (+ 2
     (sum identity 3 inc 3)))
</pre>
<p>We retrieve the body of <code>sum</code> again, replacing parameters with arguments:</p>
<pre class="brush: clojure; highlight: [3,4,5,6]">
(+ 1
  (+ 2
    (if (> 3 3)
      0
      (+ (identity 3)
         (sum identity (inc 3) inc 3))))
</pre>
<p>3 is not greater than 3, so this reduces to:</p>
<pre class="brush: clojure; highlight: [3,4]">
(+ 1
  (+ 2
    (+ 3
       (sum identity 4 inc 3))))
</pre>
<p>We retrieve the body of <code>sum</code> for the last time:</p>
<pre class="brush: clojure; highlight: [4,5,6,7]">
(+ 1
  (+ 2
    (+ 3
      (if (> 4 3)
        0
        (+ (identity 4)
           (sum identity (inc 4) inc 3))))
</pre>
<p>4 <em>is</em> greater than 3, so this reduces to:</p>
<pre class="brush: clojure; highlight: 4">
(+ 1
  (+ 2
    (+ 3
      0)))
</pre>
<p>which evaluates to 6.</p>
<p>The Substitution Model is a useful technique when you're new to functional programming, or when you just need to know in detail what is really going on in a function.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/03/20/the-substitution-model-a-tool-for-understanding-recursion/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>dbg: A Cool Little Clojure Macro</title>
		<link>http://blog.jayway.com/2011/03/13/dbg-a-cool-little-clojure-macro/</link>
		<comments>http://blog.jayway.com/2011/03/13/dbg-a-cool-little-clojure-macro/#comments</comments>
		<pubDate>Sat, 12 Mar 2011 23:48:03 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[macro]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7536</guid>
		<description><![CDATA[Here's the development of a tiny little macro that is actually pretty useful. The post is quite verbose, because I explain a lot. I want a debug function that first prints the "quoted" (unevaluated) code and then what it evaluates to, so I can write something like this: user> (dbg (+ 1 2)) dbg: (+ [...]]]></description>
			<content:encoded><![CDATA[<p>Here's the development of a tiny little macro that is actually pretty useful. The post is quite verbose, because I explain a lot.</p>
<p>I want a debug function that first prints the "quoted" (unevaluated) code and then what it evaluates to, so I can write something like this:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (dbg (+ 1 2))
dbg: (+ 1 2)=3
3
</pre>
<p>This can be useful in iterations, for example, to check whether you get what you expect in each step:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (for [i (range 5)] (dbg (+ 1 i)))
(dbg: (+ 1 i)=1
dbg: (+ 1 i)=2
dbg: (+ 1 i)=3
dbg: (+ 1 i)=4
dbg: (+ 1 i)=5
1 2 3 4 5)
</pre>
<p>Quoting is best explained using an example:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (+ 1 2 3)
6

user> (quote (+ 1 2 3))
(+ 1 2 3)
</pre>
<p>I'm also going to use the <code>let</code> form, to get convenient temporary access to an expression for the duration of the let scope. Outside the <code>let</code> scope, the symbol is not available:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (let [x (+ 1 2 3)] (println x))
6
nil

user> x
Unable to resolve symbol: x in this context
</pre>
<p>So what I want is code that looks something like this:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">  (let [x body]
    (println (str "dbg: " (quote body) "=" x))
    x)
</pre>
<p>In order to get the code in, we declare it as an argument using the varargs symbol (&), which will give us <code>body</code> as a list of forms (expressions):</p>
<pre class="brush: clojure; ruler: true; gutter: false;">(defsomething dbg [& body]
  (let [x body]
    (println (str "dbg: " (quote body) "=" x))
    x))
</pre>
<p>If we declare this as a function using <code>defn</code>, the arguments (<code>body</code>) will be evaluated before the function is called. We don't want that, so we instead use <code>defmacro</code> to get control over the evaluation. Using the macro syntax quote (<code>`</code>), we can actually write the code exactly as we want it, and then simply <em>unquote</em> (<code>~</code>) the <code>body</code> symbol to get the symbol value:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">(defmacro dbg [& body]
  `(let [x ~body]
     (println (str "dbg: " (quote ~body) "=" x))
     x))
</pre>
<p>However, varargs are delivered as a list, so simply unquoting <code>body</code> will give us some strange result. We can check it using <code>macroexpand-1</code>. You'll see that the macro tries to evaluate <code>body</code> by placing the list inside a list: <code>((+ 1 2))</code>:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (macroexpand-1 '(dbg (+ 1 2)))
(let [user/x ((+ 1 2))]
  (println (str "dbg: " (quote ((+ 1 2)))) "=" user/x))
  user/x)
</pre>
<p>What we want is the contents of the varargs list as separate elements, not as a list. We change the <em>unquote</em> operator (<code>~</code>) to the <em>unquote-splicing</em> operator (<code>~@</code>):</p>
<pre class="brush: clojure; ruler: true; gutter: false;">(defmacro dbg [& body]
  `(let [x ~@body]
     (println (str "dbg: " (quote ~@body) "=" x))
     x))
</pre>
<p>We expand the macro again, and now it looks better:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (macroexpand-1 '(dbg (+ 1 2)))
(let [user/x (+ 1 2)]
  (println (str "dbg: " (quote (+ 1 2)))) "=" user/x))
  user/x)
</pre>
<p>However, note the fully namespace-qualified symbol <code>user/x</code>. Clojure will not allow this due to the risks of name conflicts. When we try to run this macro, we will get an exception: <strong>Can't let qualified name: <code>user/x</code></strong>. We need some way of generating a unique symbol on the fly. We use the symbol generation operator (<code>#</code>):</p>
<pre class="brush: clojure; ruler: true; gutter: false;">(defmacro dbg [& body]
  `(let [x# ~@body]
     (println (str "dbg: " (quote ~@body) "=" x#))
     x#))
</pre>
<p>We test it:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (macroexpand-1 '(dbg (+ 1 2)))
(let [x__2071__auto__ (+ 1 2)]
  (println (str "dbg: " (quote (+ 1 2)) "=" x__2071__auto__))
  x__2071__auto__)
</pre>
<p>OK, so the final macro looks like this:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">(defmacro dbg [& body]
  `(let [x# ~@body]
     (println (str "dbg: " (quote ~@body) "=" x#))
     x#))
</pre>
<p>This boils down to two very simple rules:</p>
<ul>
<li>Any temporary symbols must be appended with # to become unique symbols
</li>
<li>Any varargs arguments must be unquote-spliced using ~@
</li>
</ul>
<p>Let's try our macro:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (dbg (+ 1 2))
(+ 1 2)=3
3
</pre>
<p>Let's confirm that the debug functionality does not affect others using the dbg'd code:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">user> (* 3 (dbg (+ 1 2)))
dbg: (+ 1 2)=3
9
</pre>
<p>Now, let's try the dbg macro on some more advanced code. Here's an implementation of factorial using <code>loop-recur</code>:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">(def factorial
  (fn [n]
    (loop [cnt n acc 1]
      (if (zero? cnt)
        acc
        (recur (dec cnt) (* acc cnt))))))
</pre>
<p>To check what happens inside the <code>recur</code> function, I add calls to <code>dbg</code>:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">
(def factorial
  (fn [n]
    (loop [cnt n acc 1]
      (if (zero? cnt)
        acc
        (recur (dbg (dec cnt)) (dbg (* acc cnt)))))))
</pre>
<p>Calling it gives:</p>
<pre class="brush: clojure; ruler: true; gutter: false;">
user> (factorial 5)
dbg: (dec cnt)=4
dbg: (* acc cnt)=5
dbg: (dec cnt)=3
dbg: (* acc cnt)=20
dbg: (dec cnt)=2
dbg: (* acc cnt)=60
dbg: (dec cnt)=1
dbg: (* acc cnt)=120
dbg: (dec cnt)=0
dbg: (* acc cnt)=120
120
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/03/13/dbg-a-cool-little-clojure-macro/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The country that nearly drove me crazy</title>
		<link>http://blog.jayway.com/2010/11/01/the-country-that-nearly-drove-me-crazy/</link>
		<comments>http://blog.jayway.com/2010/11/01/the-country-that-nearly-drove-me-crazy/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 22:54:04 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[ldap]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6591</guid>
		<description><![CDATA[I just upgraded my OpenLDAP to 2.4.21 and suddenly I couldn't load an LDIF that we in Spring LDAP have used successfully for years. % ldapadd -Dcn=Manager,dc=jayway,dc=se -wsomepwd -f /tmp/t.ldif adding new entry "ou=groups,dc=jayway,dc=se" adding new entry "c=Sweden,dc=jayway,dc=se" ldap_add: Invalid DN syntax (34) After some time of swearing and random changes, I managed to find [...]]]></description>
			<content:encoded><![CDATA[<p>I just upgraded my OpenLDAP to 2.4.21 and suddenly I couldn't load an LDIF that we in <a href="http://www.springsource.org/ldap">Spring LDAP</a> have used successfully for years.</p>
<pre>% ldapadd -Dcn=Manager,dc=jayway,dc=se -wsomepwd -f /tmp/t.ldif
adding new entry "ou=groups,dc=jayway,dc=se"

adding new entry "c=Sweden,dc=jayway,dc=se"
ldap_add: Invalid DN syntax (34)
</pre>
<p>After some time of swearing and random changes, I managed to find out the following little piece of information (which seems rather obvious in hindsight): country (c) is supposed to be the two-letter <a href="http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm">ISO 3166</a> country code. </p>
<p>But hang on now, we have in the Spring LDAP samples successfully been using <tt>c=Sweden</tt> and <tt>c=Norway</tt>. What is this? Well, it's actually very simple. Back in the good old days in 1997, the <a href="http://www.ietf.org/rfc/rfc2256.txt">RFC2256</a> specified the c attribute (countryName) like this:</p>
<pre>
5.7. c

   This attribute contains a two-letter ISO 3166 country code
   (countryName).

    ( 2.5.4.6 NAME 'c' SUP name SINGLE-VALUE )
</pre>
<p>Note that they suggest <em>only in text</em> that it should be the two-letter ISO code. This is curious, since in fact there existed a syntax specification at that time, specified in <a href="http://www.ietf.org/rfc/rfc2252.txt">RFC2252</a>:</p>
<pre>
6.8. Country String

   ( 1.3.6.1.4.1.1466.115.121.1.11 DESC 'Country String' )

   A value in this syntax is encoded the same as a value of Directory
   String syntax.  Note that this syntax is limited to values of exactly
   two printable string characters, as listed in ISO 3166 [14].

      CountryString  = p p

   Example:
      US
</pre>
<p>In the newer spec <a href="http://www.ietf.org/rfc/rfc4519.txt">RFC4519</a> from 2006, they are much more strict:</p>
<pre>
2.2.  'c'

   The 'c' ('countryName' in X.500) attribute type contains a two-letter
   ISO 3166 [ISO3166] country code.
   (Source: X.520 [X.520])

      ( 2.5.4.6 NAME 'c'
         SUP name
         SYNTAX 1.3.6.1.4.1.1466.115.121.1.11
         SINGLE-VALUE )

   1.3.6.1.4.1.1466.115.121.1.11 refers to the Country String syntax
   [RFC4517].

   Examples: "DE", "AU" and "FR".
</pre>
<p>Note that they have added a SYNTAX directive, which means there is no escape any more. Apparently, later versions of OpenLDAP are using a core.schema that follows <a href="http://www.ietf.org/rfc/rfc4519.txt">RFC4519</a>. This is good, I guess. I just wish someone would have told me about it...</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/11/01/the-country-that-nearly-drove-me-crazy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>17</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>1</slash:comments>
		</item>
	</channel>
</rss>

