<?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; Java</title>
	<atom:link href="http://blog.jayway.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +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>Builder pattern with a twist</title>
		<link>http://blog.jayway.com/2012/02/07/builder-pattern-with-a-twist/</link>
		<comments>http://blog.jayway.com/2012/02/07/builder-pattern-with-a-twist/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 10:49:05 +0000</pubDate>
		<dc:creator>Uzi Landsmann</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[builder]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11940</guid>
		<description><![CDATA[The builder pattern is great, isn't it? It lets you create nice immutable classes without the need for multiple constructors and it gives the API users freedom in choosing which arguments they want to use when creating the instance. But what happens when you want to tell the user that she must call one builder [...]]]></description>
			<content:encoded><![CDATA[<p>The builder pattern is great, isn't it? It lets you create nice immutable classes without the need for multiple constructors and it gives the API users freedom in choosing which arguments they want to use when creating the instance. But what happens when you want to tell the user that she must call one builder method or the other, since it is crucial for the class you're trying to build? The builder pattern simply doesn't have such a feature. This post will try to give an alternative solution to this problem.</p>
<p><span id="more-11940"></span></p>
<p>But lets take it from the beginning.</p>
<h2>Part 1: Why builder pattern?</h2>
<p>Suppose you want to create a class name Address. And suppose you want it to have fields like protocol, url, port, path and description. Now, you want to give your users the freedom to choose which arguments to pass when creating an instance of the class. Also, you want to make your class immutable, so set methods are out of the question. You might start up with something like:</p>
<pre class="brush:java">public class Address {
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    public Address(String url, int port) {}
    public Address(String protocol, String url, int port) {}
    public Address(String protocol, String url, int port, String path) {}
    public Address(String protocol, String url, int port, String path,
        String description) {}
}</pre>
<p>...but you start realizing there is a problem here. First, maybe you need more combinations, like creating an instance given an url, a port and a path, but - both url and path are Strings, and you already have a constructor which takes two String and an int, and, hey, you know you can't have two constructors with the same signature! Secondly, you realize there's simply too many constructors here, and it reminds you of something you read once in a <a href="http://industriallogic.com/xp/refactoring/">book</a> about code smells. The book suggests solving this by <a href="http://industriallogic.com/xp/refactoring/constructorCreation.html">replacing constructors with creation methods</a>. Using this tip, your class might look like this:</p>
<pre class="brush:java">public class Address {
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    // no one should use this outside your class
    private Address() {} 

    public Address createAddressWithProtocolUrlAndPort(
        String protocol, String url, int port) {}
    public Address createAddressWithProtocolUrlPortAndPath(
        String protocol, String url, int port, String path) {}
    public Address createAddressWithUrlPortAndPath(
        String url, String path) {}
}</pre>
<p>...but this is also tedious. There's simply too many combinations. And you need to create an endlessly amount of factory methods to allow all of them. It is then that it strikes you! Why didn't you consider using the builder pattern! This way, you don't have to create loads of constructors or creation methods, and still allow the user to create an immutable instance of your class while freely choosing which arguments to use. Your beautiful new class now looks like that:</p>
<pre class="brush:java">public class Address {
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    // only builder should be able to create an instance
    private Address(Builder builder) {
        this.protocol = builder.protocol;
        this.url = builder.url;
        this.port = builder.port;
        this.path = builder.path;
        this.description = builder.description;
    }

    public static class Builder {
        private String protocol;
        private String url;
        private int port;
        private String path;
        private String description;

        public Builder protocol(String protocol) {
            this.protocol = protocol;
            return this;
        }

        public Builder url(String url) {
            this.url = url;
            return this;
        }

        public Builder port(int port) {
            this.port = port;
            return this;
        }

        public Builder path(String path) {
            this.path = path;
            return this;
        }

        public Builder description(String description) {
            this.description = description;
            return this;
        }

        public Address build() {
            return new Address(this);
        }
    }
    // TODO: add some get methods here...
}</pre>
<p>...and you can create a new instance of Address by calling:</p>
<pre class="brush:java">Address address = new Builder().url("www.google.com").port(80).build();</pre>
<p>Happy? Very. But there's just one tiny problem. What happens if the user of this class tries to create an Address without an url or a port? You simply cant allow that now, can you? So you start thinking. And you realize you simply cannot find a good solution. So you ask a <a href="http://stackoverflow.com/questions/9126276/how-to-mark-a-method-obligatory">question</a> in Stackoverflow and hope someone would give you a good solution. Most of the answers you get there don't help at all, but after a while, someone called <a href="http://stackoverflow.com/users/12719/pgras">pgras</a> gives you this fantastic solution, and, well, you like it so much you decide to write a <a href="http://blog.jayway.com/2012/02/07/builder-pattern-with-a-twist">blog post</a> about it <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>&nbsp;</p>
<h2>Part 2: Mandatory methods in builder pattern</h2>
<p>The solution is to change you builder into a state machine. Each mandatory method in it leads you to the next step, until you get to the last step which includes both non-mandatory methods and the build method itself. It uses interfaces to define the different steps, and, well, it look like that:</p>
<pre class="brush:java">public class Address {
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    // only builder should be able to create an instance
    private Address(Builder builder) {
        this.protocol = builder.protocol;
        this.url = builder.url;
        this.port = builder.port;
        this.path = builder.path;
        this.description = builder.description;
    }

    public static Url builder() {
        return new Builder();
    }

    public static class Builder implements Url, Port, Build{
        private String protocol;
        private String url;
        private int port;
        private String path;
        private String description;

        /** Mandatory, must be followed by {@link Port#port(int)}  */
        public Port url(String url) {
            this.url = url;
            return this;
        }

        /** Mandatory, must be followed by methods in {@link Build}  */
        public Build port(int port) {
            this.port = port;
            return this;
        }

        /** Non-mandatory, must be followed by methods in {@link Build}  */
        public Build protocol(String protocol) {
            this.protocol = protocol;
            return this;
        }

        /** Non-mandatory, must be followed by methods in {@link Build}  */
        public Build path(String path) {
            this.path = path;
            return this;
        }

        /** Non-mandatory, must be followed by methods in {@link Build}  */
        public Build description(String description) {
            this.description = description;
            return this;
        }

        /** Creates an instance of {@link Address} */
        public Address build() {
            return new Address(this);
        }
    }

    interface Url {
        public Port url(String url);
    }

    interface Port {
        public Build port(int port);
    }

    interface Build {
        public Build protocol(String protocol);
        public Build path(String path);
        public Build description(String description);
        public Address build();
    }

    // TODO: add some get methods here...
}</pre>
<p>Using it is simple:</p>
<pre class="brush:java">Address address = Address.builder().url("www.google.com").port(80).build();</pre>
<p>Try using it without the mandatory methods, and you get a compilation error:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/cannot_resolve1.png" rel="lightbox"><img class="alignnone size-full wp-image-11952" title="cannot_resolve" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/cannot_resolve1.png" alt="" width="528" height="53" /></a></p>
<p>Autocomplete is also helpful here, and will only give you the correct options:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/autocomplete.png" rel="lightbox"><img class="wp-image-11953 alignleft" title="autocomplete" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/autocomplete.png" alt="" width="800" height="215" /></a></p>
<p>&nbsp;</p>
<p>So there you have it. The API user can now use your friendly API to create a robust and immutable class knowing that she'll get all the help needed along the way, using autocomplete and compilation errors if she did something she wasn't suppose to do. Nothing here can go wrong!</p>
<p>Thanks again, <a href="http://stackoverflow.com/">Stackoverflow</a> and  <a href="http://stackoverflow.com/users/12719/pgras">pgras</a> for this nice solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/02/07/builder-pattern-with-a-twist/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Changing an index in MongoDB</title>
		<link>http://blog.jayway.com/2011/12/15/changing-an-index-in-mongodb/</link>
		<comments>http://blog.jayway.com/2011/12/15/changing-an-index-in-mongodb/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 08:27:51 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[morphia]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11589</guid>
		<description><![CDATA[We are using the @Indexed annotation in Morphia and when we changed to @Indexed(unique=true) we were first surprised when nothing happened. Our first thought was that this might be a problem in Morphia. However, on second thought automatically changing an existing index is probably not a good idea! Although I couldn't find anything in the [...]]]></description>
			<content:encoded><![CDATA[<p>We are using the @Indexed annotation in <a href="http://code.google.com/p/morphia/">Morphia</a> and when we changed to @Indexed(unique=true) we were first surprised when nothing happened. Our first thought was that this might be a problem in Morphia. However, on second thought automatically changing an existing index is probably not a good idea! Although I couldn't find anything in the <a href="http://www.mongodb.org/display/DOCS/Indexes">documentation</a>, <a href="http://www.mongodb.org/">MongoDB</a> will not change the index if it already exists. </p>
<p>Have a look at the following to see what happens:</p>
<p><code><br />
> db.Person.save({"name" : "foo" })<br />
> db.Person.ensureIndex({"name":1})<br />
> db.Person.getIndexes()<br />
[<br />
	{<br />
		"v" : 1,<br />
		"key" : {<br />
			"_id" : 1<br />
		},<br />
		"ns" : "test.Person",<br />
		"name" : "_id_"<br />
	},<br />
	{<br />
		"v" : 1,<br />
		"key" : {<br />
			"name" : 1<br />
		},<br />
		"ns" : "test.Person",<br />
		"name" : "name_1"<br />
	}<br />
]<br />
> db.Person.save({"name" : "foo" })<br />
> db.Person.find()<br />
{ "_id" : ObjectId("4ee9ab58e57f00e1f3ca95c7"), "name" : "foo" }<br />
{ "_id" : ObjectId("4ee9ab63e57f00e1f3ca95c9"), "name" : "foo" }<br />
> db.Person.ensureIndex({"name":1},{"unique":true, "dropDups":true})<br />
> db.Person.find()<br />
{ "_id" : ObjectId("4ee9ab58e57f00e1f3ca95c7"), "name" : "foo" }<br />
{ "_id" : ObjectId("4ee9ab63e57f00e1f3ca95c9"), "name" : "foo" }<br />
> db.Person.getIndexes()<br />
[<br />
	{<br />
		"v" : 1,<br />
		"key" : {<br />
			"_id" : 1<br />
		},<br />
		"ns" : "test.Person",<br />
		"name" : "_id_"<br />
	},<br />
	{<br />
		"v" : 1,<br />
		"key" : {<br />
			"name" : 1<br />
		},<br />
		"ns" : "test.Person",<br />
		"name" : "name_1"<br />
	}<br />
]<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/15/changing-an-index-in-mongodb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Integration Tests, Part II, Using Mock Objects</title>
		<link>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/</link>
		<comments>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 20:17:27 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10532</guid>
		<description><![CDATA[In the previous post, I wrote how you can use Spring's FactoryBean to facilitate the creation of mock objects for Spring integration tests. Now, it is time to use the EasyMockFactoryBean (in this post EasyMock has been used for creating mock objects, but a similar approach applies to Mockito as well. Start by looking at [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous post, I wrote how you can use Spring's <code>FactoryBean</code> to facilitate the <a href="http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/">creation of mock objects</a> for Spring integration tests. Now, it is time to use the <a href="https://gist.github.com/1397610#file_easy_mock_factory_bean.java">EasyMockFactoryBean</a> <small>(in this post <a href="http://www.easymock.org">EasyMock</a> has been used for creating mock objects, but a similar approach applies to <a href="http://www.mockito.org">Mockito</a> as well. Start by looking at the <a href="https://gist.github.com/1397610#file_mockito_factory_bean.java">MockitoFactoryBean</a>)</small>.</p>
<p>Next, imagine that the <code>Facade</code> class and the <code>Delegate</code> interface below are part of a bigger system: </p>
<p><script src="https://gist.github.com/1427987.js?file=Facade.java"></script><br />
<script src="https://gist.github.com/1427987.js?file=Delegate.java"></script></p>
<p>Create a matching <a href="https://gist.github.com/1427987#file_easymock_test_config.xml">easymock-test-config.xml</a> <small>(or <a href="https://gist.github.com/1427987#file_movkito_test_config.xml">mockito-test-config.xml</a>)</small>.</p>
<p>Now, we have all the bits and pieces that are needed to start writing the integration test. We start simple to make sure that we autowiring and Spring context has been configured correctly:<br />
<script src="https://gist.github.com/1427987.js?file=InitialTest.java"></script></p>
<p>The test is executed and it passes without any problem.</p>
<p>A second test is added to the same file with some added mock behavior:<br />
<script src="https://gist.github.com/1427987.js?file=SecondTest.java"></script></p>
<p>Excellent, that test also passes.</p>
<p>Now that we have warmed up, we add a third test to the test class:<br />
<script src="https://gist.github.com/1427987.js?file=ThirdTest.java"></script><br />
As expected, this test also passes without any problem.</p>
<p>Unfortunately, that is not always true. A closer investigation reveals that all tests pass when they are executed <i>individually</i>. When executing all three tests (either from the IDE or from a build tool like Maven), the third test <i>fails</i> unexpectedly:</p>
<pre>
java.lang.AssertionError:
  Unexpected method call Delegate.doSomethingElse():
        at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
	at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:85)
	at $Proxy8.doSomethingElse(Unknown Source)
        [...]
</pre>
<p>This is EasyMock telling us that the mock object is in the wrong state. An EasyMock mock object goes through a series of steps:</p>
<ol>
<li><i>Initialization</i> - Instantiate the mock object.</li>
<li><i>Record</i> - Record the expectations of the mock object.</li>
<li><i>Replay</i> - Call <code>replay()</code> on the mock object so that it can replay the recorded state.</li>
<li><i>Test</i> - Execute the test assertions.</li>
<li><i>Verify</i> - Call <code>verify()</code> on the mock object to certify that the recorded mock expectations are fulfilled.</li>
</ol>
<p>In an ordinary unit test, the mock object is thrown away after the <i>verify</i> phase, a new mock instance is created before the next test that can be used to <i>record</i> the new behavior. However, since we are creating a Spring integration test, there is one more thing to consider.</p>
<h2>Reused beans</h2>
<p>In the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testing-ctx-management">testing chapter</a> of the Spring manual it is stated that:</p>
<blockquote><p>By default, once loaded, the configured ApplicationContext and all of its beans are reused for each test method. Thus the setup cost is incurred only once (per test fixture), and subsequent test execution is much faster.</p></blockquote>
<p>Consequently, all Spring beans, including mocked beans, will preserve their state between different test methods. The mock object will be in the <i>verify</i> state when the last test begins and not in the <i>record</i> state when <code>delegateMock.doSomethingElse()</code> is called. To solve the problem, we need some mechanism to ensure that the mock object is in a known, well-defined state before each test.</p>
<h2>Reset mocks</h2>
<p>Both EasyMock and Mockito provide methods to <code>reset()</code> the state of the mocked objects. Normally, resetting mock objects in the middle of a test method is considered to be a <a href="http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#17">potential code smell</a>, because it is likely that you are testing too much and that the test could be refactored into two separate tests accordingly. Nonetheless, resetting the mock instance <a href="http://junit.sourceforge.net/javadoc/org/junit/Before.html">@Before</a> each test allow us to keep the same mock instance through the entire lifetime of the test class and yet put it in the <i>record</i> state when before each test starts:</p>
<p><script src="https://gist.github.com/1427987.js?file=SetUp.java"></script></p>
<p>When executing all tests in the test class, we see that that the problem has been solved and all tests pass.<br />
For reference, click the link for the full source code of the <a href="https://gist.github.com/1427987#file_easy_mock_facade_test.java">EasyMock test class</a> <small>(and the <a href="https://gist.github.com/1427987#file_mockito_facade_test.java">Mockito test class</a>)</small>.</p>
<h2>Comments</h2>
<p>You may choose to reset the mocks <a href="http://junit.sourceforge.net/javadoc/org/junit/After.html">@After</a> each test, the result will be the same.</p>
<p>The <code>reset()</code> method is called <i>between</i> the different test methods (because of the nature of <code>@After</code> and <code>@Before</code>), so the code smell of calling reset <i>within</i> a test is avoided.</p>
<p>Tests written using Mockito mocks are generally more tolerant for this kind of problem. In contrast to EasyMock, Mockito has no <code>replay()</code> method and no notion of steps. Therefore, it is possible to add additional mock expectations and to replace existing expectations, both after the test has been executed as well as after the result has been verified. Hence, you should always reset your mock objects before each test so that you do not get any accidental mocking behavior.</p>
<p>As a side note, another solution would be to annotate the test class (or all of its test methods) with the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/annotation/DirtiesContext.html">@DirtiesContext</a> annotation. This will effectively recreate the entire application context after each test has been executed, causing all Spring beans to be in their initial state and thus the mock beans to be in the <i>record</i> state. Although this will work, there will be a significant performance penalty compared to the suggested <code>reset()</code> and <code>@Before</code> / <code>@After</code> solution, because all beans in the application context will be recreated and re-wired before each test method. </p>
<h2>Dependencies</h2>
<ul>
<li>Spring 3.0.6</li>
<li>Mockito 1.8.5</li>
<li>jUnit 4.10</li>
<li>EasyMock 3.1</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testing-ctx-management">Spring Reference Manual - Test Context Management and Caching</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testcontext-junit4-runner">Spring Reference Manual - SpringJunit4ClassRunner</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#integration-testing-annotations">Spring Reference Manual - ContextConfiguration</a></li>
<li><a href="http://easymock.org/EasyMock3_1_Documentation.html">EasyMock</a></li>
<li><a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html">Mockito</a></li>
</ul>
<p>Previous post: <a href="http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/">Spring Integration Tests, Part I, Creating Mock Objects</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Autowiring Morphia entities</title>
		<link>http://blog.jayway.com/2011/12/07/autowiring-morphia-entities/</link>
		<comments>http://blog.jayway.com/2011/12/07/autowiring-morphia-entities/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 15:02:11 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[morphia]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11364</guid>
		<description><![CDATA[My current project is using Morphia to handle object mapping to/from mongoDB and I wanted to add dependency injection using Spring to my entities like this: @Entity public class MyEntity { ... @Autowired @Transient private SomeService someService; } Notice the @Transient annotation that tells Morphia to avoid persisting this field! I solved this problem by [...]]]></description>
			<content:encoded><![CDATA[<p>My current project is using <a href="http://code.google.com/p/morphia/">Morphia</a> to handle object mapping to/from <a href="http://www.mongodb.org/">mongoDB</a> and I wanted to add dependency injection using <a href="http://www.springsource.org/spring-core">Spring</a> to my entities like this:</p>
<pre class="brush:java">
@Entity
public class MyEntity {
...
    @Autowired @Transient
    private SomeService someService;

}
</pre>
<p>Notice the @Transient annotation that tells Morphia to avoid persisting this field! I solved this problem by adding an EntityInterceptor that autowires all entities:</p>
<pre class="brush:java">
public class SpringAutowiringEntityInterceptor extends AbstractEntityInterceptor {
	@Autowired
	private ApplicationContext applicationContext;

    @Autowired
    private Morphia morphia;

	@PostConstruct
	public void postConstruct() {
		morphia.getMapper().addInterceptor(this);
	}

	@Override
	public void preLoad(Object ent, DBObject dbObj, Mapper mapr) {
		applicationContext.getAutowireCapableBeanFactory().autowireBean(ent);
	}
}
</pre>
<p>Here is the complete source code <a href="https://gist.github.com/1443114">SpringAutowiringEntityInterceptor.java</a>. Let me know what you think!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/07/autowiring-morphia-entities/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Integration Tests, Part I, Creating Mock Objects</title>
		<link>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/</link>
		<comments>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 20:26:05 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[factory-method]]></category>
		<category><![CDATA[factorybean]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10514</guid>
		<description><![CDATA[When writing integration tests with Spring, it can sometimes be convenient to mock one or more of Spring bean dependencies. However, during some circumstances strange things may happen... (In this post, Mockito has been used for creating mock objects, but the same problem applies to EasyMock as well. You can find the corresponding files if [...]]]></description>
			<content:encoded><![CDATA[<p>When writing integration tests with Spring, it can sometimes be convenient to mock one or more of Spring bean dependencies. However, during some circumstances strange things may happen...</p>
<p><small>(In this post, <a href="http://www.mockito.org">Mockito</a> has been used for creating mock objects, but the same problem applies to <a href="http://www.easymock.org">EasyMock</a> as well. You can find the corresponding files if you follow the provided links.)</small></p>
<h2>Test setup</h2>
<p>In the following example the <code>SomeClass</code> needs a reference to an instance of the <code>SomeDependency</code> interface:</p>
<p><script src="https://gist.github.com/1397610.js?file=SomeClass.java"></script></p>
<p><script src="https://gist.github.com/1397610.js?file=SomeDependency.java"></script></p>
<p>When writing the integration test, we use the static  <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class classToMock)</a> method to create a mock instance. The straightforward approach would be to let Spring instantiate the mock object with a <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-class-static-factory-method">static factory method</a> in the xml configuration, e.g.</p>
<p><script src="https://gist.github.com/1397610.js?file=failing-mockito-config.xml"></script><br />
<small>(Corresponding <a href="https://gist.github.com/1397610#file_failing_easymock_config.xml">EasyMock config</a>.)</small></p>
<p>To verify that the beans are created and wired correctly, we write a simple test:</p>
<p><script src="https://gist.github.com/1397610.js?file=BeanWiringTest.java"></script><br />
<small>(Same test for EasyMock, just update the <code>@ContextConfiguration</code> with the EasyMock config file.)</code></small></p>
<p>To our surprise, the test fails:</p>
<pre>
[...]
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'someClass': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private com.jayway.example.SomeDependency com.jayway.example.SomeClass.someDependency;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
    No matching bean of type [com.jayway.example.SomeDependency] found for dependency:
    expected at least 1 bean which qualifies as autowire candidate for this dependency.
    Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
[...]
</pre>
<h2>Explanation</h2>
<p>In order to find a solution to the problem, we need to understand Spring's initialization process:</p>
<ol>
<li>
<i>Load bean definitions.</i><br />
This step includes scanning the application context XML files, scanning packages defined by <code>component-scan</code>, and loading the bean definitions found into the bean factory. (BeanFactoryPostProcessors such as the PropertyPlaceHolderConfigurer may be called to update the bean definitions.)
</li>
<li>
<i>Instantiate beans and store them in the application context.</i><br />
The bean factory creates the bean from the bean definitions. Bean dependencies get injected.
</li>
<li>
<i>Bean post processing.</i><br />
All initializing methods (e.g. annotated with <code>@PostConstruct</code>, <code>init-method</code>s declared in the XML and the <code>afterPropertiesSet()</code> method will execute. Annotations such as <code>@Required</code> will be validated. Dynamic proxies in an AOP environment will be created and so on.
</li>
</ol>
<p>The problem that we see occurs due to a corner case in the first two steps. When the bean definition is created Spring scans through the application context XML file. It finds the declaration of the mock bean and a reflective call is made to find out the return type of the method defined by the <code>factory-method</code> declaration in an attempt to determine the bean's type. The return type of this method is declared as the formal type parameter <code>&lt;T&gt;</code> (remember that we use the <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class&lt;T&gt; classToMock)</a> as factory method). Consequently, the bean definition of <code>someDependencyMock</code> will be of <code>java.lang.Object</code> and not <code>SomeDependency</code> as one would think.</p>
<p>In the second step, the <code>someClass</code> bean is instantiated. Springs discovers the <code>@Autowired</code> annotation and tries to fetch an existing <code>SomeDependency</code> bean from the application context. None has yet been created, so the bean factory proceeds and looks for suitable bean definition in order to create an instance of the requested bean on the fly. This operation fails because the bean definition of <code>someDependency</code> is mapped to <code>java.lang.Object</code>. At this point, Spring bails out and throws the <code>NoSuchBeanDefinitionException</code>.  </p>
<h2>FactoryBean to the rescue</h2>
<p>The problem is solved by implementing a custom <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean">FactoryBean</a> that can be used whenever we need to mock an object:</p>
<p><script src="https://gist.github.com/1397610.js?file=MockitoFactoryBean.java"></script><br />
<small>(In the <a href="https://gist.github.com/1397610#file_easy_mock_factory_bean.java">EasyMockFactoryBean</a>, I have added an enum to define the type of mock object.)</small></p>
<p>Next, the Spring test config is updated to use the factory bean:</p>
<p><script src="https://gist.github.com/1397610.js?file=mockito-factory-bean.xml"></script><br />
<small>(Corresponding <a href="https://gist.github.com/1397610#file_easymock_factory_bean.xml">EasyMock config</a>.)</small></p>
<p>Spring will still instantiate the beans in the order that they were declared in the <code>mockito-test-config.xml</code>, i.e. starting by creating an instance of <code>SomeClass</code> and then attempt to inject an instance of a <code>SomeDependency</code> into it before any has been created. The good news is that bean factory will scan through all declared <code>FactoryBean</code>s, calls its <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/FactoryBean.html#getObjectType()">getObjectType()</a> method, and if the returned type is correct, call its <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/FactoryBean.html#getObject()">getObject()</a> which should return an instance of the requested type.</p>
<h2>Alternative solution</h2>
<p>There is another more brittle solution to the problem. By simply changing the order of the tags in the initial application context, e.g. putting the bean declaration that defines the mock above the component scan, will cause the test to pass. The bean definition will still be wrong in the sense that the <code>someDependencyMock</code> will be defined as a <code>java.lang.Object</code>, but there is another important difference. In this case, the bean factory will invoke the <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class&lt;T&gt; classToMock)</a> method with <code>SomeDependency</code> as parameter causing the <code>someDependencyMock</code> bean to be created and subsequently stored in the application context. Later, the <code>someClass</code> bean is created and the dependency can obtained from the application context when requested by the bean factory and the wiring of the beans will succeed. However, making sure that the order of the bean declarations in the XML is always correct may neither be simple nor obvious, and it will get increasingly more difficult the more beans you add to the configuration.</p>
<h2>Disclaimer</h2>
<p>As stated in the in the first paragraph, I would only consider this solution for <i>integration</i> tests because of performance reasons. The application context itself adds some overhead, but the big performance hit is to create and wire all beans that are associated with it. When writing <i>unit</i> tests there is no need for this, so you could revert to constructor or setter dependency injection, Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html#setField%28java.lang.Object,%20java.lang.String,%20java.lang.Object%29">ReflectionTestUtils.setField()</a>, PowerMock's <a href="http://powermock.googlecode.com/svn/docs/powermock-1.4.10/apidocs/org/powermock/reflect/Whitebox.html#setInternalState%28java.lang.Object,%20java.lang.Class,%20java.lang.Object%29">Whitebox.setInternalState()</a>, Mockito's <a href="http://docs.mockito.googlecode.com/hg/org/mockito/InjectMocks.html">@InjectMocks</a> or similar techniques.</p>
<h2>Acknowledgements</h2>
<p>Thanks to <a href="http://stackoverflow.com/users/97641/wilhelm-kleu">Wilhelm Kleu</a> at stack overflow for <a href="http://stackoverflow.com/questions/6340007/autowiring-of-beans-generated-by-easymock-factory-method/6340391#6340391">suggesting</a> the solution and to <a href="http://blog.jayway.com/author/mattiasarthursson/">Mattias Hellborg Arthursson</a> for valuable discussions.</p>
<h2>Dependencies</h2>
<ul>
<li>Spring 3.0.6</li>
<li>Mockito 1.8.5</li>
<li>jUnit 4.10</li>
<li>EasyMock 3.1</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-class-static-factory-method">Spring Reference Manual - Static Factory Method</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean">Spring Reference Manual - FactoryBean</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#integration-testing-annotations">Spring Reference Manual - Integration Testing</a></li>
<li><a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html">Mockito</a></li>
<li><a href="http://easymock.org/EasyMock3_1_Documentation.html">EasyMock</a></li>
</ul>
<p>Next post: <a href="http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/">Spring Integration Tests, Part II, Using Mock Objects</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started with Spring Data &#8211; MongoDB in Scala</title>
		<link>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/</link>
		<comments>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 15:11:14 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[spring data]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10621</guid>
		<description><![CDATA[I used MongoDB for a project in 2010 and I had great experience with it. Unfortunately I didn't get the chance to work with this agile and scalable document-oriented database again until now. But my current assignment has brought the opportunity to use it in production In this post I want to show you a [...]]]></description>
			<content:encoded><![CDATA[<p>I used <a title="MongoDB" href="http://www.mongodb.org/">MongoDB</a> for a project in 2010 and I had great experience with it. Unfortunately I didn't get the chance to work with this agile and scalable document-oriented database again until now. But my current assignment has brought the opportunity to use it in production <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In this post I want to show you a step by step guide on how you can start your Scala project with <a title="Spring Data" href="http://www.springsource.org/spring-data/mongodb">Spring Data</a> for MongoDB.</p>
<p>You should have <a title="SBT" href="https://github.com/harrah/xsbt">SBT</a> 0.11 installed on your system since I am going to use it as the building tool through out this post.</p>
<h3>1. Creating Project</h3>
<p>Create the project like below:</p>
<pre>$ mkdir springDataMongo
$ cd springDataMongo/
$ sbt
[info] Loading global plugins from /home/amir/.sbt/plugins
[info] Set current project to default-71a5a0 (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set name := "SpringMongo"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set version := "1.0"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set scalaVersion := "2.9.1"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; session save
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)</pre>
<p>Open file build.sbt and add the dependencies:</p>
<p><script src="https://gist.github.com/1309234.js?file=build.sbt"></script></p>
<p>Save the file and run the following in SBT console:</p>
<pre>&gt; reload
[info] Loading global plugins from /home/amir/.sbt/plugins
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; update
[info] Updating {file:/data/3-Projects/scala-projects/springDataMongo/}default-71a5a0...
[info] Done updating.</pre>
<p>And generate the IDE related files. I am using IntelliJ:</p>
<pre>&gt; gen-idea</pre>
<p>or if you use Eclipse:</p>
<pre>&gt; eclipse create-src</pre>
<p>Now you have configured your project and you can start coding!</p>
<h3>2. Configuring Spring</h3>
<p>There are two ways to configure Spring Data for MongoDB: Annotations and XML. I explain annotations here. You have to extend <span style="text-decoration: underline;">AbstractMongoConfiguration</span> class as follows to define your database settings:</p>
<p><script src="https://gist.github.com/1309234.js?file=MongoConfig.scala"></script></p>
<p>As you see there are two methods to implement. <span style="text-decoration: underline;">mongo</span> method should return an instance of Mongo class. If you are using a mongo instance in a network, you should then specify the address and possibly port (if not the default).</p>
<h3>3. Data Model</h3>
<p>Consider we have the following class for keeping accounts in a system. This class will be mapped to a mongo document by Spring:</p>
<p><script src="https://gist.github.com/1309234.js?file=Account.scala"></script></p>
<h3>4. Interacting with MongoDB</h3>
<p>Now let's write a simple program to interact with MongoDB:</p>
<p><script src="https://gist.github.com/1309234.js?file=App.scala"></script></p>
<p><span style="text-decoration: underline;">mongoTemplate</span> is an implementation of <span style="text-decoration: underline;">MongoOperation</span> interface. With <span style="text-decoration: underline;">MongoOperation</span> you can do all CRUD operations. E.g. inserting/saving a document:</p>
<p><script src="https://gist.github.com/1309234.js?file=SaveAccount.scala"></script></p>
<p>"accounts" is the name of collection. Or if you want to query:</p>
<p><script src="https://gist.github.com/1309234.js?file=Query.scala"></script></p>
<p>Note that <span style="text-decoration: underline;">JavaConversions</span> is required here since the result of <span style="text-decoration: underline;">find</span> is a <span style="text-decoration: underline;">java.util.List[Account]</span> and we need to convert it to Scala list.</p>
<p>Please refer to <a title="documentation" href="http://www.springsource.org/spring-data/mongodb#documentation">documentation</a> of Spring Data for MongoDB for more info about what you can do more <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Facebook Test Java API release 1.1.5</title>
		<link>http://blog.jayway.com/2011/10/20/facebook-test-java-api-release-1-1-5/</link>
		<comments>http://blog.jayway.com/2011/10/20/facebook-test-java-api-release-1-1-5/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 12:23:38 +0000</pubDate>
		<dc:creator>Tobias Södergren</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10597</guid>
		<description><![CDATA[The Facebook Test Java API framework has been updated. There are two additions to the API and one bugfix: Bugfix for NPE when calling facebookStore.createTestUser(false,"..."). Added possibility of using a provided HttpClient instance in HttpClientFacebookTestUserStore. Added unit test that displays the use of json-path when asserting data. Here's a quick reminder of how to create [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://code.google.com/p/facebook-test-java-api/" title="Facebook Test Java API">Facebook Test Java API</a> framework has been updated. There are two additions to the API and one bugfix:</p>
<ol>
<li>Bugfix for NPE when calling facebookStore.createTestUser(false,"...").</li>
<li>Added possibility of using a provided HttpClient instance in HttpClientFacebookTestUserStore.</li>
<li>Added unit test that displays the use of json-path when asserting data.</li>
</ol>
<p>Here's a quick reminder of how to create test users for an application. The creation process is handled by an instance of FacebookTestUserStore, e.g. The HttpClientFacebookTestUserStore which uses Apache HttpClient as communication method. The class needs the <i>application ID</i> and the <i>application secret</i> for the application in order to be able to create the users and this is specified in the constructor:</p>
<pre class="brush:java">
FacebookTestUserStore facebookStore = new HttpClientFacebookTestUserStore("&lt;appId&gt;", "&lt;appSecret&gt;"));
</pre>
<p>Now you have a choice when creating a test user: You may say that the test user should accept the privileges that you specify for it, which is done by:</p>
<pre class="brush:java">
FacebookTestUserAccount aTestUser = facebookStore.createTestUser(true, "read_stream");
</pre>
<p>If you want to give a choice to the test user whether the privileges should be accepted or not, you do the following:</p>
<pre class="brush:java">
FacebookTestUserAccount aTestUser = facebookStore.createTestUser(false, "read_stream");
</pre>
<p>The accept/decline choice takes part in the web browser, hence you need the login URL for the test user to access the page. This URL is accessible from the FacebookTestUserAccount:</p>
<pre class="brush:java">
aTestUser.loginUrl();
</pre>
<h3>Specifying a HttpClient instance to HttpClientFacebookTestUserStore</h3>
<p>There might be occasions where you need a special HttpClient instance for communication, for example one instance with proxy settings configures, or another instance where you have stubbed all the communication that takes place. To provide the instance to HttpClientFacebookTestUserStore, just specify it in the constructor:</p>
<pre class="brush:java">
HttpClient httpClient = new DefaultHttpClient();
FacebookTestUserStore facebookStore = new HttpClientFacebookTestUserStore("&lt;appId&gt;", "&lt;appSecret&gt;", httpClient));
</pre>
<h3>Using json-assert to verify application behavior</h3>
<p>The <a href="http://code.google.com/p/json-assert/" title="json-assert">json-assert</a> project, which uses <a href="http://code.google.com/p/json-path/" title="json-path">json-path</a> can be used to make life a little less verbose when asserting on data from the JSON document representations of the Facebook data streams that are available in the FacebookTestUserAccount. For example, the user details of a test user can be accessed like this:</p>
<pre class="brush:java">
aTestUser.getUserDetails();
</pre>
<p>The result is a java.lang.String containing a JSON Document. To make it easier to assert that the user details actually contain the expected data, you may use json-assert and <a href="http://code.google.com/p/hamcrest/wiki/Tutorial" title="Hamcrest matchers">Hamcrest matchers</a>:</p>
<pre class="brush:java">
String userDetails = account.getUserDetails();

JsonAssert.with(userDetails).assertThat("$.first_name", equalTo("Sue"));
JsonAssert.with(userDetails).assertThat("$.last_name", equalTo("Ellen"));
</pre>
<p>Feel free to test it out, the code is open source an can be found on Maven central or on the<br />
<a href="http://code.google.com/p/facebook-test-java-api/" title="Facebook Test Java API project page">Facebook Test Java API project page</a>.</p>
<p>/Tobias</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/20/facebook-test-java-api-release-1-1-5/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Experimenting with Scala Parallel Collections (contd.)</title>
		<link>http://blog.jayway.com/2011/10/18/experimenting-with-scala-parallel-collections-contd/</link>
		<comments>http://blog.jayway.com/2011/10/18/experimenting-with-scala-parallel-collections-contd/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 12:35:01 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10535</guid>
		<description><![CDATA[In the previous post we went through Scala parallel collections and you saw how you can convert a sequential collection into a parallel one by using method par on that collection. In this post I want to show you how you can write your own parallel collection in Scala. The example I use for this [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous <a title="post" href="http://blog.jayway.com/2011/10/02/experimenting-with-scala-parallel-collections/">post</a> we went through Scala parallel collections and you saw how you can convert a sequential collection into a parallel one by using method <strong>par</strong> on that collection.</p>
<p>In this post I want to show you how you can write your own parallel collection in Scala. The example I use for this post is taken from Alex Prokopec's presentation at Scala eXchange 2011.</p>
<p>Consider we want to have a parallel String in our application. If you convert a String into a parallel collection you get a <span style="text-decoration: underline;">ParArray</span>:</p>
<pre>scala&gt; "I Love Scala".par
res2: scala.collection.parallel.ParSeq[Char] = ParArray(I,  , L, o, v, e,  , S, c, a, l, a)</pre>
<p>This is good enough to take advantage of your multi-core CPU architecture, but for some reason you want to write you own Parallel String collection!</p>
<p>Scala Parallel collection is implemented by a mechanism that is called <em>split-combine</em>. As the name implies a sequential collection can be <em>splitted</em> into sub-collections and each one can be stolen by a thread from a thread pool. Later the results of each sub-collection can be <em>combined</em> to make the final collection. You can find details about this implementation in [1].</p>
<p>In order to start with our Parallel String we need to extend <span style="text-decoration: underline;">scala.collection.parallel.immutable.ParSeq</span> trait. There are 4 abstract methods that we need to implement:</p>
<p><script src="https://gist.github.com/1295051.js?file=ParallelStringV1.scala"></script></p>
<p><span style="text-decoration: underline;">seq</span>, <span style="text-decoration: underline;">length</span> and <span style="text-decoration: underline;">apply</span> have obvious implementations. Method <span style="text-decoration: underline;">splitter</span> returns a new instance of class <span style="text-decoration: underline;">ParallelStringSplitter</span> which we are going to define next. Note that this instance is mixed-in into <span style="text-decoration: underline;">SignalContextPassingIterator</span> which is responsible for passing the signal context along iterators. We define <span style="text-decoration: underline;">ParallelStringSplitter</span> class inside ParallelString class:</p>
<p><script src="https://gist.github.com/1295051.js?file=ParallelStringSplitter.scala"></script></p>
<p>Note that we need to extend <span style="text-decoration: underline;">Splitter</span> trait. There are 6 abstract methods to implement. Method <span style="text-decoration: underline;">dup</span> returns a new instance of <span style="text-decoration: underline;">ParallelStringSplitter</span> with current values. Method <span style="text-decoration: underline;">split</span> splits the iterator into a sequence of disjunct views and method <span style="text-decoration: underline;">psplit</span> splits the splitter into a sequence of disjunct views.</p>
<p>Now we have the splitter. Let's test this parallel String in REPL:</p>
<pre>scala&gt; val pstr = new ParallelString("This is a long string" * 250000)
pstr: ParallelString = ParallelString(T, h, i, s,  , i, s,  , a,  , l, o, n, g,  ...</pre>
<p>If you don't provide a combiner, then the default one is used. Sometimes you want to have control over the combination and you want to take the responsibility for it. Let's write our own combiner to show how you can do that. We need to mix in another trait into the definition of <span style="text-decoration: underline;">ParallelString</span>: <span style="text-decoration: underline;">ParSeqLike</span></p>
<p><script src="https://gist.github.com/1295051.js?file=WithCombiner.scala"></script></p>
<p>In order to specify our own combiner we need to override method <span style="text-decoration: underline;">newCombiner</span>:</p>
<p><script src="https://gist.github.com/1295051.js?file=Combiner.scala"></script></p>
<p>Now we need to define <span style="text-decoration: underline;">ParallelStringCombiner</span> class by extending the <span style="text-decoration: underline;">Combiner</span> trait:</p>
<p><script src="https://gist.github.com/1295051.js?file=ParallelStringCombiner.scala"></script></p>
<p>There are 5 abstract methods that need to be implemented. As the names imply method <span style="text-decoration: underline;">combine</span> combines the content of another builder to the current builder and produces a new builder. Method <span style="text-decoration: underline;">result</span> produces a collection from added elements and <span style="text-decoration: underline;">+=</span> adds a single element to this builder.</p>
<p>To summarize, to build a parallel collection class <span style="text-decoration: underline;">A</span>, one should:</p>
<ul>
<li>extend <span style="text-decoration: underline;">ParSeq</span> trait</li>
<li>implement all abstract methods from <span style="text-decoration: underline;">ParSeq</span> trait</li>
<li>define a splitter class that mixes in with <span style="text-decoration: underline;">Splitter</span> and <span style="text-decoration: underline;">ParIterator</span> traits and put it in class <span style="text-decoration: underline;">A</span></li>
<li>extend <span style="text-decoration: underline;">ParSeqLike</span> trait</li>
<li>define a combiner class that extend <span style="text-decoration: underline;">Combiner</span> trait and implement all abstract methods</li>
<li>override <span style="text-decoration: underline;">newCombiner</span> method in class <span style="text-decoration: underline;">A</span> and return a new instance of defined combiner</li>
</ul>
<p>For the complete code of this example please refer to <a title="Alex Prokopec's Github" href="https://github.com/axel22/sd/blob/master/src/main/scala/scaladays/ParString.scala">Alex Prokopec's Github</a>.</p>
<h3>References</h3>
<p>[1]: Aleksandar Prokopec, Tiark Rompf, Phil Bagwell, Martin Odersky, "A Generic Parallel Collection Framework", Euro-Par 2011</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/18/experimenting-with-scala-parallel-collections-contd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with Android NDK</title>
		<link>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/</link>
		<comments>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 20:15:48 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[ndk]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10385</guid>
		<description><![CDATA[You want to try out the Android NDK? I have gotten a lot of questions about how to setup and work with the NDK and I decided to write down how I do it. My goal with this entry is to gather all the information you need to get started with the Android NDK. I [...]]]></description>
			<content:encoded><![CDATA[<p>You want to try out the Android NDK? I have gotten a lot of questions about how to setup and work with the NDK and I decided to write down how I do it. My goal with this entry is to gather all the information you need to get started with the Android NDK. I will not get into details about installing the basic components but will focus on setting up the environment. So you will need some knowledge about working with Android.</p>
<p>You will need to download and install a couple of things. </p>
<h2>Eclipse</h2>
<p>I usually go with the Eclipse Classic version. It is available from <a href="http://www.eclipse.org/downloads/" title="eclipse.org" target="_blank">eclipse.org</a>. Installing Eclipse is simply just unpacking the downloaded file.</p>
<h2>Android SDK</h2>
<p>The SDK is located at <a href="http://developer.android.com/sdk/index.html" title="developer.android.com" target="_blank">developer.android.com</a> There is a really good installation guide at <a href="http://developer.android.com/sdk/installing.html" title="developer.android.com" target="_blank">developer.android.com</a></p>
<h2>Android NDK</h2>
<p>The NDK is located at <a href="http://developer.android.com/sdk/ndk/index.html" title="developer.android.com" target="_blank">developer.android.com</a> with an installation guide.</p>
<h2>Eclipse C/C++ Development Tools</h2>
<p>To make it a bit easier we also install the C/C++ Development Tools to get C/C++ support in Eclipse. From the 'Help' menu choose 'Install New Software...'<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_00.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_00-300x233.png" alt="" title="cdt_00" width="300" height="233" class="aligncenter size-medium wp-image-10467" /></a></center></p>
<p>From the drop down select the update site for your eclipse version, in my case Indigo.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_01.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_01-283x300.png" alt="" title="cdt_01" width="283" height="300" class="aligncenter size-medium wp-image-10468" /></a></center></p>
<p>Under 'Programming Languages' you will find 'C/C++ Development Tools'. Select it and click 'next' and follow the install instructions.</p>
<p><center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_02b.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_02b-283x300.png" alt="" title="cdt_02b" width="283" height="300" class="aligncenter size-medium wp-image-10509" /></a></center></p>
<h2>Getting started</h2>
<p>I will show you how to get started by making a small application called NDKSetup.</p>
<p>Create a new android project for this example I will call it NDKSetup.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Screen-shot-2011-10-13-at-4.44.09-PM-copy.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Screen-shot-2011-10-13-at-4.44.09-PM-copy-194x300.png" alt="Project Wizard" title="Project Wizard" width="194" height="300" class="size-medium wp-image-10423" /></a></center></p>
<p>First thing we need to do is to create a new folder called 'jni'<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/jni-folder.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/jni-folder.png" alt="" title="jni-folder" width="258" height="266" class="aligncenter size-full wp-image-10431" /></a></center></p>
<p>The next thing we need to do is to setup Eclipse so we can build the JNI code. Click on the small down arrow on the external tool button and choose the 'External Tools Configuration...'.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_00.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_00-300x161.png" alt="" title="etc_00" width="300" height="161" class="aligncenter size-medium wp-image-10433" /></a></center></p>
<p>Mark the 'Program' and click on the 'new'-icon.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_01.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_01-272x300.png" alt="" title="etc_01" width="272" height="300" class="aligncenter size-medium wp-image-10435" /></a></center></p>
<p>Select a proper name.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_02.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_02-272x300.png" alt="" title="etc_02" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>Location is the location of the external tool you want to run, in our case the ndk-build file. Click on 'Browse file system...' and locate the ndk-build file located under your NDK folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_03.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_03-272x300.png" alt="" title="etc_03" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>The working directory is the jni folder we created in our project. Click on 'Browse Workspace...' ...<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04-272x300.png" alt="" title="etc_04" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>... and choose the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04b1.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04b1-228x300.png" alt="" title="etc_04b" width="228" height="300" class="aligncenter size-medium wp-image-10443" /></a></center></p>
<p>You should now have something looking like this:<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_05.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_05-272x300.png" alt="" title="etc_05" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>Press run and you will get this error:</p>
<pre>/Users/uncle/ndk-setup/android-ndk-r6b/build/core/add-application.mk:118: *** Android NDK: Aborting...    .  Stop.
Android NDK: Your APP_BUILD_SCRIPT points to an unknown file: /Users/uncle/Workspaces/ndk-setup/NDKSetup/jni/Android.mk</pre>
<p>This means two things. Your setup to the ndk-build works and you are missing the Android.mk file.</p>
<p>Create a new file called Android.mk in the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/android-mk.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/android-mk.png" alt="" title="android-mk" width="260" height="268" class="aligncenter size-full wp-image-10451" /></a></center></p>
<p>In the Android.mk file write this:</p>
<pre class="c">LOCAL_PATH := $<span style="color: #66cc66;">&#40;</span>call my-dir<span style="color: #66cc66;">&#41;</span>
&nbsp;
include $<span style="color: #66cc66;">&#40;</span>CLEAR_VARS<span style="color: #66cc66;">&#41;</span>
&nbsp;
LOCAL_LDLIBS := -llog
&nbsp;
LOCAL_MODULE    := ndksetup
LOCAL_SRC_FILES := native.<span style="color: #202020;">c</span>
&nbsp;
include $<span style="color: #66cc66;">&#40;</span>BUILD_SHARED_LIBRARY<span style="color: #66cc66;">&#41;</span></pre>
<p>LOCAL_PATH := $(call my-dir)<br />
An Android.mk file must begin defining the LOCAL_PATH variable, this is where the source files are. The macro 'my-dir' is the path where the Android.mk file is located.</p>
<p>include $(CLEAR_VARS)<br />
Since all the building and parsing is done in the same context the variables called LOCAL_XXX is globals and need to be cleared.</p>
<p>LOCAL_MODULE := ndksetup<br />
This is where you set the name used as the identifier for each module. Later used in java when loading the module. The system will add 'lib' before the module name when compiling into the .so file. So ndksetup will become libndksetup.so. The only exception is if you add 'lib' first in your module name then the system will not add it.</p>
<p>LOCAL_SRC_FILES := native.c<br />
Here you add a list of the files you need to compile your module. You do not need to add headers or include files the system will take care of that for you.</p>
<p>include $(BUILD_SHARED_LIBRARY)<br />
The NDK provides you with two make files that parse and build everything accordingly to your Android.mk file. The two once are BUILD_STATIC_LIBRARY for building static library and BUILD_SHARED_LIBRARY for building shared library. </p>
<p>For the example project here we use the BUILD_SHARED_LIBRARY.</p>
<p>If you run the external tool "NDK Build" we get a new error:</p>
<pre>make: *** No rule to make target `/Users/uncle/Workspaces/ndk-setup/NDKSetup/jni/native.c', needed by `/Users/uncle/Workspaces/ndk-setup/NDKSetup/obj/local/armeabi/objs/ndksetup/native.o'.  Stop.</pre>
<p>So lets att the missing native.c file into the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/native-c.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/native-c-221x300.png" alt="" title="native-c" width="221" height="300" class="aligncenter size-medium wp-image-10486" /></a></center></p>
<p>Before we start adding code to the native.c file I think it is easier to write the API starting from java. We start by adding the loading of the library.</p>
<pre java="java">static {
    System.loadLibrary("ndksetup"); // ndksetup is the LOCAL_MODULE string.
}</pre>
<p>We also need to define the function we are going to implement. By adding the keyword 'native' the system will know it is a function located in the native code.</p>
<pre java="java">private native void printLog(String logThis);</pre>
<p>Putting in all together give us this:</p>
<pre java="java">package com.jayway.ndksetup;

import android.app.Activity;
import android.os.Bundle;

public class NDKSetupActivity extends Activity {

    static {
        System.loadLibrary("ndksetup");
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        printLog("Hello!!!");
    }

    private native void printLog(String logThis);
}</pre>
<p>Back to the native.c file.</p>
<p>The name structure of the function is important. It is build from the java starting with a java identifier followed by the package name, followed by the class name, followed by the function name. This is one way of converting our java function into the native function. I usually do it by right clicking on the function name ( printLog ) and select 'Copy Qualified Name' paste it in the native.c file:</p>
<pre class="c">com.<span style="color: #202020;">jayway</span>.<span style="color: #202020;">ndksetup</span>.<span style="color: #202020;">NDKSetupActivity</span>.<span style="color: #202020;">printLog</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>Start by changing all dots (.) to underscores (_).</p>
<pre class="c">com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>Add the return value and a Java_ identifier to the function:</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>The input variable is a String in java so lets make it a java string in native as well.</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>jstring logString<span style="color: #66cc66;">&#41;</span></pre>
<p>The last thing we need to add is a reference to the JNI enviroment and a reference to java object that this function belongs to.</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jstring logString<span style="color: #66cc66;">&#41;</span></pre>
<p>Finally our first native function will look like this:</p>
<pre class="c"><span style="color: #339933;">#include &lt;jni.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
<span style="color: #339933;">#include &lt;android/log.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define DEBUG_TAG &quot;NDKSetupActivity&quot;</span>
&nbsp;
<span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jstring logString<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
    jboolean isCopy;
    <span style="color: #993333;">const</span> <span style="color: #993333;">char</span> * szLogString = <span style="color: #66cc66;">&#40;</span>*env<span style="color: #66cc66;">&#41;</span>-&gt;GetStringUTFChars<span style="color: #66cc66;">&#40;</span>env, logString, &amp;isCopy<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    __android_log_print<span style="color: #66cc66;">&#40;</span>ANDROID_LOG_DEBUG, DEBUG_TAG, <span style="color: #ff0000;">&quot;NDK: %s&quot;</span>, szLogString<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #66cc66;">&#40;</span>*env<span style="color: #66cc66;">&#41;</span>-&gt;ReleaseStringUTFChars<span style="color: #66cc66;">&#40;</span>env, logString, szLogString<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Just for fun we add another function, a fibonacci function.</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">native</span> <span style="color: #993333;">int</span> fibonacci<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> value<span style="color: #66cc66;">&#41;</span>;</pre>
<pre class="c">jint Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jint value<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>value &lt;= <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">return</span> value;
	<span style="color: #b1b100;">return</span> Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>env, this, value<span style="color: #cc66cc;">-1</span><span style="color: #66cc66;">&#41;</span>
            + Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>env, this, value<span style="color: #cc66cc;">-2</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Now you are up and running with your NDK development for Android.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Injectors and Extractors in Scala</title>
		<link>http://blog.jayway.com/2011/10/11/injectors-and-extractors-in-scala/</link>
		<comments>http://blog.jayway.com/2011/10/11/injectors-and-extractors-in-scala/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 14:05:46 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[case]]></category>
		<category><![CDATA[extractor]]></category>
		<category><![CDATA[injector]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10253</guid>
		<description><![CDATA[If you have used case classes in Scala, you can not neglect the power they bring to your applications. They provide a recursive decomposition mechanism via pattern matching. In this post I go through injectors and mostly extractors. You will see that how extractors can be employed for pattern matching. Consider that we need to [...]]]></description>
			<content:encoded><![CDATA[<p>If you have used <em>case</em> classes in Scala, you can not neglect the power they bring to your applications. They provide a recursive decomposition mechanism via pattern matching.</p>
<p>In this post I go through injectors and mostly extractors. You will see that how extractors can be employed for pattern matching.</p>
<p>Consider that we need to hold first names in an application. We can define a case class for <span style="text-decoration: underline;">Firstname</span>:</p>
<p><script src="https://gist.github.com/1280657.js?file=Firstname.scala"></script></p>
<p>we build a value from this case class in REPL:</p>
<pre>scala&gt; val fname = Firstname("Amir")
fname: Firstname = Firstname(Amir)</pre>
<p>and now a pattern matching on this case class:</p>
<pre>scala&gt; fname match {
     |     case Firstname(f) =&gt; println(f)
     |     case _            =&gt; println("Nothing found")
     | }
Amir</pre>
<p>Here <span style="text-decoration: underline;">fname</span> is matched against its case class by constructor patterns mechanism and its field is extracted and printed. Very powerful and handy.</p>
<p>What if we need to do a pattern matching for a string? The problem is that strings are not case classes.</p>
<p>Scala provides us with a very interesting mechanism called Extractors. An extractor is an object that has a method called <strong>unapply</strong> as one of its members. Let's clarify this with an example: assume we want to have an extractor object for IP addresses. We define the extractor as the following:</p>
<p><script src="https://gist.github.com/1280657.js?file=IPAddress.scala"></script></p>
<p>Method <span style="text-decoration: underline;">unapply</span> receives a string representing a possible IP address and returns an option of 4 strings. If the string is not a valid IP address, the method returns None. Method <span style="text-decoration: underline;">isValid</span> is added for validating IP addresses. Let's try this in REPL:</p>
<pre>scala&gt; val ip = "127.0.0.1"
ip: java.lang.String = 127.0.0.1

scala&gt; val nonIP = "128.-112.ABC."
nonIP: java.lang.String = 128.-112.ABC.

scala&gt; IPAddress.unapply(ip)
res0: Option[(String, String, String, String)] = Some((127,0,0,1))

scala&gt; IPAddress.unapply(nonIP)
res1: Option[(String, String, String, String)] = None</pre>
<p>And if we use it in a pattern matching statement:</p>
<pre>scala&gt; ip match {
     |    case IPAddress(_, _, _, a) =&gt; println(a)
     |    case _                     =&gt; println("Invalid ip address")
     | }
1

scala&gt; nonIP match {
     |    case IPAddress(_, _, _, a) =&gt; println(a)
     |    case _                     =&gt; println("Invalid ip address")
     | }
Invalid ip address</pre>
<p>So <span style="text-decoration: underline;">ip</span> was a valid string representation of an IP Address and it is matched against <span style="text-decoration: underline;">IPAddress</span> while <span style="text-decoration: underline;">nonIP</span> was not a valid one. In the example above we were only interested in the last byte of IP Address and we skipped the rest by _ wildcard. Of course you can extract all the four parts if you need them.</p>
<p>In <span style="text-decoration: underline;">IPAddress</span> object we used 4 variables that is wrapped in a <em>Some</em> in the success case and returned. This can be generalized to <em>N</em> variables.</p>
<p>It is also possible that an extractor pattern does not bind to any variables. In this case the corresponding <span style="text-decoration: underline;">unapply</span> method returns a boolean (<em>true</em> for success and <em>false</em> for failure). As an example we changed the unapply method to the following:</p>
<p><script src="https://gist.github.com/1280657.js?file=NoBinding.scala"></script></p>
<p>and we try it in REPL:</p>
<pre>scala&gt; "127.0.0.1" match {
     |    case IPAddress() =&gt; println("Valid")
     |    case _           =&gt; println("Invalid")
     | }
Valid</pre>
<p>Remember that although there is no binding in this case but you have to put the parentheses in front of <span style="text-decoration: underline;">IPAddress</span>.</p>
<p>So far we have seen fixed number of element values. But what if we have variable number of element values? For example if you have a string that can contain arbitrary number of IP addresses? In order to handle this case, Scala allows you to define a different extractor method called <strong>unapplySeq</strong>. To see how it can be used, assume we want to have pattern matching on a string containing arbitrary number of IP Addresses:</p>
<p><script src="https://gist.github.com/1280657.js?file=IPAddresses.scala"></script></p>
<p>This time the method returns an option of a sequence of string. Now let's see what we can do with it:</p>
<pre>scala&gt; val ips = "192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4"
ips: java.lang.String = 192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4

scala&gt; ips match {
     |    case IPAddresses(IPAddress(a, _, _, _), IPAddress(b, _, _, _), _*) =&gt; println(a + " " + b)
     |    case _                                                             =&gt; println("Invalid IP addresses")
     | }
192 192</pre>
<p>In this example we used both <span style="text-decoration: underline;">IPAddress</span> and <span style="text-decoration: underline;">IPAddresses</span> objects in the pattern matching. There are 4 IP addresses in <span style="text-decoration: underline;">ips</span> and we are looking for the first byte of the first two IPs in the string. How powerful and clean!</p>
<p>The <span style="text-decoration: underline;">unapply</span> method is called <em>extractor</em> because it takes an element of the same set and extracts some of its parts. In our example <span style="text-decoration: underline;">IPAddress</span> takes a string and validates and extracts all 4 bytes of the address. You can also define a method <span style="text-decoration: underline;">apply</span> on an object that does vice versa which takes some arguments and yields an element of a given set. This method is called an <em>injection</em>. We can define injection for our <span style="text-decoration: underline;">IPAddress</span> object like this:</p>
<p><script src="https://gist.github.com/1280657.js?file=Injector.scala"></script></p>
<p>Injections and extractions are often located in the same object because then you can use the object name for both constructions and pattern matching. However, it is also possible to have an extraction object without injection. The object itself is called <em>extractor</em> regardless of whether or not it has an apply method [1].</p>
<p>Remember if you include the injection method, it should be a dual to the extraction method, for example:</p>
<pre>IPAddress.unapply( IPAddress.apply(a, b, c, d) )</pre>
<p>should return:</p>
<pre>Some(a,b,c,d)</pre>
<h3>Extractors vs. Case classes</h3>
<p>There is a section in [1] that compares extractors and case classes which I summarize here:</p>
<ul>
<li>There is one shortcoming with case classes: they expose the <em>concrete representation of data</em>. This means that if a case succeeds in a matching, you know that the selector expression is an instance of that case class.</li>
<li>Extractors do not expose the concrete representation of data.</li>
<li>Case classes have less code and they are easier to set up. Scala compiler can optimize patterns over case classes much better than extractors.</li>
<li>If a case class inherits from a sealed base class, Scala compiler checks for pattern matches for exhaustiveness and will complain in case there exists something while Scala compiler can not do the same thing for extractors.</li>
<li>If you write code for a <em>closed application</em>, case classes are preferable because of their advantages in conciseness, speed and static checking.</li>
<li>If you need to expose a type to unknown clients, extractors might be preferable.</li>
</ul>
<p>&nbsp;</p>
<p><span class="Apple-style-span" style="font-size: 15px; font-weight: bold;">References:</span></p>
<p>[1]: Martin Odersky, Lex Spoon, Bill Venners, "Programming in Scala", 2nd Edition</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/11/injectors-and-extractors-in-scala/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Simple Parsing of Complex JSON and XML Documents in Java</title>
		<link>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/</link>
		<comments>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/#comments</comments>
		<pubDate>Sun, 09 Oct 2011 15:12:15 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9743</guid>
		<description><![CDATA[In this blog I'm going to demonstrate how to parse and validate more complex JSON and XML documents in Java using the REST Assured framework and the XmlPath and JsonPath components available in this framework. Since REST Assured is implemented in Groovy it can be really beneficial to take advantage of Groovy's collection API. Let's [...]]]></description>
			<content:encoded><![CDATA[<p>In this blog I'm going to demonstrate how to parse and validate more complex JSON and XML documents in Java using the <a href="http://code.google.com/p/rest-assured/">REST Assured</a> framework and the <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/xml/XmlPath.html">XmlPath</a> and <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> components available in this framework. Since REST Assured is implemented in Groovy it can be really beneficial to take advantage of Groovy's <a href="http://groovy.codehaus.org/Collections">collection</a> API. Let's begin by looking at an example in Groovy:</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> wordsWithSizeGreaterThanFour = words.<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20findAll"><span style="color: #663399;">findAll</span></a> <span style="color: #66cc66;">&#123;</span> it.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &gt; <span style="color: #cc66cc;">4</span> <span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>At the first line we simply define a list with some words but the second line is more interesting. Here we search the <code>words</code> list for all words that are longer than 4 characters by calling the <code>findAll</code> with a <a href="http://groovy.codehaus.org/Closures">Groovy closure</a>. The closure has an implicit variable called "it" which represents the current item in the list. The result is a new list, <code>wordsWithSizeGreaterThanFour</code>, containing <code>buffalo</code> and <code>dinosaur</code>. Pretty nice and simple! There are other interesting methods that we can use on collections in Groovy as well, e.g.</p>
<ul>
<li>find - finds the first item matching a closure predicate</li>
<li>collect - collect the return value of calling a closure on each item in a collection</li>
<li>sum - Sum all the items in the collection</li>
<li>max/min - returns the max/min values of the collection</li>
</ul>
<p>So how do we take advantage of this when validating our XML or JSON responses with REST Assured?</p>
<h2>XML Example</h2>
<p>Let's say we have a resource at "localhost:8080/shopping" that returns the following XML:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;shopping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;groceries&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Chocolate<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Coffee<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;supplies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Paper<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item</span> <span style="color: #000066;">quantity</span>=<span style="color: #ff0000;">&quot;4&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>Pens<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;present&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item</span> <span style="color: #000066;">when</span>=<span style="color: #ff0000;">&quot;Aug 10&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>Kathryn's Birthday<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/shopping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Let's also say we want to write a test that verifies that the category of type <code>groceries</code> has items Chocolate and Coffee. In REST Assured it can look like this:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;</pre>
</pre>
<p>What's going on here? First of all the XML path "shopping.category" returns a list of all categories. On this list we invoke a function, <code>find</code>, to return the single category that has the XML attribute, <code>type</code>, equal to "groceries". On this category we then continue by getting all the items associated with this category. Since there are more than one item associated with the groceries category a list will be returned and we verify this list against the hasItems <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> matcher. </p>
<p>But what if you want to get the items and not validate them against a Hamcrest matcher? This is also simple using the <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/xml/XmlPath.html">XmlPath</a> class:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</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> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// And get the grocieries from the response. &quot;from&quot; is statically imported from the XmlPath class</span>
List&lt;String&gt; groceries = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getList</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>If the list of groceries is the only thing you care about in the response body you can also use a shortcut:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</span>
List&lt;String&gt; groceries = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">path</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>Depth-first search</h3>
<p>It's actually possible to simplify the previous example even further:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'groceries' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p><code>**</code> is a shortcut for doing depth first searching in the XML document. We search for the first node that has an attribute named <code>type</code> equal to "groceries". Notice also that we don't end the XML path with "item". The reason is that <code>toString()</code> is called automatically on the category node which returns a list of the item values.</p>
<h3>Root path</h3>
<p>Let's expand the example by also validating that the category of type supplies contains Paper and Pens:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'groceries' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'supplies' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Paper&quot;</span>, <span style="color: #ff0000;">&quot;Pens&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Even though this works you can probably see that the XML path is almost duplicated for the two body expectations and this is of course something we want to avoid. To address this we can use a root path and path arguments:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">rootPath</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == '%s' }&quot;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span>, withArgs<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;groceries&quot;</span><span style="color: #66cc66;">&#41;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span>, withArgs<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;supplies&quot;</span><span style="color: #66cc66;">&#41;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Paper&quot;</span>, <span style="color: #ff0000;">&quot;Pens&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>By specifiying a "root path" we don't need to duplicate the entire path just to change the category type.</p>
<h2>JSON Example</h2>
<p>Let's say we have a resource at "/store" that returns the following JSON document:</p>
<pre>&nbsp;
{ &quot;store&quot; : {
  &quot;book&quot; : [
          { &quot;author&quot; : &quot;Nigel Rees&quot;,
            &quot;category&quot; : &quot;reference&quot;,
            &quot;price&quot; : 8.95,
            &quot;title&quot; : &quot;Sayings of the Century&quot;
          },
          { &quot;author&quot; : &quot;Evelyn Waugh&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;price&quot; : 12.99,
            &quot;title&quot; : &quot;Sword of Honour&quot;
          },
          { &quot;author&quot; : &quot;Herman Melville&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;isbn&quot; : &quot;0-553-21311-3&quot;,
            &quot;price&quot; : 8.99,
            &quot;title&quot; : &quot;Moby Dick&quot;
          },
          { &quot;author&quot; : &quot;J. R. R. Tolkien&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;isbn&quot; : &quot;0-395-19395-8&quot;,
            &quot;price&quot; : 22.99,
            &quot;title&quot; : &quot;The Lord of the Rings&quot;
          }
        ]
   }
}
&nbsp;</pre>
<h3>Example 1</h3>
<p>As a first example let's say we want to make the request to "/store" and assert that the titles of the books with a price less than 10 are "Sayings of the Century" and "Moby Dick":</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.findAll { it.price &lt; 10 }.title&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Sayings of the Century&quot;</span>, <span style="color: #ff0000;">&quot;Moby Dick&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Just as in the XML examples above we use a closure to find all books with a price less than 10 and then return the titles of all the books. We then use the <code>hasItems</code> matcher to assert that the titles are the ones we expect. Using <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> we can return the titles instead:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</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> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// And get all books with price &lt; 10 from the response. &quot;from&quot; is statically imported from the JsonPath class</span>
List&lt;String&gt; bookTitles = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getList</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.findAll { it.price &lt; 10 }.title&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>Example 2</h3>
<p>Let's consider instead that we want to assert that the sum of the length of all author names are greater than 50. This is a rather complex question to answer and it really shows the strength of closures and Groovy collections. In REST Assured it looks like this:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author.collect { it.length() }.sum()&quot;</span>, greaterThan<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>First we get all the authors ("store.book.author") and invoke the <code>collect</code> method on the resulting list with the closure <code>{ it.length() }</code>. What it does is to call the <code>length()</code> method on each author in the list and returns the result to a new list. On this list we simply call the <code>sum()</code> method to sum all the length's. The end result is <code>53</code> and we assert that it's greater than 50 by using the <code>greaterThan</code> matcher. But it's actually possible to simplify this even further. Consider the <code>words</code> example from the beginning of the article again:</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
&nbsp;</pre>
<p>Groovy has a very handy way of calling a function for each element in the list by using the <code>*</code> notation, e.g.</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20assert"><span style="color: #000000; font-weight: bold;">assert</span></a> <span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">8</span><span style="color: #66cc66;">&#93;</span> == words*.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>I.e. Groovy returns a new list with the lengths of the items in the words list. We can utilize this for the author list in REST Assured as well:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author*.length().sum()&quot;</span>, greaterThan<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>And of course we can use <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> to actually return the result:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as an input stream</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInputStream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">InputStream</span></a> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asInputStream</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Get the sum of all author length's as an int. &quot;from&quot; is again statically imported from the JsonPath class</span>
<span style="color: #993333;">int</span> sumOfAllAuthorLengths = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getInt</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author*.length().sum()&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// We can also assert that the sum is equal to 53 as expected.</span>
assertThat<span style="color: #66cc66;">&#40;</span>sumOfAllAuthorLengths, is<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">53</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Summary</h2>
<p>At a first glance the syntax may seem quite strange and complex but once you get used to it it's extremely powerful and actually quite simple. It's also a good place to start if you work with Java and want to understand the benefit of closures. There are a lot more features that can help you parsing and validating JSON and XML using <a href="http://code.google.com/p/rest-assured/">REST Assured</a> than the ones shown in this article. For further reading refer to the <a href="http://code.google.com/p/rest-assured/">REST Assured web-page</a> and read up on <a href="http://groovy.codehaus.org/Collections">Groovy collections</a>. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scala Type Variances &#8211; Part three</title>
		<link>http://blog.jayway.com/2011/10/05/scala-type-variances-part-three/</link>
		<comments>http://blog.jayway.com/2011/10/05/scala-type-variances-part-three/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 11:05:50 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[lower-bound]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[subtyping]]></category>
		<category><![CDATA[type]]></category>
		<category><![CDATA[upper-bound]]></category>
		<category><![CDATA[variance]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9977</guid>
		<description><![CDATA[So far we have seen how to define covariant and contravariant subtypes in Scala. In this post we will study lower bounds and upper bounds and see how they can be of great help when designing your application. Lower bounds Consider the class I defined in the first post: Company is covariant in type T [...]]]></description>
			<content:encoded><![CDATA[<p>So far we have seen how to define <a title="covariant" href="http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/">covariant</a> and <a title="contravariant" href="http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/">contravariant</a> subtypes in Scala. In this post we will study lower bounds and upper bounds and see how they can be of great help when designing your application.</p>
<h3>Lower bounds</h3>
<p>Consider the class I defined in the first post:</p>
<p><script src="https://gist.github.com/1280571.js?file=Company.scala"></script></p>
<p>Company is covariant in type <em>T</em> as you know by now. It's been a while and we realize it's the time to define a partnership relation for companies to connect them together and expand their co-operations. So we add the following method to <span style="text-decoration: underline;">Company</span> class:</p>
<p><script src="https://gist.github.com/1280571.js?file=PartnerDef.scala"></script></p>
<p>When we try to compile this code we get:</p>
<pre>Error: covariant type T occurs in contravariant position in type T of value y</pre>
<p>What happened here? To see what has happened it's better to take a look at Function1 definition in Scala:</p>
<p><script src="https://gist.github.com/1280571.js?file=Function1.scala"></script></p>
<p>This definition tells us that the input of a function is contravariant (negative) and what it returns is covariant (positive). So remember that no matter how many arguments a function has, all of them are in negative positions:</p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/function2.png" rel="lightbox"><img class="aligncenter size-medium wp-image-9991" title="function" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/function2-300x111.png" alt="" width="300" height="111" /></a></p>
<p>Now it should be more clear why we got the compile error. We were passing an argument of type <em>T</em> which is covariant (positive) and we know that arguments of a function has negative (contravariant) positions. This is a contradiction.</p>
<p>But how can we solve this? We can use lower type bounds to parameterize a method.</p>
<p><em>Lower type bounds</em>: help you to declare a type to be a supertype of another type. <em>T</em> &gt;: <em>A</em> indicates that type <em>T</em> or abstract type <em>T</em> refers to a supertype of type <em>A</em>.</p>
<p>Let's correct the defined method by using lower bounds:</p>
<p><script src="https://gist.github.com/1280571.js?file=NewPartnerDef.scala"></script></p>
<p>By this new definition, <span style="text-decoration: underline;">partnerWith</span> method accepts arguments that can be supertype of type <em>T</em>.</p>
<pre>scala&gt; val littleCompany: Company[SmallCompany] = new Company[SmallCompany](new SmallCompany)
littleCompany: Company[SmallCompany] = Company@149bc5a

scala&gt; val bigCompany: Company[BigCompany] = new Company[BigCompany](new BigCompany)
bigCompany: Company[BigCompany] = Company@116ac04

scala&gt; bigCompany.partnerWith(littleCompany)</pre>
<p>So <span style="text-decoration: underline;">partnerWith</span> method is now generalized and polymorphic.</p>
<h3>Upper bounds</h3>
<p>Assume that we want to restrict the partnership relation somehow in our example. We wanna say that a company can have partnership with another company that is a subtype of <span style="text-decoration: underline;">Company[BigCompany]</span>. In order to apply this restriction in Scala, one can use upper bounds. So let's change the <span style="text-decoration: underline;">partnerWith</span> method to reflect this:</p>
<p><script src="https://gist.github.com/1280571.js?file=UpperboundPartner.scala"></script></p>
<p>Now <span style="text-decoration: underline;">partnerWith</span> only accepts arguments that are a subtype of <span style="text-decoration: underline;">Company[BigCompany]</span>. Let's prove this by introducing a new company:</p>
<p><script src="https://gist.github.com/1280571.js?file=CrappyCompany.scala"></script></p>
<p>This class does not extend <span style="text-decoration: underline;">BigCompany</span> so <span style="text-decoration: underline;">Company[CrappyCompany]</span> is not a subtype of <span style="text-decoration: underline;">Company[BigCompany]</span> according to covariant type declaration. Now we try to build partnerships in REPL:</p>
<pre>scala&gt; val littleCompany: Company[SmallCompany] = new Company[SmallCompany](new SmallCompany)
littleCompany: Company[SmallCompany] = Company@1979eb4

scala&gt; val bigCompany: Company[BigCompany] = new Company[BigCompany](new BigCompany)
bigCompany: Company[BigCompany] = Company@6d1901

scala&gt; littleCompany.partnerWith(bigCompany)

scala&gt; val crappyCompany: Company[CrappyCompany] = new Company[CrappyCompany](new CrappyCompany)
crappyCompany: Company[CrappyCompany] = Company@1d0d313

scala&gt; littleCompany.partnerWith(crappyCompany)
&lt;console&gt;:11: error: inferred type arguments [Company[CrappyCompany]] do not conform to method 
partnerWith's type parameter bounds [U &lt;: Company[BigCompany]]
       littleCompany.partnerWith(crappyCompany)
                     ^</pre>
<p>So by upper type bound declaration we could restrict our partnership relation.</p>
<p>Remember that by definition a class is supertype and subtype of itself. Hence you can pass an instance of <span style="text-decoration: underline;">Company[BigCompany]</span> to <span style="text-decoration: underline;">partnerWith</span>:</p>
<pre>scala&gt; val bigCompany2 : Company[BigCompany] = new Company[BigCompany](new BigCompany)
bigCompany2: Company[BigCompany] = Company@b61e92

scala&gt; bigCompany.partnerWith(bigCompany2)</pre>
<p>Note that both lower and upper bound declarations have the colon as their second character so you don't mix the order ( &lt;: &gt;: )</p>
<h3>Conclusion</h3>
<p>In these three posts I showed how you can avail from Scala variance annotations and lower and upper bounds together to design your application in a type safe manner. Scala provides you with <em>type-driven design</em> where types of an interface guides its detailed design and implementation [1]. Examples provided in these posts were not the best examples but they could still show the purpose of their existence. I hope you have a better understanding of this cool feature in Scala.</p>
<p>&nbsp;</p>
<h3>References</h3>
<p>[1]: Martin Odersky, Lex Spoon, Bill Venners, "Programming in Scala", 2nd Edition</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/05/scala-type-variances-part-three/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Scala Type Variances &#8211; Part two</title>
		<link>http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/</link>
		<comments>http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 10:18:11 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[contravariant]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[subtyping]]></category>
		<category><![CDATA[type]]></category>
		<category><![CDATA[variance]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9907</guid>
		<description><![CDATA[In the previous post, I went through what covariant subtyping is. In this post we will study contravariant subtyping with a small example. Contravariant Subtyping Do you remember the definition of covariant? Contravariant is the other way around. I will clarify this by the following example (example is adopted from [1]). Consider we have a [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous <a title="post" href="http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/">post</a>, I went through what covariant subtyping is. In this post we will study contravariant subtyping with a small example.</p>
<h3>Contravariant Subtyping</h3>
<p>Do you remember the definition of covariant? Contravariant is the other way around. I will clarify this by the following example (example is adopted from [1]). Consider we have a trait:</p>
<p><script src="https://gist.github.com/1280571.js?file=NetworkChannel.scala"></script></p>
<p>This trait has a write method that is responsible for accepting an argument and writing it in the current network channel. Assume that we have two <span style="text-decoration: underline;">NetworkChannel</span> of type AnyRef and String:</p>
<p><script src="https://gist.github.com/1280571.js?file=ChannelImpl.scala"></script></p>
<p>We just don't care about the write implementation now. There is another class that is responsible for controlling output channels:</p>
<p><script src="https://gist.github.com/1280571.js?file=BufferControl.scala"></script></p>
<p>The control method accepts an argument of type <span style="text-decoration: underline;">NetworkChannel[String]</span>. Do you think we can pass <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> to this method? Yes we can! <span style="text-decoration: underline;">NetworkChannel</span> is declared to be contravariant in its type T.</p>
<p>Contrvariant subtyping means: <strong>If <em>S</em> is a subtype of <em>T</em> then NetworkChannel[<em>T</em>] is a subtype of NetworkChannel[<em>S</em>]</strong></p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/contra1.png" rel="lightbox"><img class="size-medium wp-image-9921 aligncenter" title="contra1" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/contra1-300x175.png" alt="" width="300" height="175" /></a></p>
<p>This seems to be a little bit strange in our example. We know that String is a subtype of AnyRef in Scala. How come <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> can be a subtype of <span style="text-decoration: underline;">NetworkChannel[String]</span> ?</p>
<p>Consider what you can do with each channel. <span style="text-decoration: underline;">NetworkChannel[String]</span> accepts arguments of type String and write them in network channel. <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> accepts arguments of type AnyRef and write them also in network channel. We can substitute <span style="text-decoration: underline;">NetworkChannel[String]</span> with <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> since whatever can be done by <span style="text-decoration: underline;">NetworkChannel[String]</span> can be done also by <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> (remember that <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> can also write strings) but not vice versa. We can not use <span style="text-decoration: underline;">NetworkChannel[String]</span> instead of <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> since it only accepts strings.</p>
<p>Remember that contravariant orders types from more <em>genetic</em> to more <em>specific.</em></p>
<p>How should I know if two types are covariants or contravariants? Read the following section.</p>
<h3>Liskov Substitution Principle (LSP)</h3>
<p>LSP is a principle in object-oriented programming. It states:</p>
<blockquote><p>It is safe to assume that S is a subtype of T if you can substitute a value of type S wherever a value of type T is required without violating the desirable properties of the program [2].</p></blockquote>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/contravariantSubTyping1.png" rel="lightbox"><img class="aligncenter size-full wp-image-9929" title="contravariantSubTyping" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/contravariantSubTyping1.png" alt="" width="535" height="283" /></a></p>
<p>So let's say we have <em>S</em> as a subtype of <em>T</em>. If Class of type <em>S</em> is a subtype of Class of type <em>T</em> then there is a <strong>covariant</strong> subtyping between them. Otherwise if Class of type <em>T</em> is a subtype of Class of type <em>S</em> then there is <strong>contravariant</strong> subtyping between them. if there is no subtyping relation between Class of type <em>S</em> and <em>T</em>, then there is <strong>invariant</strong> subtyping relation.</p>
<p>I hope you have understood Scala Types variances. In the next <a title="post" href="http://blog.jayway.com/2011/10/05/scala-type-variances-part-three/">post</a> I will discuss Lower bounds and upper bounds.</p>
<h3>References</h3>
<p>[1]: Martin Odersky, Lex Spoon, Bill Venners, "Programming in Scala", 2nd Edition<br />
[2]: Barbara Liskov, Jeannette Wing, "A behavioral notion of subtyping", ACM Transactions on Programming Languages and Systems (TOPLAS), Volume 16, Issue 6 (November 1994), pp. 1811 – 1841</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Scala Type Variances &#8211; Part one</title>
		<link>http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/</link>
		<comments>http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 16:34:43 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[covariant]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[subtyping]]></category>
		<category><![CDATA[type]]></category>
		<category><![CDATA[variance]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9867</guid>
		<description><![CDATA[I remember when I started to learn Scala, I usually come up with brackets in the Scala API doc that have plus and minus characters inside. Honestly that scared me a little bit! But after I learned a bit about Scala type system, I know the purpose of theses type declarations and I appreciate their [...]]]></description>
			<content:encoded><![CDATA[<p>I remember when I started to learn Scala, I usually come up with brackets in the Scala API doc that have plus and minus characters inside. Honestly that scared me a little bit! But after I learned a bit about Scala type system, I know the purpose of theses type declarations and I appreciate their designer <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In this series of posts I will try my best to clear out type variance annotations in Scala; a powerful tool to handle type orderings from specific to generic and vice verca.</p>
<h3>Covariant Subtyping</h3>
<p>We start by covariant subtyping. If you don't know what it is, please be patient. First consider the following code in Scala:</p>
<p><script src="https://gist.github.com/1280571.js?file=CompanyAndInvestor.scala"></script></p>
<p>We have a <span style="text-decoration: underline;">Company</span> class that has type parameter <em>T</em>. This class accepts a value of type <em>T</em> for its constructor. We have two companies defined here: <span style="text-decoration: underline;">BigCompany</span> and <span style="text-decoration: underline;">SmallCompany</span>. As it is obvious from the code <span style="text-decoration: underline;">SmallCompany</span> is a subtype of <span style="text-decoration: underline;">BigCompany</span>. Finally we have a class Investor that accepts only companies of type <span style="text-decoration: underline;">BigCompany</span> so it invests only on big ones!<br />
Now let's do some constructions in REPL:</p>
<pre>scala&gt; val littleCompany: Company[SmallCompany] = new Company[SmallCompany](new SmallCompany)
littleCompany: Company[SmallCompany] = Company@1e70822

scala&gt; val bigCompany: Company[BigCompany] = new Company[BigCompany](new BigCompany)
bigCompany: Company[BigCompany] = Company@9bb740

scala&gt; val bigInvestor:Investor = new Investor(bigCompany)
bigInvestor: Investor = Investor@1004566</pre>
<p>So far so good. After a while it is decided that we need investors that can take care of small companies. We don't want to define a new brand of investor thus we use the existing one. So we try to construct:</p>
<pre>scala&gt; val smallInvestor:Investor = new Investor(littleCompany)</pre>
<p>But we get:</p>
<pre>&lt;console&gt;:8: error: type mismatch;
 found   : Company[SmallCompany]
 required: Company[BigCompany]
Note: SmallCompany &lt;: BigCompany, but class Company is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
       val smallInvestor:Investor = new Investor(littleCompany)
                                                 ^</pre>
<p>Bang! What happened? Compile error!</p>
<p>Let's see what happened exactly here. We know by definition that <span style="text-decoration: underline;">SmallCompany</span> is subtype of <span style="text-decoration: underline;">BigCompany</span>. But what is the relation between <span style="text-decoration: underline;">Company[</span><span style="text-decoration: underline;">SmallCompany]</span> and <span style="text-decoration: underline;">Company[BigCompany]</span> ? It is not defined by default and we need somehow to tell compiler about this. In order to solve this we change class <em>Company</em> to the following:</p>
<p><script src="https://gist.github.com/1280571.js?file=Company.scala"></script></p>
<p>The only thing that is changed is the type parameter that has a + sign in front. This means that subtyping is covariant (flexible) in paramter <em>T</em>.</p>
<p>Covariant subtyping means: <strong>if <em>S</em> is a subtype of <em>T</em> then Company[<em>S</em>] is subtype of Company[<em>T</em>]</strong>.</p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/convariantSubTyping1.png" rel="lightbox"><img class="size-medium wp-image-9892 aligncenter" title="convariantSubTyping" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/convariantSubTyping1-300x191.png" alt="" width="300" height="191" /></a></p>
<p>Remember that covariant orders types from more <em>specific</em> to more <em>generic</em>.</p>
<p>Let's construct a small investor again with new <span style="text-decoration: underline;">Company</span> definition:</p>
<pre>scala&gt; val smallInvestor:Investor = new Investor(littleCompany)
smallInvestor: Investor = Investor@9fad9c</pre>
<p>Great! We could solve this by Scala variance subtyping. By a single + sign that is called <em>variance annotation</em> you could tell Scala compiler that you want <span style="text-decoration: underline;">Company[SmallCompany]</span> be a subtype of <span style="text-decoration: underline;">Company[BigCompany]</span>.</p>
<p>In the next <a title="post" href="http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/">post</a>, we will investigate contravariant subtyping.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Experimenting with Scala Parallel Collections</title>
		<link>http://blog.jayway.com/2011/10/02/experimenting-with-scala-parallel-collections/</link>
		<comments>http://blog.jayway.com/2011/10/02/experimenting-with-scala-parallel-collections/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 15:26:13 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9802</guid>
		<description><![CDATA[In this short post, I want to show you how you can avail from Scala parallel collections in your application and under which conditions it makes sense to use it. Parallel Collections were introduced in Scala 2.9 release which are built on the same abstractions and provide the same interfaces as existing collection implementation. It [...]]]></description>
			<content:encoded><![CDATA[<p>In this short post, I want to show you how you can avail from Scala parallel collections in your application and under which conditions it makes sense to use it.</p>
<p>Parallel Collections were introduced in <a title="Scala 2.9" href="http://www.scala-lang.org/node/9483">Scala 2.9</a> release which are built on the same abstractions and provide the same interfaces as existing collection implementation. It follows the model proposed by Doug Lea in his Fork/Join framework [1]. They are really easy to use and this is one of the advantages you can see for them. If you are familiar with parallel programming, it is quite difficult to convert a sequential program into a parallel one. This difficulty comes from the fact that each has its own paradigm, algorithm and data structure.</p>
<p>Scala enables you to invoke a method called <strong>par</strong> on a collection to get a parallel collection. This parallel collection then employs all the available cores on the target system. You can easily try this out in REPL:</p>
<pre>scala&gt; List(1,2,3,4,5).par.filter { _ % 2 == 0 }
res1: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(2, 4)</pre>
<p>This is a simple filtering on a list. The only new thing I added is 'par' after list definition.</p>
<p>Now let's have a comparison between sequential and parallel versions and see how parallel collection can help us. Consider that we have a Data class with some data as follows:</p>
<p><script src="https://gist.github.com/1292276.js?file=Data.scala"></script></p>
<p>and a companion object to construct Data instances:</p>
<p><script src="https://gist.github.com/1292276.js?file=CompanionData.scala"></script></p>
<p>Now we define computation trait to perform some operations on the aforementioned data class:</p>
<p><script src="https://gist.github.com/1292276.js?file=Computation.scala"></script></p>
<p>This trait has two implementations:</p>
<p><script src="https://gist.github.com/1292276.js?file=Implementations.scala"></script></p>
<p>In each implementation, method compute applies a map with function f and then calculate the maximum element in the list. The only difference between these two implementations is the use of 'par' method. Now let's run and time each implementation:</p>
<p><script src="https://gist.github.com/1292276.js?file=Experiment.scala"></script></p>
<p>Running the code with SBT on a machine with 4 CPU cores:</p>
<pre>&gt; run 3
[info] Running com.jayway.parallel.ParallelExperiment 3
Sequential 44 (ms)
Parallel 14 (ms)</pre>
<p>&nbsp;</p>
<pre>&gt; run 100
[info] Running com.jayway.parallel.ParallelExperiment 100
Sequential 1020 (ms)
Parallel 268 (ms)</pre>
<p>As expected, we gained speed up in parallel version. Results for a couple of run with different list sizes is depicted in the following fgure:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_htm_88dfb8f1.jpg" rel="lightbox"><img class="aligncenter size-full wp-image-9833" title="parallel-result_htm_88dfb8f" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_htm_88dfb8f1.jpg" alt="" width="580" height="397" /></a></p>
<p>Now let's change function f to the following:</p>
<pre>  def f(data:Data):Int =  {
    data.a + data.b
  }</pre>
<p>I removed the Thread.sleep so the method returns immediately. Now let's have a look at results for different runs again:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_21.jpeg" rel="lightbox"><img class="aligncenter size-full wp-image-9837" title="parallel-result_2" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_21.jpeg" alt="" width="583" height="407" /></a><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_2.jpeg"><br />
</a></p>
<p>Interestingly, this time the result is not good at all! It's even vice versa and sequential implementation has lower running time for the first 5 runs. This is because using parallel collection has some overhead for distributing (fork) and gathering (join) the data between cores. Thus one can conclude having heavy computations (which is the case in most applications), parallel collections can be of great performance improvement. But there might be scenarios (like the second scenario we discussed) where sequential collection is faster <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>For a better understanding of Scala Parallel Collection internals, please watch <a title="Aleksander Prokopec's presentation" href="http://days2010.scala-lang.org/node/138/140">Aleksander Prokopec's presentation</a> from Scala Days 2010. If you are interested to know more then you can read [2].</p>
<h3>References:</h3>
<p>[1]: Doug Lea, A Java Fork/Join Framework, 2000.<br />
[2]: Aleksandar Prokopec, Tiark Rompf, Phil Bagwell, Martin Odersky, "A Generic Parallel Collection Framework", Euro-Par 2011</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/02/experimenting-with-scala-parallel-collections/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>IntelliJ IDEA performance improvement</title>
		<link>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/</link>
		<comments>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 17:26:58 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[home directory]]></category>
		<category><![CDATA[idea]]></category>
		<category><![CDATA[intellij]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9443</guid>
		<description><![CDATA[Working as a consultant, it is not unusual that I am referred to customer specific software environment with regard to computers, operating systems, networks and other configurations. However, since I work with Java, most tools are available online and they can easily be downloaded and installed on different platforms. IntelliJ IDEA is no exception, but [...]]]></description>
			<content:encoded><![CDATA[<p>Working as a consultant, it is not unusual that I am referred to customer specific software environment with regard to computers, operating systems, networks and other configurations. However, since I work with Java, most tools are available online and they can easily be downloaded and installed on different platforms. IntelliJ IDEA is no exception, but before you start coding you should make sure you know how the <a href="http://en.wikipedia.org/wiki/Home_directory">home directory</a> of your computer is setup and configure IntelliJ IDEA accordingly. From the <a href="http://devnet.jetbrains.net/docs/DOC-181">documentation</a>:</p>
<blockquote><p>
In some environments user's home directory is located on the mapped network drive which in unacceptable for IntelliJ IDEA. You'll notice the huge performance degradation.
</p></blockquote>
<h2>What is the problem?</h2>
<p>There are some good motives for keeping the home directory mounted to a network folder rather than on the local hard drive. For example, all user settings and user documents can be backed up centrally, and the user could potentially log in to any computer and have the same user environment. However, there are also some drawbacks. Depending on how the home folder is configured, there will either be a remote network call for each file access, or the file changes will be executed as a batch job at scheduled intervals or specific events such as logging off the computer.</p>
<p>The second part of the problem is that IntelliJ IDEA produces quite a lot of data, typically several hundred megabytes, besides the anticipated artifacts. The data consists of IDE plugins, configuration files, log files, but the vast majority is internal cache files. By default, the data is written to a hidden <i>.IntelliJIdea10/</i> folder in your home directory.</p>
<p>If you combine these two factors, the performance will suffer. How much depends on the bandwidth of your network, something that I became painfully aware of when I logged in remotely to the customer's network via a slow VPN connection.</p>
<h2>Solution</h2>
<p>Avoid network overhead by configuring IntelliJ IDEA to cache data on your local computer instead of in your home folder. A recent customer used Windows XP as their working environment, the instructions below are based on that experience.</p>
<ol>
<li>
Create a new directory on a <i>local</i> harddrive that IntelliJ IDEA can use, e.g. <i>C:/.IntelliJIdea10/</i>. Hint, you cannot create a library starting with a "." from Windows Explorer, you have to use the <code>mkdir</code> command from the terminal.
</li>
<li>
Locate the <i>idea.properties</i> file in the <i>bin</i> directory in IntelliJ IDEA's installation directory. The default location is <i>C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 10.5.1\bin</i>.
</li>
<li>
Change the relevant properties to point to the recently created directory:</p>
<pre class="brush:xml">
# path to IDEA config folder. Make sure you're using forward slashes
idea.config.path=C:/.IntelliJIdea10/config

# path to IDEA system folder. Make sure you're using forward slashes
idea.system.path=C:/.IntelliJIdea10/system

# path to user installed plugins folder. Make sure you're using forward slashes
idea.plugins.path=C:/.IntelliJIdea10/config/plugins
</pre>
</li>
</ol>
<h2>Considerations</h2>
<p>Consider <i>not</i> to change the <i>idea.config.path</i> property if you are using several different computers and you would like to have the same configuration on all machines. Additionally, if you are using IntelliJ IDEA Ultimate, i.e. the commercial version of the tool, you should also make a cautious decision about whether or not to keep this property unchanged, because the license file is stored in the denoted directory. On the other hand, if you always use the same computer you might as well change this property together with the other properties, so that all IntelliJ IDEA files are stored in the same location.</p>
<h2>References</h2>
<ul>
<li>IDEA files location: <a href="http://devnet.jetbrains.net/docs/DOC-181">http://devnet.jetbrains.net/docs/DOC-181</a></li>
<li>IDEA license key: <a href="http://devnet.jetbrains.net/docs/DOC-200">http://devnet.jetbrains.net/docs/DOC-200</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Infinitest</title>
		<link>http://blog.jayway.com/2011/09/21/infinitest/</link>
		<comments>http://blog.jayway.com/2011/09/21/infinitest/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 20:20:06 +0000</pubDate>
		<dc:creator>Anders Eriksson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[junit]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9572</guid>
		<description><![CDATA[The Infinitest Eclipse plug-in looks for unit tests and have them run as soon as changes are detected. Just as modern IDEs have provided automatic compilation for ages this can now also be provided for unit testing. The test outcome shows up as a green or red bar in the bottom of the Eclipse application [...]]]></description>
			<content:encoded><![CDATA[<p>The <a title="Infinitest" href="http://infinitest.github.com/">Infinitest</a> Eclipse plug-in looks for unit tests and have them run as soon as changes are detected. Just as modern IDEs have provided automatic compilation for ages this can now also be provided for unit testing.</p>
<p>The test outcome shows up as a green or red bar in the bottom of the Eclipse application window. The plugin also gives more feedback. In case of failing test the failing line of code in the unit test shows up with a "problem" icon just as a compilation error would look like. Doing mouse-over on the problem icon you will get the failing assert message. This feature I have noticed in recent versions of Eclipse so try to update to the latest Eclipse if you don't see this happen.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/infinitest12.png" rel="lightbox"><img class="alignnone size-full wp-image-9591" title="infinitest1" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/infinitest12.png" alt="" width="640" height="243" /></a></p>
<p>The problem indicator is quite powerful and allows a higher level of TDD. When doing pure TDD you write a failing test first. This would make Infinitest mark your assert statement as problematic until you save a working implementation of your tested code. This allows a very focused <em>write failing test / write implementation</em>-loop.</p>
<p>Infinitest operates independently from the JUnit view in Eclipse. As Infinitest is activated as soon as source code is saved while JUnit is run when initiated by the developer the state shown by either system is often out of sync. I have also experienced that the Infinitest fails to "re-test" but then a project clean brings it back on track. Even if there are quirks I think Infinitest is useful for my daily work and it really promotes TDD.</p>
<p>The plug-in is available on update site http://infinitest.github.com/ and if you are using SpringSource Tool Suite (STS) the plug-in is also available in STS's  extension list.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/21/infinitest/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Multipart Form Data File Uploading Made Simple with REST Assured</title>
		<link>http://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/</link>
		<comments>http://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 16:59:53 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9349</guid>
		<description><![CDATA[From a client perspective it has always seemed to me that uploading a large file or stream to a server using multi-part form data encoding in Java is overly complex. To address this I implemented support for it in REST Assured 1.3. Example Let's say you have a simple HTML page that performs file-uploading from [...]]]></description>
			<content:encoded><![CDATA[<p>From a client perspective it has always seemed to me that uploading a large file or stream to a server using <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2">multi-part form data encoding</a> in Java is overly complex. To address this I implemented support for it in <a href="http://code.google.com/p/rest-assured/">REST Assured</a> 1.3.</p>
<h2>Example</h2>
<p>Let's say you have a simple HTML page that performs file-uploading from a browser like this:</p>
<pre>
&lt;html&gt;
&lt;body&gt;
	&lt;form id=&quot;upload&quot; action=&quot;/fileUpload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
		&lt;input type=&quot;file&quot; name=&quot;file&quot; size=&quot;40&quot;&gt;
		&lt;input type=submit value=&quot;Upload!&quot;&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>We also assume that we have a server that receives the file and return a JSON response like this if everything was ok:</p>
<pre class="javascript">&nbsp;
<span style="color: #66cc66;">&#123;</span> <span style="color: #3366CC;">&quot;fileUploadResult&quot;</span> : <span style="color: #3366CC;">&quot;OK&quot;</span> <span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now let's use REST Assured to upload a file and assert that the upload was OK:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</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%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/home/johan/some_large_file.bin&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;fileUploadResult&quot;</span>, is<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;OK&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">post</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/fileUpload&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>With so little code you've now managed to POST a large file using multi-part form data encoding to the server and asserted that the expected JSON bundled in the response body was correct.</p>
<p>But how can this work? We haven't even specified a <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.2">control name</a>? Well if you don't define a control name specifically REST Assured will default to "file". In many cases this is of course not the case. For example let's say we change the control name in the HTML form to "file2" instead:</p>
<pre>
&lt;html&gt;
&lt;body&gt;
	&lt;form id=&quot;upload&quot; action=&quot;/fileUpload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
		&lt;input type=&quot;file&quot; name=&quot;file2&quot; size=&quot;40&quot;&gt;
		&lt;input type=submit value=&quot;Upload!&quot;&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>REST Assured still makes it simple:</p>
<pre class="java">&nbsp;
given<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file2&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/home/johan/some_large_file.bin&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;fileUploadResult&quot;</span>, is<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;OK&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">post</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/fileUpload&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Multiple parts</h2>
<p>You can even send multiple files, streams, byte-arrays and form parameters in the same request:</p>
<pre class="java">&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInputStream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">InputStream</span></a> inputStream = ..
&nbsp;
<span style="color: #006600;">given</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file1&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/home/johan/some_large_file.bin&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file2&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AFile+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">File</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/home/johan/some_other_large_file.bin&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">multiPart</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;file3&quot;</span>, <span style="color: #ff0000;">&quot;file_name.bin&quot;</span>, inputStream<span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">formParam</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;name&quot;</span>, <span style="color: #ff0000;">&quot;value&quot;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">expect</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;fileUploadResult&quot;</span>, is<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;OK&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">post</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/advancedFileUpload&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Summary</h2>
<p>As you've hopefully seen it's very simple do multi-part form data uploading with REST Assured. Credits should of course also go to <a href="http://hc.apache.org/">Apache HTTP Client</a> for making it possible. To get started with REST Assured today just visit the <a href="http://code.google.com/p/rest-assured/">web-site</a>. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create &#8216;native&#8217; Java applications on OS X and Windows using Maven plugins</title>
		<link>http://blog.jayway.com/2011/08/15/create-native-java-applications-on-os-x-and-windows-using-maven-plugins/</link>
		<comments>http://blog.jayway.com/2011/08/15/create-native-java-applications-on-os-x-and-windows-using-maven-plugins/#comments</comments>
		<pubDate>Mon, 15 Aug 2011 09:07:21 +0000</pubDate>
		<dc:creator>Tobias Södergren</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[desktop]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[native]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9190</guid>
		<description><![CDATA[When building a desktop application, the target audience usually expects an executable to when launching it. If the application is written in Java you have the options to create a batch file to launch it, create an executable jar file, compile the application as a native application or wrap the application using a native 'launcher'. [...]]]></description>
			<content:encoded><![CDATA[<p>When building a desktop application, the target audience usually expects an executable to when launching it. If the application is written in Java you have the options to create a batch file to launch it, create an executable jar file, compile the application as a native application or wrap the application using a native 'launcher'. This post will result in a maven pom for dealing with the last option, it may be used in both Windows and OS X environments.</p>
<p>The pom is configured to use two different plugins depending on which operating system that is executing it.<br />
On Windows, a <a href="http://launch4j.sourceforge.net/">Launch4j</a> project <a href="http://alakai.org/reference/plugins/launch4j-plugin-usage.html">plugin</a> will be used. On OS X the <a href="http://mojo.codehaus.org/osxappbundle-maven-plugin/">osxappbundle</a> plugin is used, which creates an OS X application directory structure and uses the JavaApplicationStub binary for launching the application.</p>
<p>The <code>&lt;profile&gt;</code> tag is used for deciding which plugin to use depending on operating system.</p>
<p>The pom also points out different application icons for the binaries, OS X requires the icon to be in the <a href="http://en.wikipedia.org/wiki/Apple_Icon_Image_format">icns</a> and windows in the <a href="http://en.wikipedia.org/wiki/ICO_(file_format)">ico</a> format.</p>
<p>The wrapped application has a main class in the file <code>com.jayway.wrappedapplication.Launcher</code></p>
<h2>The pom.xml</h2>
<pre class="brush:xml">
<project 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/maven-v4_0_0.xsd">
  <modelversion>4.0.0</modelversion>
  <groupid>com.jayway.wrappedapplication</groupid>
  <artifactid>launcher</artifactid>
<packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>launcher</name>
  <url>http://maven.apache.org</url>
<profiles>
<profile>
      <id>windows-deploy</id>
      <activation>
        <os>
          <family>Windows</family>
        </os>
      </activation>
      <build>
<plugins>
<plugin>
            <groupid>org.bluestemsoftware.open.maven.plugin</groupid>
            <artifactid>launch4j-plugin</artifactid>
            <version>1.5.0.0</version>
            <executions>
              <execution>
                <id>launch4j</id>
<phase>verify</phase>
                <goals>
                  <goal>launch4j</goal>
                </goals>
                <configuration>
                  <dontwrapjar>false</dontwrapjar>
<headertype>gui</headertype>
                  <outfile>${project.build.directory}/relauncher-${project.version}.exe</outfile>
                  <jar>${project.build.directory}/${project.build.finalName}.jar</jar>
                  <errtitle>Launcher</errtitle>
                  <jre>
                    <minversion>1.6.0</minversion>
                  </jre>
                  <classpath>
                    <mainclass>com.jayway.wrappedapplication.Launcher</mainclass>
                    <adddependencies>false</adddependencies>
<precp>anything</precp>
                  </classpath>
                  <icon>${basedir}/build-resources/win/icons/application.ico</icon>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
<profile>
      <activation>
        <os>
          <family>mac</family>
        </os>
      </activation>
      <build>
<plugins>
<plugin>
            <groupid>org.codehaus.mojo</groupid>
            <artifactid>osxappbundle-maven-plugin</artifactid>
            <version>1.0-alpha-2</version>
            <configuration>
              <mainclass>com.jayway.wrappedapplication.Launcher</mainclass>
              <iconfile>${basedir}/build-resources/osx/icons/application.icns</iconfile>
            </configuration>
            <executions>
              <execution>
<phase>package</phase>
                <goals>
                  <goal>bundle</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>
</pre>
<p>And that's it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/08/15/create-native-java-applications-on-os-x-and-windows-using-maven-plugins/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Apache Camel automatic type conversion</title>
		<link>http://blog.jayway.com/2011/08/12/apache-camel-automatic-type-conversion/</link>
		<comments>http://blog.jayway.com/2011/08/12/apache-camel-automatic-type-conversion/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 08:05:58 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[camel]]></category>
		<category><![CDATA[integration]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9172</guid>
		<description><![CDATA[Apache Camel has good support for type conversion and it is easy to add your own type converters. In this blog post I'll show how to create a generic type converter using reflection. Type conversion is done by Camel either when you explicitly tell Camel to perform conversion or in some cases where Camel detects [...]]]></description>
			<content:encoded><![CDATA[<p>Apache Camel has good support for type conversion and it is easy to add your own type converters. In this blog post I'll show how to create a generic type converter using reflection.</p>
<p>Type conversion is done by Camel either when you explicitly tell Camel to perform conversion or in some cases where Camel detects that a type conversion is needed. For example in this case Camel tries to perform type conversion from SourceType to TargetType:</p>
<pre class="brush:java">
public class SourceType {
    private final int value;

    public SourceType(int value) {
        this.value = value;
    }
}
public class TargetType {
    private final int value;

    public TargetType(int value) {
        this.value = value;
    }
}
public interface Service {
    public void call(TargetType value);
}
...
from("direct:call").bean(service, "call");
...
template.requestBody("direct:call", new SourceType(17));
</pre>
<p>This will fail since there is no type converter registered to handle conversion to TargetType. What if TargetType has a constructor taking a SourceType:</p>
<pre class="brush:java">
public TargetType(SourceType source) {
    this.value = source.getValue();
}
</pre>
<p>But this will also fail! My solution is to add a FallbackConverter that can handle this scenario, that is the target type having a single argument constructor taking the source type. The code looks like this:</p>
<pre class="brush:java">
package com.jayway.camel.typeconverter;

@Converter
public class UsingConstructor {
    @SuppressWarnings("unchecked")
    @FallbackConverter
    public static &lt;T> T convertTo(Class&lt;T> type, Object value, TypeConverterRegistry registry) throws Throwable {
        for (Constructor&lt;?> c : type.getConstructors()) {
            Class&lt;?>[] types = c.getParameterTypes();
            if (types.length == 1 && types[0].isAssignableFrom(value.getClass())) {
                    return (T) c.newInstance(value);
            }
        }
        return null;
    }
}
</pre>
<p>A couple of things to notice:</p>
<ul>
<li>The class has the @Converter annotation</li>
<li>The method has the @FallbackConverter</li>
<li>The signature of the method</li>
</ul>
<p>You also need to include file <i>META-INF/services/org/apache/camel/TypeConverter</i> in your classpath that contains the package name. This allows Camel to automatically discover the type converter class.</p>
<pre class="brush:java">
com.jayway.camel.typeconverter
</pre>
<p>Here is an <a href="https://github.com/jankronquist/AirportWeather/blob/master/src/test/java/com/jayway/camel/typeconverter/UsingReflectionIntegrationTest.java">integration test showing this example</a>. I have also implemented a type converter that checks if the source type has a no argument method returning the target type. The source code for <a href="https://github.com/jankronquist/AirportWeather/tree/master/src/main/java/com/jayway/camel/typeconverter">both type converters</a> are available at GitHub.</p>
<p>Notice that this is just a demo of the capabilities of fallback converters. You have to decide if this approach is appropriate in your project. It might not be desirable to have a direct dependency between the TargetType and the SourceType. The overhead of reflection might be too high or it might have unintended consequences. For example the <a href="https://github.com/jankronquist/AirportWeather/blob/master/src/main/java/com/jayway/camel/typeconverter/UsingMethod.java">UsingMethod</a> converter has the unintended consequence of finding and using the toString() method when a conversion to String is needed. The <a href="https://github.com/jankronquist/AirportWeather/blob/master/src/main/java/com/jayway/camel/typeconverter/UsingConstructor.java">UsingConstructor</a> is probably faster and safer since there are usually fewer constructors than public methods. </p>
<p>See the <a href="http://camel.apache.org/type-converter.html">Camel documentation for type converts</a> for more information.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/08/12/apache-camel-automatic-type-conversion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OSGi quick start</title>
		<link>http://blog.jayway.com/2011/07/15/osgi-quick-start/</link>
		<comments>http://blog.jayway.com/2011/07/15/osgi-quick-start/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 15:20:04 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[karaf]]></category>
		<category><![CDATA[osgi]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9109</guid>
		<description><![CDATA[OSGi has been looking promising for a long time, but I have felt that getting started have been really complicated and deploying dependencies have been messy, in particular for transitive dependencies. While I was looking into deployment options for Apache Camel I realized that a lot has happened with OSGi since last I looked. In [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/OSGi">OSGi</a> has been looking promising for a long time, but I have felt that getting started have been really complicated and deploying dependencies have been messy, in particular for transitive dependencies. While I was looking into deployment options for Apache Camel I realized that a lot has happened with OSGi since last I looked. In particular <a href="http://karaf.apache.org/">Apache Karaf</a> really simplifies OSGi deployment with two useful <a href="http://karaf.apache.org/manual/2.2.2/users-guide/provisioning.html">provisioning features</a>:</p>
<ul>
<li><b>Maven URL handler</b> that allows deployment directly from a Maven repository</li>
<li><b>Features</b> that allow grouping of OSGi bundles</li>
</ul>
<p>Although these features are not part of the OSGi standard, it at least makes my life easier and I believe that something similar will become part of the standard since Spring DM and Apache Aries also have similar concepts. I'll just show how to create a blank OSGi project and deploy in Karaf:</p>
<pre>
mvn org.ops4j:maven-pax-plugin:create-bundle -Dpackage=com.jayway.osgi.helloworld
cd com.jayway.osgi.helloworld/
mvn clean install
</pre>
<p>Now you need to <a href="http://karaf.apache.org/index/community/download.html">download Karaf</a>, unzip and then:</p>
<pre>
cd $KARAF_HOME
bin/karaf
osgi:install --start mvn:com.jayway/com.jayway.osgi.helloworld/1.0-SNAPSHOT
</pre>
<p>The output will be (it is not a completely blank project!):</p>
<pre>
STARTING com.jayway.osgi.helloworld
REGISTER com.jayway.osgi.helloworld.ExampleService
</pre>
<p>To generate an Eclipse project:</p>
<pre>
mvn org.ops4j:maven-pax-plugin:eclipse
</pre>
<p>Some links:</p>
<ul>
<li>Apache Karaf have a good <a href="http://karaf.apache.org/manual/2.2.2/quick-start.html">quick start page</a></li>
<li><a href="http://camel.apache.org/tutorial-osgi-camel-part1.html">Apache Camel OSGi tutorial</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/07/15/osgi-quick-start/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apache Camel and SOAP</title>
		<link>http://blog.jayway.com/2011/07/14/apache_camel_and_soap/</link>
		<comments>http://blog.jayway.com/2011/07/14/apache_camel_and_soap/#comments</comments>
		<pubDate>Thu, 14 Jul 2011 16:13:37 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[camel]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[sample]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9090</guid>
		<description><![CDATA[To learn more about Apache Camel I have implemented a non-trivial integration scenario using freely available SOAP web services to create a service that can return the weather at an airport. The webservices are: The Airport Information Webservice to find the location of an airport The National Digital Forecast Database Webservice provided by http://www.weather.gov/ to [...]]]></description>
			<content:encoded><![CDATA[<p>To learn more about <a href="http://camel.apache.org/">Apache Camel</a> I have implemented a non-trivial integration scenario using freely available SOAP web services to create a service that can return the weather at an airport. </p>
<p>The webservices are:</p>
<ul>
<li>The <a href="http://www.webservicex.net/WS/WSDetails.aspx?WSID=20&CATID=7">Airport Information Webservice</a> to find the location of an airport</li>
<li>The <a href="http://www.nws.noaa.gov/forecasts/xml/">National Digital Forecast Database Webservice</a> provided by http://www.weather.gov/ to find the weather at a location</li>
</ul>
<p>My goals have been:</p>
<ul>
<li>Use web services from different providers</li>
<li>Be able to test the routes</li>
<li>Include error handling</li>
<li>Try various methods for transformation</li>
</ul>
<p>So far I'm quite happy with the results and impressed with the flexibility of Apache Camel. Have a look at the code available at <a href="https://github.com/jankronquist/AirportWeather">AirportWeather project @ GitHub</a> and let me know what you think.</p>
<h2>Routes</h2>
<p>The complete route looks like this:</p>
<pre class="brush:java">
from("direct:getMaximumTemperaturAtAirport")
	.to("direct:getAirportInformationByAirportCode")
	.to("direct:fromAirportInformationToLocation")
	.to("direct:fromLocationToNDFD")
	.to("direct:fromNDFDToTempInCelcius");
</pre>
<p>The flow is synchronous and each step is implemented in a separate route to be testable, for example I can stub out entire steps of the route.   </p>
<p>A step can be further broken down into even smaller routes, for example separating the call to the web service and the error handling:</p>
<pre class="brush:java">
from("direct:getAirportInformationByAirportCode")
	.to("direct:invokeGetAirportInformationByAirportCode")
	.choice()
		.when().xpath("count(/NewDataSet/Table)=0").rollback("No Airport found")
		.otherwise();
</pre>
<h2>Calling a SOAP web service</h2>
<p>To call the web service I use <a href="http://camel.apache.org/spring-web-services.html">Spring WS</a>. The reason I didn't use <a href="http://camel.apache.org/cxf.html">CXF</a> is that the NDFD is using RPC encoding which is an old web standard <a href="http://stackoverflow.com/questions/412772/java-rpc-encoded-wsdls-are-not-supported-in-jaxws-2-0">not supported by the current version of CXF</a>. The XML payload is generated using a <a href="http://camel.apache.org/velocity.html">Velocity template</a>. This works well in this case, but later I want to compare this to JAXB generated objects from an XML schema.</p>
<pre class="brush:java">
from("direct:invokeGetAirportInformationByAirportCode")
    .to("velocity:getAirportInformationByAirportCode.vm")
    .to("spring-ws:http://www.webservicex.net/airport.asmx?soapAction=http://www.webserviceX.NET/
</pre>
<h2>Transformation</h2>
<p>Camel has very flexible support for transformation and un/marshalling. I have tried a couple of different variations. Registering a object and simply calling a method:</p>
<pre class="brush:java">
SimpleRegistry registry = new SimpleRegistry();
registry.put("temperatureTransformer", new TemperatureTransformer());
...
.transform().method("temperatureTransformer", "fromFahrenheitToCelsius");
</pre>
<p>Let Camel figure out which method to call:</p>
<pre class="brush:java">
registry.put("cdataTransformer", new CDataTransformer());
...
.transform().method("cdataTransformer");
</pre>
<p>XML unmarshalling using <a href="http://camel.apache.org/xstream.html">XStream</a>:</p>
<pre class="brush:java">
XStreamDataFormat xmlToAirPortLocation() {
    XStream xstream = new MissingFieldIgnoringXStream();
    xstream.alias("Table", AirportLocation.class);
    XStreamDataFormat dataFormat = new XStreamDataFormat(xstream);
    return dataFormat;
}
...
.unmarshal(xmlToAirPortLocation())
</pre>
<p><a href="http://camel.apache.org/xpath.html">XPath</a> transformation:</p>
<pre class="brush:java">
.transform().xpath("/NewDataSet/Table[1]")
</pre>
<p>Let Camel figure out <a href="http://camel.apache.org/type-converter.html">how to perform the conversion</a>:</p>
<pre class="brush:java">
.convertBodyTo(Integer.class)
</pre>
<h2>Stubbing routes</h2>
<p>When testing I used <a href="http://camel.apache.org/advicewith.html">AdviceWith</a> to stub out a route in the test case. I'm not really sure if this is the best way, but it works. </p>
<pre class="brush:java">
context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
    @Override
    public void configure() throws Exception {
        interceptSendToEndpoint(someEndpoint)
            .skipSendToOriginalEndpoint().to("velocity:AirportResult-empty.xml");
    }
});
</pre>
<p>To make the stub actually override the endpoint it is important to call skipSendToOriginalEndpoint. I use <a href="http://camel.apache.org/velocity.html">Velocity</a> to generate a static reply.  See the <a href="https://github.com/jankronquist/AirportWeather/blob/master/src/test/java/com/jayway/airportweather/AirportWeatherTest.java">AirportWeatherTest</a> for more details.</p>
<h2>Handling bad results</h2>
<p>To verify the result of the invoked web service I have used a choice and rollback to signal the error, for example when the airport does not exist:</p>
<pre class="brush:java">
.choice()
    .when().xpath("count(/NewDataSet/Table)=0").rollback("No Airport found")
    .otherwise();
</pre>
<h2>Future Camel rides</h2>
<p>Things I will investigate further:</p>
<ul>
<li>Other ways to stub out routes</li>
<li>Making use of <a href="http://camel.apache.org/camel-test.html">camel-test</a></li>
<li>Use CXF and JAXB to avoid creating XML payloads using Velocity (perhaps for some other web service)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/07/14/apache_camel_and_soap/feed/</wfw:commentRss>
		<slash:comments>4</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>Secure JMS, Spring and WebLogic &#8211;  a One Click Workaround</title>
		<link>http://blog.jayway.com/2011/06/26/secure-jms-spring-and-weblogic-a-one-click-workaround/</link>
		<comments>http://blog.jayway.com/2011/06/26/secure-jms-spring-and-weblogic-a-one-click-workaround/#comments</comments>
		<pubDate>Sun, 26 Jun 2011 09:12:56 +0000</pubDate>
		<dc:creator>Olof Åkesson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[spring jms]]></category>
		<category><![CDATA[weblogic]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8879</guid>
		<description><![CDATA[In our current assignment we are building a messaging based integration solution using Spring Integration and deploying it on WebLogic. In general, this has been quite a good experience as Spring Integration is a pleasant framework to work with from a developer's perspective and the customer is happy that it will be rolled out on [...]]]></description>
			<content:encoded><![CDATA[<p>In our current assignment we are building a messaging based integration solution using <a href="http://www.springsource.org/spring-integration">Spring Integration</a> and deploying it on <a href="http://www.oracle.com/technetwork/middleware/weblogic/overview/index.html">WebLogic</a>. In general, this has been quite a good experience as Spring Integration is a pleasant framework to work with from a developer's perspective and the customer is happy that it will be rolled out on WebLogic as this is their strategic platform.</p>
<p>When it was time to implement the requirement for secure JMS (meaning authentication and authorization) we were sure that this would be easy. After all, even if security is not part of the JMS standard, Spring usually provides support for integrating with the application server in a consistent way. </p>
<h2>A simple configuration change?</h2>
<p>Since we retrieve connections from the connection factory it should be as simple as adding some properties to the JNDI-lookup like this:</p>
<pre class="brush: xml;">
<jee:jndi-lookup id="connectionFactory" jndi-name="weblogic.jms.XAConnectionFactory">
    <jee:environment>
      java.naming.security.principaluser=jmsuser
      java.naming.security.credentials=password
   </jee:environment>
</jee:jndi-lookup>
</pre>
<h2>Not so simple after all...</h2>
<p>Unfortunately when we tested this we were greeted with: "JMSSecurityException: Access Denied To Resource". This was discouraging but since using secure JMS with Spring and WebLogic should be quite a common use case we were still confident that there would be an accepted solution available.</p>
<p>Indeed, we were not alone. There were at least three JIRA-issues opened for this problem and a number of forum threads:</p>
<ul>
<li><a href="https://jira.springsource.org/browse/SPR-2941">Support secure JMS queue access on WebLogic - SPR-2941</a></li>
<li><a href="https://jira.springsource.org/browse/SPR-4720">DefaultMessageListenerContainer failover to work with Weblogic JMS and security credentials - SPR-4720</a></li>
<li><a href="https://issues.springsource.org/browse/SPR-5869">exposeAccessContext doesn't resolve the issues with secure JMS and WebLogic. - SPR-5869</a></li>
<li><a href="http://forum.springsource.org/showthread.php?73622-Secure-JMS-and-Spring-with-WebLogic">Secure-JMS-and-Spring-with-WebLogic</a></li>
<li><a href="http://forum.springsource.org/showthread.php?62373-weblogic-10-standalone-jms-client">weblogic-10-standalone-jms-client</a></li>
<li><a href="http://forum.springsource.org/showthread.php?63338-excessive-JNDI-lookups-on-weblogic">excessive-JNDI-lookups-on-weblogic</a></li>
</ul>
<p>It was evident that this was not going to be so easy after all. Basically, the root of the problem seems to be that WebLogic does not allow the InitialContext created in one thread to be used in another thread which is what happens when Spring does the lookup on the connection factory in one thread and then tries to retrieve a connection in another. Although the problem has been known for at least <a href="https://jira.springsource.org/browse/SPR-2941">five years</a>, there is still no real solution.</p>
<h2>A solution, sort of...</h2>
<p>The accepted way (and the only one we found in the forums that would work for us) of getting around this if you are determined to use WebLogic JMS together with Spring is to use a decorator on the connection factory to create the InitialContext with the required security credentials for each call to "createConnection()". This way, the credentials will be bound to the thread that is executing and WebLogic will not complain. The details of the implementation <a href="http://forum.springsource.org/showthread.php?62373-weblogic-10-standalone-jms-client">are here</a>. </p>
<p>While the above solution worked well (thanks <a href="http://forum.springsource.org/member.php?38446-honeybunny">Honeybunny!</a>) we were not really happy with it. Introducing a decorator felt invasive. Furthermore there is a potential performance issue in creating an InitialContext for every call to "createConnection()" which could of course be solved by introducing a threadlocal cache to avoid unnecessary calls but the real problem lies in the way that users are associated with threads which, as the <a href="http://download.oracle.com/docs/cd/E13222_01/wls/docs61/jndi/jndi.html#467275">WebLogic documentation</a> makes quite clear, needs to be handled carefully:</p>
<blockquote><p>"When you create a JNDI Context with a username and password, you associate a user with a thread. When the Context is created, the user is pushed onto the context stack associated with the thread. Before starting a new Context on the thread, you must close the first Context so that the first user is no longer associated with the thread. Otherwise, users are pushed down in the stack each time a new context created. This is not an efficient use of resources and may result in the incorrect user being returned by ctx.lookup() calls. "</p></blockquote>
<p>Making sure the context is closed is certainly possible but it seemed to us that we were going in the wrong direction in writing custom code to get around something that should basically "just work" as we wanted to deliver a maintainable solution. </p>
<h2>A one-click solution</h2>
<p>After trying the different proposed solutions in the JIRA and forum threads we decided to check if there wasn't some way to solve this by configuring WebLogic as it seems to have configuration alternatives for just about everything. In the admin console we noticed something promising. If you click on one of your deployed applications to get to the "Overview"-tab there is a field called "Deployment Principal Name" where you can specify the principal (user) that should be used during startup and shutdown if you need something else than the anonymous principal. This looked like it was worth a try so we set the principal to a user with the privileges for connecting to the JMS destination, restarted the server and - it worked! </p>
<p>Click the image to see the configuration in the console:<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/jmsconf2.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/jmsconf2-300x159.png" alt="Deployment Principal Name" title="Deployment Principal Name" width="300" height="159" class="aligncenter size-medium wp-image-8926" /></a></p>
<p>Of course there are other ways of doing this configuration and since operations tend not to like the "point and click" deployment model the best way is to incorporate it in your deployment <a href="http://download.oracle.com/docs/cd/E12840_01/wls/docs103/config_scripting/reference.html#wp1024285">scripts with WLST</a>. </p>
<h2>Final words</h2>
<p>Some caveats are in order. We are aware that this is still only a workaround and certainly not the final solution to the problem. </p>
<ul>
<li>First of all, this was what worked in our case and your mileage may vary. For one thing we are using the <a href="http://download.oracle.com/docs/cd/E13222_01/wls/docs103/commonj/commonj.html#wp1058124">commonj.WorkManager API</a> and not a thread pool managed by the Spring container.</li>
<li>Obviously, this will only work for applications that are deployed in the application server. If you have a JMS-client that uses Spring JMS that is not deployed in WebLogic, you will need some other workaround.</li>
<li>In our case, we have a simple deployment setup where we are not using a cluster and distributed JMS destinations so we haven't tested if that will work but we think it's likely that there will be issues.</li>
</ul>
<p>Anyway, we hope that at least someone will find this solution helpful. Personally, we would have appreciated not having to spend nearly a week reading old forum threads figuring out what would work or not. </p>
<p>And as a final note; if all else fails you can always <a href="http://activemq.apache.org/">switch to Active MQ</a> <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/06/26/secure-jms-spring-and-weblogic-a-one-click-workaround/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>
	</channel>
</rss>

