<?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; spring</title>
	<atom:link href="http://blog.jayway.com/tag/spring/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>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>Spring Web Flow + Roo &#8211; a simple example</title>
		<link>http://blog.jayway.com/2011/05/18/spring-web-flow-roo-a-simple-example/</link>
		<comments>http://blog.jayway.com/2011/05/18/spring-web-flow-roo-a-simple-example/#comments</comments>
		<pubDate>Wed, 18 May 2011 05:30:34 +0000</pubDate>
		<dc:creator>Anders Davoust</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[roo]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring web flow]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8477</guid>
		<description><![CDATA[The other day I was trying to implement a new user registration. The goal was to validate user input data and save it to a database. I am using Spring Roo in my project so Spring Web Flow would be a good candidate for the task. Since Roo has support for Web Flow I thought [...]]]></description>
			<content:encoded><![CDATA[<p>The other day I was trying to implement a new user registration. The goal was to validate user input data and save it to a database. I am using Spring Roo in my project so Spring Web Flow would be a good candidate for the task. Since Roo has support for Web Flow I thought this would be an easy task. However, since I am not familiar with Web Flow it took me quite some time to figure it out so I thought I should share.</p>
<p><strong>Setup</strong><br />
I have used Roo 1.1.2.RELEASE for this tutorial and I started out with this simple Roo project.</p>
<pre class="brush:xml">
project --topLevelPackage com.jayway.webflowexample
persistence setup --database H2_IN_MEMORY --provider HIBERNATE
entity --class ~.domain.Account
field string --fieldName username --sizeMin 6 --sizeMax 40
field string --fieldName password --sizeMin 6 --sizeMax 40
controller all --package ~.web
web flow --flowName registration
perform eclipse
</pre>
<p>Start the project in your favorite container and surf to http://localhost:8080/webflowexample/registration and you should see the initial state:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/initial6.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/initial6.png" alt="" title="initial" width="591" height="248" class="alignleft size-full wp-image-8351" /></a></p>
<p><strong>Web Flow</strong><br />
The "web flow --flowName registration" command will setup the needed configuration and create a sample web flow. To update with persistence do the following:</p>
<p>In the file src/main/webapp/WEB-INF/views/registration/flow.xml  </p>
<ul>
<li>add creation of the new user account and save it in the flow scope (line 1-3)</li>
<li> attach the model to the view by adding model="account" to the view-state tag (line 6)</li>
<li>save the account in the end-state (line 17-19)</li>
</ul>
<p>Put together it looks like this:</p>
<pre class="brush:xml">
<on-start>
	<evaluate expression="new com.jayway.webflowexample.domain.Account()" result="flowScope.account"/>
</on-start>

<!-- A sample view state -->
<view-state id="view-state-1" view="registration/view-state-1" model="account">
<transition on="success" to="view-state-2"></transition>
<transition on="cancel" to="end-state"></transition>
</view-state>

<view-state id="view-state-2" view="registration/view-state-2">
<transition on="cancel" to="end-state"></transition>
</view-state>

<!-- A sample end state -->
<end-state id="end-state" view="registration/end-state">
	<on-entry>
		<evaluate expression="account.persist()" result="flowScope.account"></evaluate>
	</on-entry>
</end-state>
</pre>
<p>If you want to encode the password before storing it use a service instead for line 17-19 and implement it there. A bean with id "userRegistrationService" must be registered in the application context for the below snippet to work.</p>
<pre class="brush:xml">
<on-entry>
	<evaluate expression="userRegistrationService.registerUser(account)" result="flowScope.account"></evaluate>
</on-entry>
</pre>
<p><strong>View</strong></p>
<p>In the file src/main/webapp/WEB-INF/views/registration/view-state-1.jspx </p>
<ul>
<li>change the form tag to form:form, add the attribute modelAttribute to this tag (line 1) and make sure to add the form xml namespace xmlns:form="http://www.springframework.org/tags/form"</li>
<li>add user input fields and tie them to the model and add display of error messages in case there are validation errors (line 3-16)</li>
</ul>
<p>Put together this is how the form tag would look:</p>
<pre class="brush:xml">
<form:form modelAttribute="account">
<div class="submit">
<table>
<tr>
<td>Username:</td>
<td>
<form:input path="username"></form:input>
<form:errors path="username"></form:errors></td>
</tr>
<tr>
<td>Password:</td>
<td>
<form:password path="password"></form:password>
<form:errors path="password"></form:errors></td>
</tr>
</table>

         <spring:message var="cancel" code="button_cancel" htmlEscape="false"></spring:message>
        <spring:message var="proceed" code="button_proceed" htmlEscape="false"></spring:message>
<input type="submit" id="cancel" name="_eventId_cancel" value="${fn:escapeXml(cancel)}" ></input>
<input type="submit" id="success" name="_eventId_success" value="${fn:escapeXml(proceed)}" ></input>
</div>
</form:form>
</pre>
<p>The account object needs to be serializable so add @RooSerializable to the Account class.<br />
Make sure to have the Roo shell running in the background when adding this annotation.</p>
<p><strong>Validation</strong></p>
<p>In the 2.3.0.RELEASE version of Spring Web Flow you can take advantage of the annotations of the fields in the Account class for validation. If we take a look at the Account class we see that the username and the password have to be between 6 and 40 characters (line 7 and 10). </p>
<pre class="brush:java">
@RooJavaBean
@RooToString
@RooEntity
@RooSerializable
public class Account {

    @Size(min = 6, max = 40)
    private String username;

    @Size(min = 6, max = 40)
    private String password;
}
</pre>
<p>To activate this validation update your pom.xml to use 2.3.0.RELEASE for web flow and add the following to your webflow-config.xml:</p>
<pre class="brush:xml">
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</pre>
<p>And add the validator bean as attribute to the flowBuilderServices bean:</p>
<pre class="brush:xml">
<webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="mvcViewFactoryCreator" development="true" validator="validator"/>
</pre>
<p>Replace the schema location</p>
<pre class="brush:xml">

http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
</pre>
<p>with</p>
<pre class="brush:xml">

http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd
</pre>
<p>If you now enter a username or password that is too short you will see a validation error message:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/validation.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/validation.png" alt="" title="validation" width="570" height="226" class="alignleft size-full wp-image-8348" /></a></p>
<p>That's it!<br />
Here's the <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2011/04/WebFlowExample.zip'>code</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/18/spring-web-flow-roo-a-simple-example/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dynamic FTP Client using Apache Camel and Spring</title>
		<link>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/</link>
		<comments>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 16:48:45 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[camel]]></category>
		<category><![CDATA[FTP]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5743</guid>
		<description><![CDATA[I was recently asked to develop an FTP client that could transmit files to various FTP servers as a part of a delivery system in a Java enterprise application. The requirements dictated a flexible implementation: Three different FTP protocols should be supported, namely FTP, FTPS and SFTP It should be possible to transmit different files [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently asked to develop an FTP client that could transmit files to various FTP servers as a part of a delivery system in a Java enterprise application. The requirements dictated a flexible implementation:</p>
<ul>
<li>Three different FTP protocols should be supported, namely <a href="#FTP">FTP</a>, <a href="#FTPS">FTPS</a> and <a href="#SFTP">SFTP</a></li>
<li>It should be possible to transmit different files to several different servers</li>
<li>The files to be sent were generated in runtime, they had different file names and were stored in different directories</li>
</ul>
<p>Basically, I should implement the following interface:</p>
<h4>FtpSender.java</h4>
<p><a name="FtpSender"></a></p>
<pre class="brush:java">
public interface FtpSender {

    /**
     * Uses the {@code ftpProperties} to transmit the provided {@code file} to a remote server
     *
     * @param ftpProperties The FTP properties of the remote server
     * @param file The file to transmit
     */
    void sendFile(FtpProperties ftpProperties, File file);
}
</pre>
<p>where the FtpProperties was another interface:</p>
<h4>FtpProperties.java</h4>
<pre class="brush:java">
public interface FtpProperties {

    /**
     * Gets the protocol
     * @return One of {@code ftp}, {@code ftps} or {@code sftp}
     */
    String getProtocol();

    /**
     * Gets the user name
     * @return The name of the user
     */
    String getUserName();

    /**
     * Gets the password
     * @return The password
     */
    String getPassword();

    /**
     * Gets the FTP host
     * @return The FTP host
     */
    String getHost();

    /**
     * Gets the name of the directory on the server where the file will be transferred
     * @return The name of the remote directory
     */
    String getRemoteDirectory();

    /**
     * Gets the passive mode, e.g. if the server is behind a firewall
     * @return whether or not passive mode should be used
     */
    boolean getPassiveMode();
}
</pre>
<p>Rather than implementing the entire FTP client from scratch, I investigated the capabilities of existing frameworks. Most solutions recommend using an existing FTP framework such as <a href="http://commons.apache.org/net/">Apache Commons / Jakarta Commons Net</a> for FTP and FTPS and then wrap it in a SSH layer like <a href="http://www.jcraft.com/jsch/">Jsch / Java Secure Channel</a> for SFTP. However, soon I discovered <a href="http://camel.apache.org/">Apache Camel</a>, "a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration" (their words). They support a various range of <a href="http://camel.apache.org/components.html">components</a>, anything from XQuery and Atom to XSLT and SQL, just to name a few. To my luck, they also support all three FTP protocols that I needed. </p>
<h2>Fundamentals</h2>
<p>What does the <a href="http://camel.apache.org/ftp2.html">Camel FTP</a> API look like? In its basic form it is a little more than a one-liner:</p>
<h4>FtpRouteBuilder.java</h4>
<p><a name="FtpRouteBuilder"></a></p>
<pre class="brush:java">
public class FtpRouteBuilder extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("file://localDirectory").to("ftp://user@host.com/remoteDirectory?password=secret&passiveMode=true");
    }
}
</pre>
<p>So what is going on here? The <a href="http://camel.apache.org/routebuilder.html">RouteBuilder</a> is one of Camel's core classes that defines the Camel specific <a href="http://camel.apache.org/dsl.html">DSL</a>. In this example, a <a href="http://camel.apache.org/routes.html">Route</a> from the <code>localDirectory</code> to a <code>remoteDirectory</code> over FTP with the provided credentials has been created. As can be seen, it is easy to create and configure different endpoints using <code>String</code> URIs. It should also be mentioned that it is possible to fetch files from the remote FTP server by swapping the URIs in the <code>to</code> and <code>from</code> methods.</p>
<p>A few more lines are needed to activate the route:</p>
<pre class="brush:java">
public static void main(String[]args) throws Exception {
    CamelContext camelContext = new DefaultCamelContext();
    try {
        camelContext.addRoutes(new FtpRouteBuilder());
        camelContext.start();
        // do other stuff...
    }
    finally {
        camelContext.stop();
    }
}
</pre>
<p>A <a href="http://camel.apache.org/camelcontext.html">CamelContext</a> is created for managing the route. The previously described <a href="#FtpRouteBuilder">FtpRouteBuilder</a> is instantiated and added to the camelContext which is subsequently started. As a consequence, any file that is placed in the "localDirectory" folder will be automatically transferred to the "remoteDirectory" of the FTP server while the program is running. </p>
<h2>Adding Configurability</h2>
<p>The requirement of supporting different FTP protocols is solved by changing the URI from <code>ftp://</code> to <code>ftps://</code> or <code>sftp://</code> respectively. It is just as easy to fulfill the second requirement of multiple server support by changing the host, user, port and other parameters of the URI. Likewise, additional settings may be configured by adding more options if needed, see the <a href="http://camel.apache.org/ftp2.html">Camel FTP</a> documentation.</p>
<h2>Adding Dynamism</h2>
<p>The last challenge was to add the dynamic support of selecting source files and destination servers during runtime. The easiest solution is to use another of Camel's base classes, the <a href="http://camel.apache.org/producertemplate.html">ProducerTemplate</a>. Again, the solution is a one-liner:</p>
<pre class="brush:java">
producerTemplate.sendBodyAndHeader("ftp://user@host.com/remoteDirectory?password=secret", file, Exchange.FILE_NAME, file.getName());
</pre>
<p>The <code>sendBodyAndHeader()</code> method name reveals a glimpse of Camel's underlying messaging architecture. The parameters used are the destination URI with additional options, the message body, i.e. the <code>File</code> to be sent, a message header parameter that identifies the last parameter as the name of the file it will have on the remote server once it has been transferred.</p>
<h2>Spring Integration</h2>
<p>With some refactoring and a little Spring magic we have all the bits and pieces needed to implement the previously defined <a href="#FtpSender">FtpSender</a> interface:</p>
<h4>FtpSenderImpl.java</h4>
<pre class="brush:java">
@Service
class FtpSenderImpl implements FtpSender {

    /** Camel URI, format is ftp://user@host/fileName?password=secret&passiveMode=true */
    private static final String CAMEL_FTP_PATTERN = "{0}://{1}@{2}/{3}?password={4}&passiveMode={5}";

    private final ProducerTemplate producerTemplate;

    /**
      * Constructor
      * @param producerTemplate The producer template to be be used
      */
    @Autowired
    FtpSenderImpl(ProducerTemplate producerTemplate) {
        this.producerTemplate = producerTemplate;
    }

    @Override
    public void sendFile(FtpProperties ftpProperties, File file) throws RuntimeException {
        producerTemplate.sendBodyAndHeader(createFtpUri(ftpProperties), file, Exchange.FILE_NAME, fileName);
    }

    /**
      * Creates a Camel FTP URI based on the provided FTP properties
      * @param ftpProperties The properties to be used
      */
    private String createFtpUri(FtpProperties ftpProperties) {
        return MessageFormat.format(CAMEL_FTP_PATTERN,
                ftpProperties.getProtocol(),
                ftpProperties.getUserName(),
                ftpProperties.getHost(),
                ftpProperties.getRemoteDirectory(),
                ftpProperties.getPassword(),
                ftpProperties.getPassiveMode());
    }
}
</pre>
<p>Using the <a href="http://camel.apache.org/spring.html">Camel namespace</a>, the required plumbing work is delegated to the Spring application config:</p>
<h4>spring-config.xml</h4>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"&gt;

    &lt;!-- Let Spring create the Camel context and the Camel template, including lifecycle management such as starting and stopping them --&gt;
    &lt;camel:camelContext id="camelContext"&gt;
        &lt;camel:template id="camelTemplate" /&gt;
    &lt;/camel:camelContext&gt;

    &lt;!-- Use Spring component scan to find the FtpSenderImpl implementation --&gt;
    &lt;context:component-scan base-package="com.jayway.ftp" /&gt;

&lt;/beans&gt;
</pre>
<h2>Conclusions</h2>
<p>Camel and Spring provide a simple, yet configurable, way of implementing a dynamic FTP client.</p>
<h2>Acknowledgments</h2>
<p>Thanks to Claus Ibsen and other members of the <a href="http://camel.apache.org/discussion-forums.html">Apache Camel Forums</a> for providing valuable and rapid support.</p>
<h2>Glossary</h2>
<ul>
<li><a name="FTP"></a><code>FTP</code> File Transfer Protocol</li>
<li><a name="FTPS"></a><code>FTPS</code> FTP Secure is an extension to FTP that adds support for the TLS, Transport Layer Security, and the SSL, Secure Sockets Layer, cryptographic protocols</li>
<li><a name="SFTP"></a><code>SFTP</code> SSH File Transfer Protocol, i.e. FTP over the Secure Shell protocol</li>
</ul>
<h2>References</h2>
<p><a href="http://camel.apache.org/maven/camel-2.2.0/camel-core/apidocs/index.html">Camel API</a><br />
<a href="http://camel.apache.org/components.html">Camel Components</a><br />
<a href="http://camel.apache.org/ftp2.html">Camel FTP</a><br />
<a href="http://camel.apache.org/producertemplate.html">Camel ProducerTemplate</a><br />
<a href="http://camel.apache.org/spring.html">Camel Spring</a><br />
<a href="http://camel.apache.org/why-does-camel-use-too-many-threads-with-producertemplate.html">Camel ProducerTemplate and Spring</a><br />
<a href="http://camel.apache.org/enterprise-integration-patterns.html">Camel Enterprise Integration Patterns</a><br />
<a href="http://camel.apache.org/discussion-forums.html">Camel Forums</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>REST and XML using Spring MVC and Groovy</title>
		<link>http://blog.jayway.com/2010/04/09/rest-and-xml-using-spring-mvc-and-groovy/</link>
		<comments>http://blog.jayway.com/2010/04/09/rest-and-xml-using-spring-mvc-and-groovy/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 14:32:10 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[hateoas]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5319</guid>
		<description><![CDATA[There's one particular thing Groovy is really good for and that is working with XML. When I started playing around with the REST support in the latest version of Spring MVC I wanted to try using Spring for the controller infrastructure and delegate to Groovy for producing XML responses. It turned out this wasn't as [...]]]></description>
			<content:encoded><![CDATA[<p>There's one particular thing Groovy is really good for and that is working with XML. When I started playing around with the REST support in the latest version of Spring MVC I wanted to try using Spring for the controller infrastructure and delegate to Groovy for producing XML responses. It turned out this wasn't as easy as expected.</p>
<p>The built-in support for rendering XML from RESTful web services in Spring is built on top of the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/oxm.html">Marshaller</a> abstraction originally from Spring Web Services (now moved to Spring core). This is a pretty nice abstraction if you want to use one of the existing Object-XML marshalling frameworks (JAXB, Castor, XMLBeans, etc.), but if you want to move out of that box you're pretty much stranded.</p>
<p>I really do want to move out of the box because I think the control and readability greatly improves if you do your XML marshalling in Groovy. It's quite common that the same domain object will need to be marshalled differently depending on the scenario (an object will e.g. quite probably need to be marshalled differently in a detail view than in a list). Also, it is not uncommon that more complicated application logic will be required when rendering the XML; a common example of this is URI generation in 'linked' REST applications (<a href="http://en.wikipedia.org/wiki/HATEOAS">HATEOAS</a>). Hence, Groovy is the perfect choice: Very little code is needed, you are able to include some logic if necessary, and the code written exactly reflects the XML that will be produced. </p>
<h3>The Building Blocks</h3>
<p>I started out by defining a simple interface for a completely generic Marshaller:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> SimpleMarshaller <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> marshal<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AWriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Writer</span></a> writer, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> o<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>I now needed a View implementation to render Model objects using the <code>SimpleMarshaller</code> interface (much of this code is actually borrowed from the Spring <code>MarshallingView</code> - Apache license rocks!):</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SimpleMarshallingView <span style="color: #000000; font-weight: bold;">extends</span> AbstractView <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">static</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> DEFAULT_MODEL_KEY = <span style="color: #ff0000;">&quot;objectToMarshal&quot;</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">boolean</span> AUTOMATIC_FLUSH = <span style="color: #000000; font-weight: bold;">true</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <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> DEFAULT_CHARSET = <span style="color: #ff0000;">&quot;utf8&quot;</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> SimpleMarshaller marshaller;
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> SimpleMarshallingView<span style="color: #66cc66;">&#40;</span>SimpleMarshaller marshaller<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">marshaller</span> = marshaller;
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">void</span> renderMergedOutputModel<span style="color: #66cc66;">&#40;</span>Map&lt;String, Object&gt; model, HttpServletRequest request,
      HttpServletResponse response<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
    <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AByteArrayOutputStream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">ByteArrayOutputStream</span></a> outputStream = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AByteArrayOutputStream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">ByteArrayOutputStream</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3APrintWriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">PrintWriter</span></a> writer = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3APrintWriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">PrintWriter</span></a><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%3AOutputStreamWriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">OutputStreamWriter</span></a><span style="color: #66cc66;">&#40;</span>outputStream, DEFAULT_CHARSET<span style="color: #66cc66;">&#41;</span>, AUTOMATIC_FLUSH<span style="color: #66cc66;">&#41;</span>;
    marshaller.<span style="color: #006600;">marshal</span><span style="color: #66cc66;">&#40;</span>writer, objectToRender<span style="color: #66cc66;">&#40;</span>model<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    response.<span style="color: #006600;">setContentType</span><span style="color: #66cc66;">&#40;</span>getContentType<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    response.<span style="color: #006600;">setContentLength</span><span style="color: #66cc66;">&#40;</span>outputStream.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    FileCopyUtils.<span style="color: #006600;">copy</span><span style="color: #66cc66;">&#40;</span>outputStream.<span style="color: #006600;">toByteArray</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, response.<span style="color: #006600;">getOutputStream</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> objectToRender<span style="color: #66cc66;">&#40;</span>Map&lt;String, Object&gt; model<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> o = model.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>DEFAULT_MODEL_KEY<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>o == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIllegalArgumentException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalArgumentException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Model does not contain the expected key '&quot;</span> + DEFAULT_MODEL_KEY + <span style="color: #ff0000;">&quot;'&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> o;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Next I created an abstract <code>SimpleMarshaller</code> implementation for marshalling using a Groovy <code>MarkupBuilder</code>:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> AbstractMarkupBuilderSimpleMarshaller <span style="color: #000000; font-weight: bold;">implements</span> SimpleMarshaller <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">void</span> marshal<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AWriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Writer</span></a> writer, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> o<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    MarkupBuilder builder = <span style="color: #000000; font-weight: bold;">new</span> MarkupBuilder<span style="color: #66cc66;">&#40;</span>writer<span style="color: #66cc66;">&#41;</span>;
    marshalToBuilder<span style="color: #66cc66;">&#40;</span>builder, o<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #993333;">void</span> marshalToBuilder<span style="color: #66cc66;">&#40;</span>MarkupBuilder builder, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> o<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now all that is left is to create a new Groovy View implementation for specific XML response you want, e.g.:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> UserXmlMarshallingView <span style="color: #000000; font-weight: bold;">extends</span> SimpleMarshallingView <span style="color: #66cc66;">&#123;</span>
  @Autowired
  <span style="color: #000000; font-weight: bold;">public</span> UserXmlMarshallingView<span style="color: #66cc66;">&#40;</span>UriConstructionService uriConstructionService<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> UserXmlMarshaller<span style="color: #66cc66;">&#40;</span>uriConstructionService<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    setContentType<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;application/xml&quot;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">class</span> UserXmlMarshaller <span style="color: #000000; font-weight: bold;">extends</span> AbstractMarkupBuilderSimpleMarshaller <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> UriConstructionService uriConstructionService;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> UserXmlMarshaller<span style="color: #66cc66;">&#40;</span>UriConstructionService uriConstructionService<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">uriConstructionService</span> = uriConstructionService;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> marshalToBuilder<span style="color: #66cc66;">&#40;</span>MarkupBuilder builder, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> user<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      builder.<span style="color: #ff0000;">'user'</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'name'</span>: user.<span style="color: #006600;">name</span>, <span style="color: #ff0000;">'email'</span>: user.<span style="color: #006600;">email</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        user.<span style="color: #006600;">orders</span>.<span style="color: #006600;">each</span> <span style="color: #66cc66;">&#123;</span>
          <span style="color: #ff0000;">'order-ref'</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'dateCreated'</span>: it.<span style="color: #006600;">dateCreated</span>.<span style="color: #006600;">format</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'yyyy-MM-dd hh:mm:ss'</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #ff0000;">'uri'</span>: uriConstructionService.<span style="color: #006600;">orderUri</span><span style="color: #66cc66;">&#40;</span>it<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#125;</span>
      <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Note above that we included some processing logic as well - we get a formatted date and we also make use of a service for producing URIs for referencing sub-entities.</p>
<p>Each individual View implementations now needs to be registered in the <code>DispatcherServlet</code>'s ApplicationContext:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;user&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.jayway.demo.xml.UserXmlMarshallingView&quot;</span><span style="font-weight: bold; color: black;">/&gt;</span></span>
...
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.web.servlet.view.BeanNameViewResolver&quot;</span><span style="font-weight: bold; color: black;">/&gt;</span></span>
&nbsp;</pre>
<p>Since we have defined a <code>BeanNameViewResolver</code> we can now refer to these Views using their bean names when pointing them out from a Controller:</p>
<pre class="java">&nbsp;
@Controller
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserController <span style="color: #66cc66;">&#123;</span>
  @Autowired
  <span style="color: #000000; font-weight: bold;">private</span> Repo repo;
&nbsp;
  @RequestMapping<span style="color: #66cc66;">&#40;</span>value = <span style="color: #ff0000;">&quot;/users/{id}&quot;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #000000; font-weight: bold;">public</span> ModelAndView user<span style="color: #66cc66;">&#40;</span>@PathVariable <span style="color: #993333;">int</span> id<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    User user = repo.<span style="color: #006600;">userById</span><span style="color: #66cc66;">&#40;</span>id<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> ModelAndView<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;user&quot;</span>, SimpleMarshallingView.<span style="color: #006600;">DEFAULT_MODEL_KEY</span>, user<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<h3>Infrastructure</h3>
<p>Obviously, for the above to work we need organize our code appropriately and make sure that our build system properly builds the groovy files. This turned out to be surprisingly easy (using maven). All groovy code should be placed under <code>src/main/groovy</code>. Then maven needs to be configured to build the groovy files using the <a href="http://docs.codehaus.org/display/GMAVEN/Building+Groovy+Projects">gmaven</a> plugin. Also, make sure you include the groovy libs in your dependency list:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.codehaus.groovy<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>groovy-all<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>1.7.1<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<h3>Conclusion</h3>
<p>With the above setup it's easy to quickly implement (and test) new marshalling views for the different resources in a REST application. Even though this was used in a rather small proof-of-concept project my general feeling is that the approach will work pretty well. My next step with this will be to add some simplifications for working with HTTP status codes (the approach to HTTP response codes with the <code>@ResponseCode</code> annotation in Spring MVC feels insufficient for many cases).</p>
<p>Finally it should be noted that the approach with a completely generic marshaller makes it easy to expand this to working with other representations as well, e.g. JSON (although the JSON support in Groovy is still a little bit shaky).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/09/rest-and-xml-using-spring-mvc-and-groovy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Load-time weaving, Spring and Maven.</title>
		<link>http://blog.jayway.com/2009/12/15/load-time-weaving-spring-and-maven/</link>
		<comments>http://blog.jayway.com/2009/12/15/load-time-weaving-spring-and-maven/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 11:42:58 +0000</pubDate>
		<dc:creator>Mattias Ask</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[javaagent]]></category>
		<category><![CDATA[load-time weaving]]></category>
		<category><![CDATA[ltw]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3951</guid>
		<description><![CDATA[As some of you might have read in my earlier post, I'm using load-time weaving in the project that I'm working on. Lately I've run in to some problems with getting the tests to play nice with Maven. So what was the problem? Well, I've been using @Configurable and @Autowired to inject stuff in my [...]]]></description>
			<content:encoded><![CDATA[<p>As some of you might have read in my <a href="http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/">earlier post</a>, I'm using load-time weaving in the project that I'm working on. Lately I've run in to some problems with getting the tests to play nice with Maven. </p>
<p>So what was the problem? Well, I've been using <em>@Configurable</em> and <em>@Autowired</em> to inject stuff in my domain object which I create in code. To get this working when running <em>mvn test</em> you have to pass in spring-agent.jar as javaagent. When you do this, everything worked great! To to this with Maven you have to do the following:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.maven.plugins<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>maven-surefire-plugin<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>2.4<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;forkMode<span style="font-weight: bold; color: black;">&gt;</span></span></span>once<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/forkMode<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;argLine<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        -javaagent:${settings.localRepository}/org/springframework/spring-agent/${spring.version}/spring-agent-${spring.version}.jar
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/argLine<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;useSystemClassloader<span style="font-weight: bold; color: black;">&gt;</span></span></span>true<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/useSystemClassloader<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Now, that's all cool, and it worked like a charm... for a while. When I added <em>@Configurable</em> to another class to autowire in a new dependency, I could not get that specific class to get weaved properly. Believe me, I tried everything I could think of, but nothing worked... until I found a hint on a thread with a related problem. By passing in a second javaagent, aspectjweaver.jar, the problem was solved! To do this in Maven you just add the second javaagent after the first, like this:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.maven.plugins<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>maven-surefire-plugin<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>2.4<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;forkMode<span style="font-weight: bold; color: black;">&gt;</span></span></span>once<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/forkMode<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;argLine<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        -javaagent:${settings.localRepository}/org/springframework/spring-agent/${spring.version}/spring-agent-${spring.version}.jar -javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/1.6.1/aspectjweaver-1.6.1.jar
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/argLine<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;useSystemClassloader<span style="font-weight: bold; color: black;">&gt;</span></span></span>true<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/useSystemClassloader<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p><em><strong>Note:</strong> If you add a line-break between the two javaagents, it doesn't work.</em></p>
<p>What was the problem I had? I have no idea! Why does this solution work? I have no idea! All I know is that I get a green light from my tests, and that I don't need this solution when running live in Tomcat or whatever, since the classloader there has <em>addTransformer(ClassFileTransformer)</em>. </p>
<p>Still, if anyone has any idea of why I, <strong>after everything worked with only spring-agent.jar</strong>, needed to add aspectjweaver I am all ears! Don't get me wrong! I can live with not knowing, but I would get peace of mind from knowing...</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/15/load-time-weaving-spring-and-maven/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Referential Integrity using Spring LDAP</title>
		<link>http://blog.jayway.com/2009/12/07/referential-integrity-using-spring-ldap/</link>
		<comments>http://blog.jayway.com/2009/12/07/referential-integrity-using-spring-ldap/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 08:40:39 +0000</pubDate>
		<dc:creator>Vlado Palczynski</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[referential integrity]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2660</guid>
		<description><![CDATA[The directory servers of today are packed with a lot of nice features, one of them being Referential Integrity which performs integrity updates on attributes like member, uniqueMember, owner etc. Simpler put, when an entry updates its distinguished name, all references using the old distinguished name get updated to the new one. However, there can [...]]]></description>
			<content:encoded><![CDATA[<p>The directory servers of today are packed with a lot of nice features, one of them being <em>Referential Integrity</em> which performs integrity updates on attributes like member, uniqueMember, owner etc. Simpler put, when an entry updates its distinguished name, all references using the old distinguished name get updated to the new one.</p>
<p>However, there can be cases where your directory server setup might have to avoid using this feature. In our case we had a multi master environment and the plug-in cannot be enabled on both machines as it would create a circular update loop between the master servers. To have one machine in production with the plug-in wasn't a good choice either as we want the master configurations to be same on both machines and if one master goes down then there is a 50-50 chance that the <em>Referential Integrity</em> goes down with it.</p>
<p>Another reason is that you might not store distinguished names on relations attributes, but values like guid or uid, and then the <em>Referential Integrity</em> won't work.</p>
<p>Still this point to an interesting feature which should be pretty easy to implement in Java using Spring LDAP.</p>
<h3>Scenario 1</h3>
<p>A person who's used as owner in some entries updates his/her uid from <strong>old.uid</strong> to <strong>new.uid</strong>, where uid is a part of the distinguished name. For example, Jane Unmarried changes here name to Jane Doe: "uid=jane.unmarried, dc=jayway, dc=com" -> "uid=jane.doe, dc=jayway, dc=com".<br />
<strong>Feature</strong>: Update all owner references to the new distinguished name.<br />
<strong>Prerequisite</strong>: Single value attribute. The <em>owner</em> attribute should be indexed for best performance.</p>
<p>The <em>owner</em> attribute might be featured in many different objectclasses, so the tiresome way would be to make searches per objectclass and update them one by one. However, we can make use of a nice feature in LDAP: attributes are global and standardized according to an LDAP schema. The <em>owner</em> attribute is of the same type everywhere, so there is no risk of accidentally changing an <em>owner</em> attribute that is used for something else. Thus, a much better way would be to make a more general search:</p>
<pre>
EqualsFilter filter = new EqualsFilter("owner", "uid=old.uid, dc=jayway, dc=com");
</pre>
<p>And what do we want to return? The distinguished name should be sufficient:</p>
<pre>
protected AbstractContextMapper getAbstractMapper() {
        return new AbstractContextMapper() {

            /* Returns the distinguished name of the object it found. */
            protected Object doMapFromContext(DirContextOperations ctx) {
                return ctx.getNameInNamespace();
            }
        };
    }
}
</pre>
<p>This is all the information we need; a list of pointers to all entries in the LDAP structure where there is an owner attribute with the value <em>"uid=old.uid, dc=jayway, dc=com"</em>. We don't care which type of entries were found, as the only thing we're interested in is updating the value of the <em>owner</em> attribute.</p>
<p>Now do the search:</p>
<pre>
List<Name> hits =  ldapTemplate.search(
                 DistinguishedName.EMPTY_PATH,
                 filter.encode(),
                 getAbstractMapper());
</pre>
<p>We need to iterate through the search hits and only update the attribute, not the whole object, as we do not know anything about the object type:</p>
<pre>
for (Name someObjectDn: hits) {
    DirContextOperations context = ldapTemplate.lookupContext(someObjectDn);
    context.setAttributeValue("owner", "uid=new.uid, dc=jayway, dc=com");'

    ldapTemplate.modifyAttributes(context);
}
</pre>
<p>And we're done, the owner references are updated to <em>uid=new.uid, dc=jayway, dc=com</em>.</p>
<p>What if the owner person gets deleted? Well, then the <em>owner</em> values should be removed and all we need to do is replacing this:</p>
<pre>
context.setAttributeValue("owner", "uid=new.uid, dc=jayway, dc=com");
</pre>
<p>with this:</p>
<pre>
context.setAttributeValue("owner", null);
</pre>
<p>and the attribute owner will be removed from all the objects.</p>
<h3>General</h3>
<p>So we see that all we need for these kind of operations are:</p>
<ul>
1. The attribute name<br />
2. The current value<br />
3. The new value, null if to remove the attribute
</ul>
<p>Scenario 1 handles a single value attribute but it shouldn't be any harder with a multivalue attribute. The problem is that it's optional to define in an LDAP Schema whether an attribute is singlevalue or multivalue, so we cannot be certain what kind of attribute we're updating. The easiest way to solve this is to let the method have a boolean parameter for this:</p>
<ul>4. Is multivalue.</ul>
<h3>Scenario 2</h3>
<p>An person updates his/her uid (from <strong>old.uid</strong> to <strong>new.uid</strong>) and uid is a part of the distinguished name.<br />
<strong>Feature</strong>: Update person references in all object classes she is a member of.<br />
<strong>Prerequisite</strong>: Multivalue attribute. The <em>uniqueMember</em> attribute should be indexed for best performance.</p>
<p>The filter is almost the same as above:</p>
<pre>
EqualsFilter filter = new EqualsFilter("uniqueMember", "uid=old.uid, dc=jayway, dc=com");
</pre>
<p>The context mapper is the same as above, it's still the distinguished names of the objects that carry the attribute <em>uniqueMember</em> we're interested in. The search is also the same as above. But as <em>uniqueMember</em> is a list we need to iterate all the members in the list and replace the old value with the new:</p>
<pre>
for (Name someObjectDn: hits) {
    DirContextOperations context = ldapTemplate.lookupContext(someObjectDn);
    String[] members = context.getStringAttributes("uniqueMember");

     for (int i = 0; i < members.length; i++) {
            if (members[i].equals("uid=old.uid, dc=jayway, dc=com")) {
                members[i] = "uid=new.uid, dc=jayway, dc=com";

                break;
            }
    }

    context.setAttributeValues("uniqueMember", members);

    ldapTemplate.modifyAttributes(context);
}
</pre>
<h3>Conclusion</h3>
<p>It's easy to get the same functionality as the <em>Referential Integrity</em> using only Spring LDAP with very little custom code. You can introduce relationship attributes in new object classes and one method call will handle them all. An upside is that the filters use string values, so your relations attributes are not forced to contain distinguished names, but might be other values like uid or guid. However, using distinguished name is recommended.</p>
<p>As the searches all start from base, the searches might be less efficient as it scans the whole directory structure for the attribute. So this isn't recommended on non-indexed attributes when having large data volumes. The same applies to using the Referential Integrity within the directory server.</p>
<p>Thanks to Ulrik Sandberg and Andreas Andersson for their inputs on this blog.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/07/referential-integrity-using-spring-ldap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Security For Real with Grails</title>
		<link>http://blog.jayway.com/2009/11/23/spring-security-for-real-with-grails/</link>
		<comments>http://blog.jayway.com/2009/11/23/spring-security-for-real-with-grails/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 18:41:34 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring security]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2248</guid>
		<description><![CDATA[Spring Security is one of the basic building blocks I use pretty much every time I'm constructing a web application. It's a very mature and incredibly powerful security framework, one of its main benefits being its versatility. There are hooks and plugs everywhere, allowing you to extend and combine basically any way you want. Now, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://static.springsource.org/spring-security/site/">Spring Security</a> is one of the basic building blocks I use pretty much every time I'm constructing a web application. It's a very mature and incredibly powerful security framework, one of its main benefits being its versatility. There are hooks and plugs everywhere, allowing you to extend and combine basically any way you want.</p>
<p>Now, if you want to apply security in a Grails application you are typically pointed in the direction of the <a href="http://grails.org/plugin/acegi">Grails Acegi Plugin</a>, which does a rather decent job at applying basic security to your Grails application. It quickly falls short however when you need to start doing something more than the bare basics (which you pretty much always need to do); even though the plugin is based on Spring Security, far from everything in the original framework is supported in the plugin, and hooking in custom components is pretty much out of the question. In addition to this, the Acegi Plugin is haunted by a couple of pretty annoying bugs.</p>
<p>Bottom line: for any real-world scenario you will most likely want to fall back to the original, i.e. use the original Spring Security framework in your Grails application. Since Grails is Spring-based it shouldn't be all that much work to set that up, right? Well basically yes, but as I set out do to it I ran into a number of problems before I got it right, so I thought I might as well line out the steps and pitfalls.</p>
<h4>1. Download and Install the Spring Security jars</h4>
<p>Typically, for the basic setup you should need only the <code>spring-security-core.jar</code> and <code>spring-security-core-tiger.jar</code>, but depending on your requirements you might need to include more of the Spring Security binaries. Place the jars in your <code>lib</code> directory of your Grails application.</p>
<h4>2. Install Templates</h4>
<p>Spring Security is based on an HTTP filter chain, which needs to be declared in the <code>WEB-INF/web.xml</code> file of the web application. This file is normally automatically generated for you by Grails, but for the event that you need more control (such as this occasion) you can have the default file generated for you to edit. The command for this is <code>grails install-templates</code>. This will generate a number of files, and the <code>web.xml</code> will be ready for editing under <code>src/templates/war</code>.</p>
<h4>3. Add the Spring Security Filter Chain</h4>
<p>There will be a number of filters defined in the <code>web.xml</code> file already. Add the Spring Security filter after the other filter definitions, but before the filter-mapping entries (all the filter definitions need to be placed before the filter-mapping ones, or else evil things will happen with any additional filters generated by Grails and we'll get in trouble when we deploy in tomcat).</p>
<pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>springSecurityFilterChain<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter-class<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.springframework.web.filter.DelegatingFilterProxy<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter-class<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<p>Now, after the other filter-mapping entries, add the filter-mapping for the Spring Security filter:</p>
<pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter-mapping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>springSecurityFilterChain<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;url-pattern<span style="font-weight: bold; color: black;">&gt;</span></span></span>/*<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/url-pattern<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter-mapping<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<h4>4. Spring Security Configuration </h4>
<p>Now we're ready to add the Spring Security configuration XML. Note that this configuration <b>needs</b> to be placed in <code>grails-app/conf/spring/resources.xml</code>. I initially tried to put it in <code>WEB-APP/WEB-INF/applicationContext.xml</code> but due to the Grails ApplicationContext loading magic that attempt failed spectacularly. We'll start out with a minimal Spring Security configuration just to get things going; for more information the configuration topic I'll refer to the <a href="http://static.springsource.org/spring-security/site/docs/2.0.x/reference/springsecurity.html">reference documentation</a>.</p>
<pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span>
        <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span>
        <span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd&quot;</span>
        <span style="color: #000066;">xmlns:sec</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/security&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:http<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:intercept-url</span> <span style="color: #000066;">pattern</span>=<span style="color: #ff0000;">&quot;/**&quot;</span> <span style="color: #000066;">access</span>=<span style="color: #ff0000;">&quot;ROLE_USER&quot;</span><span style="font-weight: bold; color: black;">/&gt;</span></span>
                <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:http-basic</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/sec:http<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:authentication-provider<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:user-service<span style="font-weight: bold; color: black;">&gt;</span></span></span>
                        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:user</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;mattias&quot;</span> <span style="color: #000066;">password</span>=<span style="color: #ff0000;">&quot;12345&quot;</span> <span style="color: #000066;">authorities</span>=<span style="color: #ff0000;">&quot;ROLE_USER&quot;</span><span style="font-weight: bold; color: black;">/&gt;</span></span>
                <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/sec:user-service<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/sec:authentication-provider<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/beans<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<p><b>Another note of caution here:</b> If there is anything incorrect in your <code>resources.xml</code> Grails will <b>happily and silently ignore this</b> and go ahead and start anyway. Therefore, whenever you start doing stuff with your own custom Spring configuration in a Grails app it is imperative to make sure to configure your logging so that Spring warning and error messages are logged properly or you'll be completely in the dark trying to figure out what went wrong.</p>
<h4>All done</h4>
<p>As it turns out this wasn't as bad as expected. You're now all set to unleash the full power of Spring Security on your Grails application.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/11/23/spring-security-for-real-with-grails/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Spring and load-time weaving of Neo4j-based domain objects</title>
		<link>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/</link>
		<comments>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/#comments</comments>
		<pubDate>Tue, 26 May 2009 07:51:25 +0000</pubDate>
		<dc:creator>Mattias Ask</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[neo4j]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1773</guid>
		<description><![CDATA[What do you do when your Spring configuration isn't in charge of creating your objects that needs to be injected with stuff? This became a real problem for me when I tried doing some non-anemic domain object implementations persisted as Neo4j Nodes. I was playing around with creating a Twitter clone, in my opinion the [...]]]></description>
			<content:encoded><![CDATA[<p>What do you do when your Spring configuration isn't in charge of creating your objects that needs to be injected with stuff? This became a real problem for me when I tried doing some non-anemic domain object implementations persisted as <a href="http://www.neo4j.org">Neo4j</a> Nodes. </p>
<p>I was playing around with creating a Twitter clone, in my opinion the "Hello World" of graph databases, and I started out with the following simple service.</p>
<p>Spring configurating:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;beans</span> ... <span style="font-weight: bold; color: black;">&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;context:annotation-config</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.neo4j.api.core.EmbeddedNeo&quot;</span>
		<span style="color: #000066;">destroy-method</span>=<span style="color: #ff0000;">&quot;shutdown&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg<span style="font-weight: bold; color: black;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;value<span style="font-weight: bold; color: black;">&gt;</span></span></span>var/neo<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/value<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/constructor-arg<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.neo4j.util.index.NeoIndexService&quot;</span>
		<span style="color: #000066;">destroy-method</span>=<span style="color: #ff0000;">&quot;shutdown&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;twitterService&quot;</span>
		<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.jayway.twitter.neo.NeoBasedTweetService&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- Transactions --&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;tx:annotation-driven</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
        ...
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/beans<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>The service:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NeoBasedTweetService <span style="color: #000000; font-weight: bold;">implements</span> TweetService <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NeoService neo;
	<span style="color: #000000; font-weight: bold;">protected</span> IndexService indexService;
&nbsp;
	<span style="color: #808080; font-style: italic;">//Setters for neo and indexService</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span>User user, <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> tweet<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		UserNode userNode = <span style="color: #000000; font-weight: bold;">new</span> UserNode<span style="color: #66cc66;">&#40;</span>indexService.<span style="color: #006600;">getSingleNode</span><span style="color: #66cc66;">&#40;</span>
				TwitterIndexConstants.<span style="color: #006600;">INDEX_USER</span>, user.<span style="color: #006600;">getUserName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span>neo.<span style="color: #006600;">createNode</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setKvitt</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		userNode.<span style="color: #006600;">createRelationshipTo</span><span style="color: #66cc66;">&#40;</span>tweetNode, KvittRelationships.<span style="color: #006600;">KVITTRAT</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Services to create User and more</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This doesn't feel very DDD. I would really want to do the User to be responsible for creating the Tweet. Like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NeoBasedTweetService <span style="color: #000000; font-weight: bold;">implements</span> TweetService <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NeoService neo;
	<span style="color: #000000; font-weight: bold;">protected</span> IndexService indexService;
&nbsp;
	<span style="color: #808080; font-style: italic;">//Setters for neo and indexService</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span>User user, <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> tweet<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		UserNode userNode = <span style="color: #000000; font-weight: bold;">new</span> UserNode<span style="color: #66cc66;">&#40;</span>indexService.<span style="color: #006600;">getSingleNode</span><span style="color: #66cc66;">&#40;</span>
				TwitterIndexConstants.<span style="color: #006600;">INDEX_USER</span>, user.<span style="color: #006600;">getUserName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> userNode.<span style="color: #006600;">createTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Services to create User and more</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The TweetNode and UserNode would look like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TweetNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Tweet <span style="color: #66cc66;">&#123;</span>
&nbsp;
	TweetNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing Tweet-stuff</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> User<span style="color: #66cc66;">&#123;</span>
&nbsp;
	UserNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing User-stuff</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> kvitt<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">//Here comes a problem! I need a new Node</span>
		<span style="color: #808080; font-style: italic;">//from the NeoService to create the TweetNode</span>
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		createRelationshipTo<span style="color: #66cc66;">&#40;</span>tweetNode, TwitterRelationships.<span style="color: #006600;">TWEETED</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>NodeDelegate, extended by both User- and TweetNode implements the Neo4j interface <code>Node</code> and delegates all the method calls to the underlying node ( for more on this, see my <a href="http://blog.jayway.com/2008/10/06/neo4j-matches-my-mental-model-of-information/">previous post</a>) :</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Node delegate;
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		delegate = underlyingNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for delegating all Node methods to the Node delegate</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>As you see I have a problem here. In the first version my NeoService is injected into NeoBasedTweetService and used when I create the new TweetNode. In the re-made, more DDD-style example I create the new TweetNode in the UserNode, where I don't have access to my NeoService. How do we solve this?</p>
<p>One alternative that I instinctively dislike is to inject the NeoService into the UserNode. The reason for me disliking this is that my UserNode IS a Node, and it feels very tangled if a Node holds a reference to its container. But I came to think of another solution thanks to a talk I did a while back together with Henrik Reinhold on what was new in Spring 2.5. </p>
<p>In Spring 2.5 load-time weaving (LTW) capabillites was introduced, and with LTW you can manipulate objects in load-time, as opposed to runtime weaving that is proxy based. This, combine it with @Configurable and @Autowired, proves to be <em>very</em> helpful when the Spring context is not in charge of creating the objects in question, as in the example above...</p>
<p>To enable LTW we add one tag in the Spring configuration:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;context:load-time-weaver</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
&nbsp;</pre>
<p>After that we have to inform the Spring container of how we want thing done. To do we edit the TweetNode and NodeDelegate like this:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">//Annotate the class with @Configurable so that Spring can find it.</span>
@Configurable
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TweetNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Tweet <span style="color: #66cc66;">&#123;</span>
&nbsp;
	TweetNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Add a default constructor both in the TweetNode</span>
	<span style="color: #808080; font-style: italic;">//and the NodeDelegate, it is new:able without a Node.</span>
	<span style="color: #000000; font-weight: bold;">public</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Add a setter for the underlaying Node and annotate it with @Autowired.</span>
	@Autowired
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setNode<span style="color: #66cc66;">&#40;</span>Node nodeDelegate<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">setNode</span><span style="color: #66cc66;">&#40;</span>nodeDelegate<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Tweet-methods as before</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Node delegate;
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		delegate = underlyingNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setNode<span style="color: #66cc66;">&#40;</span>Node nodeDelegate<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>delegate == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			delegate = nodeDelegate;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for delegating all Node methods to the Node delegate</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now Spring only has to be able to create Nodes. To do that we create a simple NodeFactory, like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeFactory <span style="color: #000000; font-weight: bold;">implements</span> FactoryBean<span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> NeoService neo = <span style="color: #000000; font-weight: bold;">null</span>;
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setNeo<span style="color: #66cc66;">&#40;</span>NeoService neo<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">neo</span> = neo;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> getObject<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> neo.<span style="color: #006600;">createNode</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">Class</span> getObjectType<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> Node.<span style="color: #000000; font-weight: bold;">class</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> isSingleton<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">false</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>... and add it to the configuration, like this:</p>
<pre class="xml">&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;node&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.jayway.neo.utils.NodeFactory&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>The result of this is that Spring now has a NodeFactory that returns a new node for every request, I have annotated the TweetNode so that Spring knows of it (@Configurable) and what to do with it (@Autowired on setNode) and I've enabled load-time weaving in order to get the a new Node woven into a TweetNode every time a new instance of it is created in the code.</p>
<p>In UserNode I really don't have to make any changes. "setNode(Node)" will get a new Node after the instantiation of a TweetNode, even if the constructor that takes a Node is called. For clarity I still changed the UserNode as follows:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> User<span style="color: #66cc66;">&#123;</span>
&nbsp;
	UserNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing User-stuff</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> kvitt<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">//This TweetNode will get a Node set by Spring</span>
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		createRelationshipTo<span style="color: #66cc66;">&#40;</span>tweetNode, TwitterRelationships.<span style="color: #006600;">TWEETED</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The problem I had when trying to make the UserNode responsible for creating its TweetNode's was that I needed to inject something that could create Nodes into the UserNodes. By using load-time weaving and instructing Spring of how to wire a TweetNode I don't have to pass my NeoService around to all the UserNodes created in my code. Instead I can rely on Spring to inject what is needed, when it's needed.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Simple Authentication Using Spring LDAP</title>
		<link>http://blog.jayway.com/2009/02/02/simple-authentication-using-spring-ldap/</link>
		<comments>http://blog.jayway.com/2009/02/02/simple-authentication-using-spring-ldap/#comments</comments>
		<pubDate>Mon, 02 Feb 2009 20:00:46 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[1.3.0]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[bind]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[ldap]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=870</guid>
		<description><![CDATA[It's with great pleasure that we can now finally announce the final 1.3.0 version of Spring LDAP. It's been a while since we've made a major release, but there's quite a bit in this one to make up for it. Among the highlights of this release are the improvements in the authentication area, which is [...]]]></description>
			<content:encoded><![CDATA[<p>It's with great pleasure that we can now finally announce the final 1.3.0 version of <a href="http://www.springframework.org/ldap">Spring LDAP</a>. It's been a while since we've made a major release, but there's quite a bit in this one to make up for it. Among the highlights of this release are the improvements in the authentication area, which is the intended focus of this post.</p>
<h3>Simple LDAP Authentication</h3>
<p>One of the most requested pieces of functionality in Spring LDAP has been a means to perform simple authentication. We have previously hesitated to include this, not finding any logical place to put it. In this release however we got a couple of suggestions on suitable API additions that enabled us to attack this from a different angle, in the end resulting in explicit methods in LdapTemplate for this purpose.</p>
<h4>Background</h4>
<p>The problem with authentication in LDAP is that it normally requires two separate steps: First you need to find the principal to authenticate in the LDAP tree, typically performing an LDAP search based on e.g. a user name. A new LDAP connection will then be acquired, authenticating it using the Distinguished Name of the found entry (normally referred to as an 'LDAP Bind').</p>
<h5>Example</h5>
<p>Consider the LDAP tree below:<br />
<img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/02/ldaptree.gif" alt="Ldap Tree" title="Ldap Tree" width="303" height="276" class="size-full wp-image-871" /><br />
Let us say a user identifying himself as 'John Doe' is trying to log into our system. We would execute a search from the top of the LDAP tree using a search filter like <code>(&(objectclass=person)(cn=John Doe))</code>. The search would return one single entry, from which we would extract the absolute DN; <code>cn=John Doe, ou=company1, c=Sweden, dc=jayway, dc=se</code>. This DN would then be used for authenticating a new LDAP connection to the server, thus validating the password supplied by the user.</p>
<h4>New Spring LDAP Authentication API</h4>
<p>While the above has indeed been possible to do using previous versions of Spring LDAP, it has required quite a lot of work and resulted in rather messy code. Spring LDAP 1.3.0 adds a couple of methods to LdapTemplate, making the authentication procedure very straightforward:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> authenticate<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AName+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Name</span></a> base, <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> filter, <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> password<span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> authenticate<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AName+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Name</span></a> base, <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> filter, <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> password, AuthenticatedLdapEntryContextCallback callback<span style="color: #66cc66;">&#41;</span></pre>
<p>The first method performs exactly the procedure described above, returning <code>true</code> or <code>false</code> depending on the outcome. The second method goes one step further, allowing us to perform any operation on the authenticated LDAP connection. Focusing on the simplest case, a standard authentication method using Spring LDAP would look something like the following:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> login<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> username, <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> password<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  AndFilter filter = <span style="color: #000000; font-weight: bold;">new</span> AndFilter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  filter.<span style="color: #006600;">and</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> EqualsFilter<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;objectclass&quot;</span>, <span style="color: #ff0000;">&quot;person&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">and</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> EqualsFilter<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;cn&quot;</span>, username<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #000000; font-weight: bold;">return</span> ldapTemplate.<span style="color: #006600;">authenticate</span><span style="color: #66cc66;">&#40;</span>DistinguishedName.<span style="color: #006600;">EMPTY_PATH</span>, filter.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, password<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Simple, clean and to the point, especially compared to the mess that used to be required (won't linger on those nasty details here). Obviously however, using a Spring library we will be required to write a few lines of XML as well:</p>
<pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.support.LdapContextSource&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap://url.to.ldap.server:389&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;uid=admin,ou=system&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;adminpassword&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.LdapTemplate&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;myAuthenticator&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.example.MyAuthenticatingClass&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- Assuming constructor injection of LdapTemplate instance in your authentication class --&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>A couple of comments on the suggested solution:</p>
<ul>
<li>The search needs to return exactly one result entry. In the example above, if there would be more than one person entry in the tree with <code>cn</code> 'John Doe' (which would be perfectly legal according to schema regulations), the call to <code>authenticate</code> would fail.</li>
<li>In actual implementations the attribute to use for identification will likely be e.g. <code>uid</code> or <code>sAMAccountname</code> (in Active Directory). Both of these attributes have uniqueness enforced throughout the entire tree by the LDAP server.</li>
<li> The method only returns <code>true</code> or <code>false</code>; thus the actual reason for failing will not be visible to the caller. The reason will however be logged, which might be useful useful when tracking down problems with search filters and such.</li>
<li>A common reason for confusion in LDAP searches is the <code>base</code> parameter, which is used for pointing out where in the LDAP tree to start searching. Referring again to the potential problem where several users might have the same <code>cn</code>; in that case these entries would have to be located in different subtrees. The search could then be narrowed by specifying a different base DN to the <code>authenticate</code> method, e.g. <code>c=Sweden, dc=jayway, dc=com</code></li>
</ul>
<p><b>Note: </b>While the provided methods will handle the simple task of authentication for you it is likely that your actual security requirements go way past plain authentication (e.g. authorization, web integration, etc.). The realm of security is a very complex one, which is the reason you should carefully consider your actual requirements - if they appear to go beyond simple authentication you should definitely consider using <a href="http://www.springsecurity.org">Spring Security</a> instead. (Obviously, under the covers Spring LDAP would be used for the actual authentication anyway).</p>
<p>That said, for many systems the API provided with Spring LDAP will be quite sufficient.</p>
<h3>Other improvements in Spring LDAP 1.3.0</h3>
<p>As compared to the 1.2.1 version of Spring LDAP, 1.3.0 includes more than 50 fixes, varying from internal modifications and minor improvements to important bug fixes and significant functionality additions. The full list of modifications can be viewed in the <a href="http://static.springframework.org/spring-ldap/docs/1.3.x/changelog.txt">the changelog</a>.</p>
<h3>About Spring LDAP</h3>
<p>Spring LDAP is a Java library for simplifying LDAP operations, based on the pattern of Spring's JdbcTemplate. The framework relieves the user of common chores, such as looking up and closing contexts, looping through results, encoding/decoding values and filters, and more. The library is free, open source, and distributed under the Apache Licence version 2. </p>
<p>For more information on the Spring LDAP project, including downloads, maven usage, as well as project reference and API documentation, refer to its <a href="http://www.springsource.org/ldap">project home page</a> on springsource.org. Support and enhancement requests will be answered in the <a href="http://forum.springframework.org/forumdisplay.php?f=40">Spring LDAP Forum</a> at Spring Community Forums.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/02/02/simple-authentication-using-spring-ldap/feed/</wfw:commentRss>
		<slash:comments>44</slash:comments>
		</item>
		<item>
		<title>Devoxx highlights</title>
		<link>http://blog.jayway.com/2008/12/23/devoxx-highlights/</link>
		<comments>http://blog.jayway.com/2008/12/23/devoxx-highlights/#comments</comments>
		<pubDate>Tue, 23 Dec 2008 22:29:31 +0000</pubDate>
		<dc:creator>Jacob Mattsson</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring dm]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=699</guid>
		<description><![CDATA[In order to embrace the true Christmas spirit, I thought I'd share a few goodies from the Devoxx conference that took place in Antwerp, Belgium in mid December. Devoxx is the former JavaPolis that has changed name due to trademarking issues with Sun. Nonetheless, it's still the worlds largest independent Java conference, where the 3200 [...]]]></description>
			<content:encoded><![CDATA[<p>In order to embrace the true Christmas spirit, I thought I'd share a few goodies from the <a href="http://devoxx.com">Devoxx conference</a> that took place in Antwerp, Belgium in mid December. Devoxx is the former JavaPolis that has changed name due to trademarking issues with Sun. Nonetheless, it's still the worlds largest <em>independent</em> Java conference, where the 3200 attendees find themselves being literally showered with news from the broad Java community. Below follow summaries from some of the, IMHO, best sessions from this years conference. Enjoy!</p>
<h3>BDD in Java with easyb (John Ferguson Smart)</h3>
<p>John started out by arguing that TDD is not about testing, it's about writing better code. That is, it's about making your code more maintainable, flexible, reliable and simple. TDD is forces the programmer to think about how to test the class before actually writing the class. BDD, on the other hand, helps to determine what to test and to write more focused code, by starting with the behavior. Instead of thinking that you're testing your class, you should think that you're validating your requirements! </p>
<p>easyb is a BDD testing framework for Java, written in Groovy (hence providing full access to all Java API's). It ensures that tests become clearer and easier to both write and read!  It helps the developer to focus on the requirements only. A competitor to easyb is JBehave, which is an extension to JUnit. However, according to John, JBehave is more cumbersome than easyb.</p>
<p>easyb makes use of stories, much like the story cards in the Agile world. In a story, a narrative approach is used to describe a precise requirement. In easyb, a story could look like this:</p>
<pre class="groovy">&nbsp;
scenario â€œMake initial deposit onto a <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> accountâ€, <span style="color: #66cc66;">&#123;</span>
	given â€œa <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> accountâ€
	when â€œan initial deposit is madeâ€
	then â€œthe balance should be equal to the amount depositedâ€
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This scenario is quite clear and readable, isn't it!? Furthermore, it's self-documenting - a very appreciated feature =) And the syntax is so trivial that even a non-technical stakeholder would have no problem understanding it. The developer can then reuse the given scenario (pseudo) code and implement the test case, like this:</p>
<pre class="groovy">&nbsp;
<span style="color: #a1a100;">import com.mycompany.bankonline.domain.Account</span>
&nbsp;
scenario â€œMake initial deposit onto a <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> accountâ€, <span style="color: #66cc66;">&#123;</span>
	given â€œa <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> accountâ€, <span style="color: #66cc66;">&#123;</span>
		account = <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> Account<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#125;</span>
	when â€œan initial deposit is madeâ€, <span style="color: #66cc66;">&#123;</span>
		initialAmount = <span style="color: #cc66cc;">100</span>
		account.<span style="color: #006600;">makeDeposit</span><span style="color: #66cc66;">&#40;</span>initialAmount<span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#125;</span>
	then â€œthe balance should be equal to the amount depositedâ€, <span style="color: #66cc66;">&#123;</span>
		account.<span style="color: #006600;">balance</span>.<span style="color: #006600;">shouldBe</span> initialAmount
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The <code>shouldBe</code> call is an intuitive and readable way to verify that the requirement holds. Another way to verify the outcomes is to use the <code>ensure</code> syntax. Example:</p>
<pre class="groovy">&nbsp;
ensure<span style="color: #66cc66;">&#40;</span>account.<span style="color: #006600;">balance</span> &gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>or</p>
<pre class="groovy">&nbsp;
ensure<span style="color: #66cc66;">&#40;</span>account<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	has<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>balance:<span style="color: #cc66cc;">100</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>easyb could be extended to use DBUnit (and further plugins for Grails and Excel are on the way). On the IDE support, the only good option is IntelliJ IDEA. It really comes down to the Groovy support, and Eclipse and NetBeans doesn't shine here. In those cases, you're better off running the tests in Maven or Ant, which both are well supported. In the upcoming version, easyb will have full support for Continuous Integration (CI), enabling automatic test execution in a CI-server such as Hudson.</p>
<p>Furthermore, easyb comes with a web application - Easiness (cmp. Fitnesse) - where stakeholders can create stories in plain text. The developers can then go ahead and implement the stories defined by the stakeholders. This is an important features, that further improves the cooperation between the customer and the provider. It really seems like a quite nice little framework! If you agree, have a look at it at <a href="http://easyb.org/">http://easyb.org/</a>.</p>
<h3>From Concurrent to Parallel â€“ Library-based parallelism in JDK 7 (Brian Goetz)</h3>
<p>Brian is an expert in the concurrency area, but he's not a good presenter! He speaks faster than I can read, and his slides are so packed with info that he doesn't have time to say the half of it. That put aside, in this very interesting session Brian presented some really cool concurrency features to be included in JDK 7.</p>
<p>As you probably know, JDK 5 introduced a set of very useful classes for course-grained parallelism. JDK 7 will introduce a framework for fine-grained parallelism - the "fork-join" framework.</p>
<p>We have now reach a point in time when Moore's laws isn't valid anymore. The new reality is not faster CPUs but more CPUs. To adapt to these changes, programmers have to change the way they think about parallelism. The unit of work (UoW) that represents a task to be solved must be split into even smaller parts to be able to keep all hardware busy. Nowadays, it isn't enough to for ex. spawn a new thread for each service call in a server, the UoW must be split up even further.</p>
<p>Examples of finer-grained parallelism is searching, sorting and filtering a data set. Such a task is preferably solved by dividing it into sub-problems and combining the sub-results at the end. We could use the course-grained concurrency tools (for ex. <code>Executor</code> + <code>Future</code>) introduced in JDK 5 to solve this problem. However, with multiple CPUs available, these tools doesn't perform optimally. For ex., the shared work queue in the <code>Executor</code> becomes a bottle neck when the number of threads/CPUs increases. Furthermore, these tools provide no form of load balancing, i.e. if one thread finishes before the others, it is never reused.</p>
<p>The divide-and-conquer algorithm could also be applied to solve the problem. This great advantage of this approach is that it's independent of the number of CPUs used! Using plain threads for this approach is too expensive though, since thread creation costs way too much. However, the fork-join-operation in JDK 7 solves problems like these using the divide-and-conquer algorithm in a much more effective way! Internally, it uses an slim thread pool to overcome the cost of thread creation. Furthermore, no data-copying penalty exist since the data set (for ex. an array) is not divided/copied during the solution. Instead, the indexes within the data structure is used to define each data subset. Another advantage is that the code doesn't know how many CPUs it executes on, hence it's portable! </p>
<p>While the <code>Executor</code> (JDK 5) should be used for tasks consisting of both IO and computing, the fork-join-operation (JDK 7) should be used for highly compute-intensive tasks. Examples of such tasks are matrix operations, numerical integrations and game playing. The JDK 7 class to be used for these kind of problems is <code>ParallelArray</code>. It's a utility class that greatly simplifies the work of solving a task in parallel. You can think of it as an in-memory database for data sets. Typical usage is:</p>
<pre class="java">&nbsp;
ParallelLongArray pa = ParallelLongArray.<span style="color: #006600;">createUsingHandoff</span><span style="color: #66cc66;">&#40;</span>array, forkJoinPool<span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">long</span> max = pa.<span style="color: #006600;">max</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>The <code>ParallelArray</code> class provides operations for:</p>
<ul>
<li>Filtering (nestable)</li>
<li>Mapping</li>
<li>Replacement</li>
<li>Aggregation (max, count, sum, ...)</li>
<li>Application (one action performed for each selected element)</li>
</ul>
<p>To compare, the <code>ParallelArray</code> class acts much like the Map-Produce concept introduced by Google but it works in a different domain (local system instead of in a distributed system).</p>
<p>The only downside really is that JDK 7 isn't scheduled until mid 2010, meaning we'll have to wait quite some time before we can actually use these new concurrency features. But from the looks of it ... it may be worth the wait!</p>
<h3>The SpringSource DM Server (Joris Kuipers)</h3>
<p>The reasons why SpringSource decided to develop a new application server were many. Today, modularity is important and developers spend much time on achieving it in their applications (layering, separation of concerns, etc.). However, when the application is deployed, all modularity is lost - the deployable unit is one huge, monolithic WAR file. That means that sharing code (let alone services) between applications become hard if not impossible. In order to perform the smallest update on the application, whole WAR file have to be redeployed. Furthermore, the servers themselves lack modularity; they come prepackaged with a lot of modules but there's no way to configure that your application only make use of a couple of them. Hence, they are all left in there, consuming unnecessary CPU cycles and memory.</p>
<p>The DM (Dynamic Modules) server was developed to tackle these issues of non-modularity. In order to achieve true modularity, is has been built on top of OSGi (namely the Equinox container). Since OSGi can be quite hard sometimes, the DM server conceal the complexity of OSGi in the same way as the Spring framework does with for ex. Remoting or JMX. </p>
<p>In order to be able to use a third-party library from within the DM server (and from any other OSGi containers), the standard JAR library needs to be extended with OSGi-specific meta data - the OSGi manifest. SpringSource has therefore created the Enterprise Bundle Repository, where they have started to upload and publish OSGi-ified Java EE libraries. If you're using Maven or Ivy, the bundle repository can easily be configured as a remote (or local) repository.</p>
<p>The DM server also introduces a couple of new OSGi import constructs, enabling ease of development. One example is the "Import-library" that can be useful if you want to make use of a framework (for ex. Spring) but don't want to waste your time having to specify every single Import-package (for example Spring-Remoting) within the framework (as you normally would have had to do). This doesn't affect performance improvement since (thanks to OSGi) none of the pre-installed bundles are loaded before they are actually used! Furthermore, with the DM server it's now possible to remove the library bloat of monolithic Java EE WARs. Instead of building the external libraries into your WAR, you can instead declare them as dependencies in the OSGi manifest headers. The server will then convert these into plain "Import-package" constructs during deployment. That way, the size of the built/deployed WAR can be reduced significantly!</p>
<p>In the DM server, one can of course deploy plain OSGi bundles but also WARs, EARs etc. Typical scenarios for deploying a plain OSGi bundle are stand-alone libraries, global services and small stand-alone applications. However, being able to deploy a bundle is not enough in most cases ... A normal application normally consist of multiple bundles, which becomes hard to un/deploy since there is no single deployable unit. Furthermore, with multiple bundles you don't get a common log file or a notion of an application scope. To tackle this issue, the DM server adds the notion of an application by introducing the PAR (Platform Archive) format. It's basically a JAR with a number of 'Application-*' manifest headers. You can think of it as an EAR in Java EE. PARs are versioned and the versions apply to all of their bundles. This mean that one can deploy a PAR twice with different versions but with the same bundles, without conflicts.</p>
<p>The DM server comes in several versions. Of course there's the community version, using a GPL and SpringSource license. Then there's the commercial license where full support from SpringSource is included. On the extension side, better Maven support will soon be released so that the dependencies can be specified in a single place (not like now when you have to duplicate them in the pom and in the manifest). There's a Eclipse-plugin available that enables re/deployments from within the IDE.</p>
<p>These are some of the features in the DM server. There are plenty or more cool ones, read all about them <a href="http://www.springsource.com/products/suite/dmserver">here</a>. There, you'll also find a lot of sample applications that can get you going! With the DM server, SpringSource feel that they are filling the (up until now) empty space of server side OSGi and states that "The DM server is the healthy new way to run your apps!". I must say it looks very promising! Why don't you go ahead and try it out!? I know I will!</p>
<p><em>If you appreciated these posts, you will definitely enjoy next years conference! Pick up your calendar and reserve December 2009 for a great week at Devoxx!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/23/devoxx-highlights/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Encrypting Properties With Jasypt</title>
		<link>http://blog.jayway.com/2008/12/09/encrypting-properties-with-jasypt/</link>
		<comments>http://blog.jayway.com/2008/12/09/encrypting-properties-with-jasypt/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 17:08:40 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[properties]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[tools]]></category>

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

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

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=369</guid>
		<description><![CDATA[We recently released Spring LDAP 1.3.0.RC1. This long awaited release contains a number of new features and bug fixes. In this post I'll highlight some of the changes, pointing out some of my favorite Spring LDAP features. Simple Authentication Mechanism By far the most requested feature for inclusion in Spring LDAP has been the ability [...]]]></description>
			<content:encoded><![CDATA[<p>We recently released <a href="http://www.springframework.org/ldap">Spring LDAP</a> 1.3.0.RC1. This long awaited release contains a number of new features and bug fixes. In this post I'll highlight some of the changes, pointing out some of my favorite Spring LDAP features.</p>
<h3>Simple Authentication Mechanism</h3>
<p>By far the most requested feature for inclusion in Spring LDAP has been the ability to easily perform simple authentication using the library. While you would typically like to use <a href="http://static.springframework.org/spring-security/site/index.html">Spring Security</a> to implement full-blown application security many of our users have expressed the need to just do the authentication part, not having to worry about the full Spring Security framework. This is now explicitly supported with a new method in the <code>ContextSource</code> interface: <code>getContext(String principal, String password)</code>. This means that in order to do simple user authentication you would write something like the following:</p>
<pre class="java">&nbsp;
...
<span style="color: #000000; font-weight: bold;">private</span> SimpleLdapTemplate ldapTemplate;
<span style="color: #000000; font-weight: bold;">private</span> ContextSource contextSource;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setLdapTemplate<span style="color: #66cc66;">&#40;</span>SimpleLdapTemplate ldapTemplate<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">ldapTemplate</span> = ldapTemplate;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setContextSource<span style="color: #66cc66;">&#40;</span>ContextSource contextSource<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">contextSource</span> = contextSource;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> authenticate<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> userName, <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> password<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	EqualsFilter filter = <span style="color: #000000; font-weight: bold;">new</span> EqualsFilter<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;uid&quot;</span>, userName<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #808080; font-style: italic;">// Actual filter will differ depending on LDAP Server and schema</span>
	List&lt;String&gt; results = ldapTemplate.<span style="color: #006600;">search</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span>, filter.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>,
			<span style="color: #000000; font-weight: bold;">new</span> DnContextMapper<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>results.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> != <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> IncorrectResultSizeDataAccessException<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, results.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ADirContext+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">DirContext</span></a> ctx = <span style="color: #000000; font-weight: bold;">null</span>;
	<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #66cc66;">&#123;</span>
		ctx = contextSource.<span style="color: #006600;">getContext</span><span style="color: #66cc66;">&#40;</span>results.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>, password<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">true</span>;
	<span style="color: #66cc66;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> e<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">false</span>;
	<span style="color: #66cc66;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #66cc66;">&#123;</span>
		LdapUtils.<span style="color: #006600;">closeContext</span><span style="color: #66cc66;">&#40;</span>ctx<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">class</span> DnContextMapper <span style="color: #000000; font-weight: bold;">extends</span>
		AbstractParameterizedContextMapper&lt;String&gt; <span style="color: #66cc66;">&#123;</span>
	@Override
	<span style="color: #000000; font-weight: bold;">protected</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> doMapFromContext<span style="color: #66cc66;">&#40;</span>DirContextOperations ctx<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> ctx.<span style="color: #006600;">getNameInNamespace</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The required XML configuration for this:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.LdapTemplate&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.support.LdapContextSource&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap://my.ldap.server&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;base&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;dc=mycompany, dc=com&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;cn=Administrator, ou=system&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;secret&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dummy&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;se.jayway.web.Dummy&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<h3>LDAP Data Management</h3>
<p>Working with data in LDAP is usually tedious and verbose. Spring LDAP relieves the programmer from explicitly worrying about the details of the underlying Attributes and encapsulates all data regarding an LDAP entry in the <code>DirContextAdapter</code> class. You can get the Attributes of an entry using a <code>DirContextAdapter</code> in a <code>ContextMapper</code> (or <code>ParameterizedContextMapper</code> like above), or you can use the Attribute management capabilities in <code>DirContextAdapter</code> to help you when performing updates or creating entries.</p>
<p>This has been one of the key features from Spring LDAP from the very beginning, and the API has been improved further in this release; particularly a new <code>bind</code> has been added in Spring LDAP, enabling even simpler standard repository code using Spring LDAP:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> create<span style="color: #66cc66;">&#40;</span>Person p<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	p.<span style="color: #006600;">setDn</span><span style="color: #66cc66;">&#40;</span>buildDn<span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	DirContextOperations ctx = <span style="color: #000000; font-weight: bold;">new</span> DirContextAdapter<span style="color: #66cc66;">&#40;</span>p.<span style="color: #006600;">getDn</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	setAttributeValues<span style="color: #66cc66;">&#40;</span>p, ctx<span style="color: #66cc66;">&#41;</span>;
	ldapTemplate.<span style="color: #006600;">bind</span><span style="color: #66cc66;">&#40;</span>ctx<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> update<span style="color: #66cc66;">&#40;</span>Person p<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	DirContextOperations ctx = ldapTemplate.<span style="color: #006600;">lookupContext</span><span style="color: #66cc66;">&#40;</span>p.<span style="color: #006600;">getDn</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	setAttributeValues<span style="color: #66cc66;">&#40;</span>p, ctx<span style="color: #66cc66;">&#41;</span>;
	ldapTemplate.<span style="color: #006600;">modifyAttributes</span><span style="color: #66cc66;">&#40;</span>ctx<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">void</span> setAttributeValues<span style="color: #66cc66;">&#40;</span>Person p, DirContextOperations ctx<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	ctx.<span style="color: #006600;">setAttributeValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;description&quot;</span>, p.<span style="color: #006600;">getDescription</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	ctx.<span style="color: #006600;">setAttributeValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;telephoneNumber&quot;</span>, p.<span style="color: #006600;">getPhone</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #808080; font-style: italic;">// Set more attribute values here.</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p><code>DirContextAdapter</code> now also supports entries that represent referrals. This means that if you configure your <code>ContextSource</code> to follow referrals (setting the <code>referral</code> property to <code>follow</code> and properly configuring DNS settings so that the server names of the referrals can be resolved) you can get the server URL from any <code>DirContextAdapter</code> resulting from referrals.</p>
<h3>TLS Connections</h3>
<p>It is a very common setup that the LDAP server is configured only to accept TLS connections. This has previously not been supported by Spring LDAP, but due to some internal rework in <code>AbstractContextSource</code> it is now possible to perform some more elaborate authentication and connection negotiation logic by supplying a <code>DirContextAuthenticationStrategy</code> implementation to the <code>ContextSource</code>. To enable TLS connections you will supply a <code>DefaultTlsDirContextAuthenticationStrategy</code> to your <code>LdapContextSource</code>:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.support.LdapContextSource&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap://my.ldap.server&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;base&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;dc=mycompany, dc=com&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;cn=Administrator, ou=system&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;secret&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;authenticationStrategy&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span>
			<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/property<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Authentication customization has previously often been done by subclassing <code>LdapContextSource</code>. The recommended approach from Spring LDAP 1.3 is to create a custom <code>DirContextAuthenticationStrategy</code> implementation to suit your need. This would be useful for e.g. LDAP Proxy Authentication or similar functionality.</p>
<h3>Major Bug Fixes and Other Changes</h3>
<p>Some interesting bug fixes are included in Spring LDAP. Also, some default behavior has been changed; the most important stuff is listed here:</p>
<h4>Distinguished Name toString representation</h4>
<p>It has long been requested that the Spring LDAP <code>DistinguishedName</code> <code>toString</code> representation should be changed. The <code>toString</code> representation has previously been focused on the readability of the string, adding spaces between the RDNs to make it less compact, e.g.:<br />
<code>cn=John Doe, ou=Some Company, c=Sweden</code><br />
Several users have been complaining that their DN representations have been compact and that the discrepancy has been causing problems:<br />
<code>cn=John Doe,ou=Some Company,c=Sweden</code><br />
We have changed the default string representation to the compact one in the 1.3 release. If your system should require the old, 'spaced' format, you can change the default by setting the system property <code>org.springframework.ldap.core.spacedDnFormat</code> to <code>true</code>.</p>
<h4>Built-in JNDI Connection Pooling</h4>
<p>The <code>pooled</code> property of <code>ContextSource</code> has previously defaulted to <code>true</code>, enabling the built-in Java LDAP connection pooling by default. However the built-in LDAP connection pooling suffers from several deficiencies (most notable there is no way of doing connection validation and configuration is cumbersome), which is why we decided to change the default to <code>false </code>. If you require connection pooling we strongly recommend using the Spring LDAP <a href="http://static.springframework.org/spring-ldap/docs/1.3.x/apidocs/org/springframework/ldap/pool/factory/PoolingContextSource.html"><code>PoolingContextSource</code></a> instead.</p>
<h4>The Dreaded '\' in Distinguished Names Problem</h4>
<p>Java JNDI cannot handle '\' in the Distinguished Names of entries in an LDAP tree. If they do, the DN returned from JNDI will be invalid, which previously caused Spring LDAP to throw an exception. We now work around this bug.</p>
<h3>Downloads</h3>
<p>We obviously want people to use our stuff. Here are the relevant links:<br />
<a href="http://dist.springframework.org/milestone/LDAP/spring-ldap-1.3.0.RC1.zip">Binaries</a>(<a href="http://dist.springframework.org/milestone/LDAP/spring-ldap-1.3.0.RC1.zip.sha1">sha</a>)<br />
<a href="<br />
http://dist.springframework.org/milestone/LDAP/spring-ldap-1.3.0.RC1-with-dependencies.zip">Binary With Dependencies</a>(<a href="http://dist.springframework.org/milestone/LDAP/spring-ldap-1.3.0.RC1-with-dependencies.zip.sha1">sha</a>)<br />
<a href="http://static.springframework.org/spring-ldap/docs/1.3.x/apidocs/">Javadocs</a><br />
<a href="http://static.springframework.org/spring-ldap/docs/1.3.x/reference/pdf/spring-ldap-reference.pdf">Reference docs</a></p>
<h3>Maven Users</h3>
<p>Since this is a release candidate it is not published to the main maven repository. It is however available from the Spring Framework milestone repository:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;repositories<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;repository<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;id<span style="font-weight: bold; color: black;">&gt;</span></span></span>spring-milestone<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/id<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;name<span style="font-weight: bold; color: black;">&gt;</span></span></span>Spring Portfolio Milestone Repository<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;url<span style="font-weight: bold; color: black;">&gt;</span></span></span>http://s3.amazonaws.com/maven.springframework.org/milestone<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/url<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/repository<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/repositories<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>The maven dependencies are as follows:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.springframework.ldap<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>spring-ldap-core<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>1.3.0.RC1<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.springframework.ldap<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>spring-ldap-core-tiger<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>1.3.0.RC1<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<h3>Summary</h3>
<p>In addition to the above there's quite a number of minor feature enhancements and bug fixes. The full change log can be found <a href="http://static.springframework.org/spring-ldap/docs/1.3.x/changelog.txt">here</a>. We're obviously very interested in getting your feedback. Please post any comments you might have on the <a href="http://forum.springframework.org/forumdisplay.php?f=40">Sping LDAP Support Forum</a>. Bugs should be submitted to the <a href="http://jira.springframework.org/browse/LDAP">Spring Framework Jira System</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/27/whats-new-in-spring-ldap-13/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Testing Among the Clouds, Part 2</title>
		<link>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/</link>
		<comments>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 14:22:56 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[typica]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=357</guid>
		<description><![CDATA[In a recent post I wrote about the particular problems we've been having with integration testing the Spring LDAP project and the use we've made of Amazon EC2 for solving these problems. In this post I'll present the implementation details. Prerequisites In order to keep this reasonably brief I'll have to refer to the getting [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a target="_blank" href="http://blog.jayway.com/2008/09/11/testing-among-the-clouds/">recent post</a> I wrote about the particular problems we've been having with integration testing the <a target="_blank" href="http://springframework.org/ldap">Spring LDAP</a> project and the use we've made of <a target="_blank" href="http://aws.amazon.com/ec2/">Amazon EC2</a> for solving these problems. In this post I'll present the implementation details.</p>
<h3>Prerequisites</h3>
<p>In order to keep this reasonably brief I'll have to refer to the <a target="_blank" href="http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/">getting started guide</a> for information on how to get going with Amazon EC2.</p>
<h3>A FactoryBean to Launch EC2 Instances</h3>
<p>What we want to achieve here is to launch an EC2 instance transparently and independently of the actual test code. Ideally, the test code should be oblivious of the target server and we want to externalize those details to external configuration. We will use Spring's excellent JUnit test support to automatically wire the integration test setup and make sure that the target server is up and running before the actual test code is running.</p>
<p>A powerful way to transparently perform complex initialization logic when using Spring is the <a target="_blank" href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-extension-factorybean"><code>FactoryBean</code></a> concept. We will create a <code>FactoryBean</code> implementation to launch the EC2 image and set up our target resource:</p>
<pre class="java">AbstractEc2InstanceLaunchingFactoryBean.<span style="color: #006600;">java</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> AbstractEc2InstanceLaunchingFactoryBean <span style="color: #000000; font-weight: bold;">extends</span> AbstractFactoryBean <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">int</span> INSTANCE_START_SLEEP_TIME = <span style="color: #cc66cc;">1000</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> DEFAULT_PREPARATION_SLEEP_TIME = <span style="color: #cc66cc;">30000</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Log log = LogFactory.<span style="color: #006600;">getLog</span><span style="color: #66cc66;">&#40;</span>AbstractEc2InstanceLaunchingFactoryBean.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> imageName;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsKey;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsSecretKey;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> keypairName;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> groupName;
  <span style="color: #000000; font-weight: bold;">private</span> Instance instance;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">long</span> preparationSleepTime = DEFAULT_PREPARATION_SLEEP_TIME;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setImageName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> imageName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">imageName</span> = imageName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setAwsKey<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsKey<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">awsKey</span> = awsKey;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setAwsSecretKey<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsSecretKey<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">awsSecretKey</span> = awsSecretKey;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setKeypairName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> keypairName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">keypairName</span> = keypairName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setGroupName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> groupName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">groupName</span> = groupName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setPreparationSleepTime<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">long</span> preparationSleepTime<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">preparationSleepTime</span> = preparationSleepTime;
  <span style="color: #66cc66;">&#125;</span>
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> createInstance<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>imageName, <span style="color: #ff0000;">&quot;ImageName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>awsKey, <span style="color: #ff0000;">&quot;AwsKey must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>awsSecretKey, <span style="color: #ff0000;">&quot;AwsSecretKey must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>keypairName, <span style="color: #ff0000;">&quot;KeyName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>groupName, <span style="color: #ff0000;">&quot;GroupName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
      log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Launching EC2 instance for image: &quot;</span> + imageName<span style="color: #66cc66;">&#41;</span>;
&nbsp;
      Jec2 jec2 = <span style="color: #000000; font-weight: bold;">new</span> Jec2<span style="color: #66cc66;">&#40;</span>awsKey, awsSecretKey<span style="color: #66cc66;">&#41;</span>;
      LaunchConfiguration launchConfiguration = <span style="color: #000000; font-weight: bold;">new</span> LaunchConfiguration<span style="color: #66cc66;">&#40;</span>imageName<span style="color: #66cc66;">&#41;</span>;
      launchConfiguration.<span style="color: #006600;">setKeyName</span><span style="color: #66cc66;">&#40;</span>keypairName<span style="color: #66cc66;">&#41;</span>;
      launchConfiguration.<span style="color: #006600;">setSecurityGroup</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span>groupName<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
      ReservationDescription reservationDescription = jec2.<span style="color: #006600;">runInstances</span><span style="color: #66cc66;">&#40;</span>launchConfiguration<span style="color: #66cc66;">&#41;</span>;
      instance = reservationDescription.<span style="color: #006600;">getInstances</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: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>!instance.<span style="color: #006600;">isRunning</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &amp;&amp; !instance.<span style="color: #006600;">isTerminated</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
          log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Instance still starting up; sleeping &quot;</span> + INSTANCE_START_SLEEP_TIME + <span style="color: #ff0000;">&quot;ms&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a>.<span style="color: #006600;">sleep</span><span style="color: #66cc66;">&#40;</span>INSTANCE_START_SLEEP_TIME<span style="color: #66cc66;">&#41;</span>;
          reservationDescription = jec2.<span style="color: #006600;">describeInstances</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">getInstanceId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
          instance = reservationDescription.<span style="color: #006600;">getInstances</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: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">isRunning</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
          log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;EC2 instance is now running&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>preparationSleepTime &gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
              log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Sleeping &quot;</span> + preparationSleepTime + <span style="color: #ff0000;">&quot;ms allowing instance services to start up properly.&quot;</span><span style="color: #66cc66;">&#41;</span>;
              <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a>.<span style="color: #006600;">sleep</span><span style="color: #66cc66;">&#40;</span>preparationSleepTime<span style="color: #66cc66;">&#41;</span>;
              log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Instance prepared - proceeding&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <span style="color: #66cc66;">&#125;</span>
          <span style="color: #000000; font-weight: bold;">return</span> doCreateInstance<span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">getDnsName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
          <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIllegalStateException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalStateException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Failed to start a new instance&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> doCreateInstance<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> ip<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a>;
&nbsp;
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> destroyInstance<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> ignored<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">instance</span> != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Shutting down instance&quot;</span><span style="color: #66cc66;">&#41;</span>;
      Jec2 jec2 = <span style="color: #000000; font-weight: bold;">new</span> Jec2<span style="color: #66cc66;">&#40;</span>awsKey, awsSecretKey<span style="color: #66cc66;">&#41;</span>;
      jec2.<span style="color: #006600;">terminateInstances</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">instance</span>.<span style="color: #006600;">getInstanceId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This superclass makes use of the <a target="_blank" href="http://code.google.com/p/typica/">typica</a> library (<a target="_blank" href="http://mvnrepository.com/artifact/com.google.code.typica/typica">also available in maven</a>) to launch the EC2 instance and delegates to <code>doCreateInstance</code> for creating the target resource that we will use in our test case. In our setup we want to create a <code>ContextSource</code>, which is the Spring LDAP equivalent of a <code>DataSource</code>:</p>
<pre class="java">ContextSourceEc2InstanceLaunchingFactoryBean.<span style="color: #006600;">java</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContextSourceEc2InstanceLaunchingFactoryBean <span style="color: #000000; font-weight: bold;">extends</span> AbstractEc2InstanceLaunchingFactoryBean <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> base;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> userDn;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password;
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">Class</span> getObjectType<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> ContextSource.<span style="color: #000000; font-weight: bold;">class</span>;
  <span style="color: #66cc66;">&#125;</span>
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> doCreateInstance<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">final</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> dnsName<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasText</span><span style="color: #66cc66;">&#40;</span>userDn<span style="color: #66cc66;">&#41;</span>;
    LdapContextSource instance = <span style="color: #000000; font-weight: bold;">new</span> LdapContextSource<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setUrl</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ldap://&quot;</span> + dnsName<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setUserDn</span><span style="color: #66cc66;">&#40;</span>userDn<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setPassword</span><span style="color: #66cc66;">&#40;</span>password<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setBase</span><span style="color: #66cc66;">&#40;</span>base<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    instance.<span style="color: #006600;">afterPropertiesSet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">return</span> instance;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setBase<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> base<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">base</span> = base;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setUserDn<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> userDn<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">userDn</span> = userDn;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setPassword<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">password</span> = password;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Note that the <code>AbstractEc2InstanceLaunchingFactoryBean</code> will wait for the instance to start up properly. It will also wait an additional period of time once the instance is up and running to allow for all relevant services to start up properly. Finally it will  automatically close down the launched instance once it is properly shut down (which it will be when executing using the Spring automated test support).</p>
<h3>Test Case Configuration</h3>
<p>We now have the infrastructure to have the EC2 instance launched transparently from a Spring Application Context. All we need to do is configure it:</p>
<pre class="xml">testContext.xml
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap.properties&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;systemPropertiesModeName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;SYSTEM_PROPERTIES_MODE_OVERRIDE&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.ContextSourceEc2InstanceLaunchingFactoryBean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;awsKey&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.key}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;awsSecretKey&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.secret.key}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;imageName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.ami}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;groupName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.security.group}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;keypairName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.keypair}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;base&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;dc=jayway,dc=se&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${userDn}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${password}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span>
  <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.LdapTemplate&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>We are referring to <code>ldap.properties</code> for the actual settings:</p>
<pre>
userDn=cn=admin,dc=jayway,dc=se
password=secret
base=dc=jayway,dc=se
aws.ami=ami-56ec083f
aws.keypair=spring-ldap-keypair
aws.security.group=spring-ldap
</pre>
<p>The referenced AMI is a public image specifically set up for our test cases. It has OpenLDAP installed and has been pre-populated with the test data that our test cases expect.</p>
<p>Note that we are not specifying any property value for <code>aws.key</code> and <code>aws.secret.key</code>, as this is the Amazon account access information. That will be the account settings of the individual developer and should be supplied at runtime using system properties (e.g. <code>mvn -Daws.key=xxxxxxx -Daws.secret.key=xxxxxx test</code>).</p>
<h3>Performing the Test</h3>
<p>Now all we need to do is use Spring's automated test support to start our test:</p>
<pre class="java">SomeLdapITest.<span style="color: #006600;">java</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span>locations = <span style="color: #66cc66;">&#123;</span> <span style="color: #ff0000;">&quot;testContext.xml&quot;</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SomeLdapITest <span style="color: #000000; font-weight: bold;">extends</span> AbstractJUnit4SpringContextTests <span style="color: #66cc66;">&#123;</span>
  @Autowired
  <span style="color: #000000; font-weight: bold;">private</span> LdapTemplate tested;
&nbsp;
  @Test
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testSomething<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">// Use the automatically injected LdapTemplate instance to perform a test.</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<h3>Set to Go</h3>
<p>With the above you should be all set to go to start using this powerful approach to integration testing. The actual code is available with the 1.3.0.RC1 release of Spring LDAP; links to downloads and documentation available <a href="http://www.springframework.org/ldap">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Remoting with Security and SSL</title>
		<link>http://blog.jayway.com/2008/09/30/spring-remoting-with-security-and-ssl/</link>
		<comments>http://blog.jayway.com/2008/09/30/spring-remoting-with-security-and-ssl/#comments</comments>
		<pubDate>Tue, 30 Sep 2008 19:15:17 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring remoting]]></category>
		<category><![CDATA[spring security]]></category>
		<category><![CDATA[ssl]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=311</guid>
		<description><![CDATA[One of my favorite features of the Spring Framework is the Spring Remoting part, which enables you to expose any bean in a Spring Application Context as a remote service over HTTP. It's fast, it's easy, and it's really, really simple. Basic Spring Remoting Configuration In the general situation all you need to do is [...]]]></description>
			<content:encoded><![CDATA[<p>One of my favorite features of the Spring Framework is the Spring Remoting part, which enables you to expose any bean in a Spring Application Context as a remote service over HTTP. It's fast, it's easy, and it's really, really simple.</p>
<h3>Basic Spring Remoting Configuration</h3>
<p>In the general situation all you need to do is create a DispatcherServlet (just as you would with any Spring MVC application), add an Exporter on the server side and reference a ProxyFactoryBean on the client.<br />
On the server side:</p>
<pre class="xml">web.xml
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;context-param<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;param-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>contextConfigLocation<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/param-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;param-value<span style="font-weight: bold; color: black;">&gt;</span></span></span>/WEB-INF/applicationContext.xml<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/param-value<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/context-param<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;listener<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;listener-class<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.springframework.web.context.ContextLoaderListener<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/listener-class<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/listener<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;servlet<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;servlet-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>demo<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/servlet-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;servlet-class<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.springframework.web.servlet.DispatcherServlet<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/servlet-class<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;init-param<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;param-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>contextConfigLocation<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/param-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;param-value<span style="font-weight: bold; color: black;">&gt;</span></span></span>/WEB-INF/demo-servlet.xml<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/param-value<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/init-param<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;load-on-startup<span style="font-weight: bold; color: black;">&gt;</span></span></span>1<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/load-on-startup<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/servlet<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;servlet-mapping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;servlet-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>demo<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/servlet-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;url-pattern<span style="font-weight: bold; color: black;">&gt;</span></span></span>/*<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/url-pattern<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/servlet-mapping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<pre class="xml">demo-servlet.xml - exposes bean 'helloService' as remote service
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;/hello&quot;</span>
    <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;service&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;helloService&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;serviceInterface&quot;</span>
      <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;se.jayway.demo.server.HelloService&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>On the client side:</p>
<pre class="xml">clientContext.xml
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;helloService&quot;</span>
  <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;serviceUrl&quot;</span>
      <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;https://remote-host:8080/security-remoting/hello&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;serviceInterface&quot;</span>
      <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;se.jayway.demo.server.HelloService&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Now, in the client application all you need to do is ask for the '<code>helloService</code>' bean and you will be handed a proxy that talks to the target service on the server without the server or the client knowing anything about it.</p>
<h3>Securing the Remote Service</h3>
<p>Now, in many cases you'll want to apply some security restrictions on the exposed HTTP service. Being in the Spring world the natural choice for this purpose will be Spring Security. Far from the complications of its predecessor Acegi, Spring Security configuration is now a matter of very few lines of XML code: </p>
<pre class="xml">web.xml
...
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>springSecurityFilterChain<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter-class<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.springframework.web.filter.DelegatingFilterProxy<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter-class<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter-mapping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;filter-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>springSecurityFilterChain<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter-name<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;url-pattern<span style="font-weight: bold; color: black;">&gt;</span></span></span>/*<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/url-pattern<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/filter-mapping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
...
&nbsp;</pre>
<pre class="xml">demo-servlet.xml - additions to the original file above; default with one hard coded user
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;beans</span>
  <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span>
  <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span>
  <span style="color: #000066;">xmlns:sec</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/security&quot;</span>
  <span style="color: #000066;">xsi:schemaLocation</span>=
        <span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans 
&nbsp;
http://www.springframework.org/schema/beans/spring-beans.xsd
&nbsp;
http://www.springframework.org/schema/security
&nbsp;
         http://www.springframework.org/schema/security/spring-security-2.0.xsd&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
...
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:http</span> <span style="color: #000066;">realm</span>=<span style="color: #ff0000;">&quot;Hello App&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:http-basic</span><span style="font-weight: bold; color: black;">/&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:intercept-url</span> <span style="color: #000066;">pattern</span>=<span style="color: #ff0000;">&quot;/**&quot;</span> <span style="color: #000066;">access</span>=<span style="color: #ff0000;">&quot;ROLE_USER&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/sec:http<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:authentication-provider<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:user-service<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;sec:user</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;someuser&quot;</span> <span style="color: #000066;">password</span>=<span style="color: #ff0000;">&quot;somepassword&quot;</span> <span style="color: #000066;">authorities</span>=<span style="color: #ff0000;">&quot;ROLE_USER&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/sec:user-service<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/sec:authentication-provider<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Note that we're defining the Spring Security XML schema in the schema definition.</p>
<pre class="xml">clientContext.xml
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;helloService&quot;</span>
  <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;serviceUrl&quot;</span>
      <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;https://remote-host:8080/security-remoting/hello&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;serviceInterface&quot;</span>
      <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;se.jayway.demo.server.HelloService&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;httpInvokerRequestExecutor&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.security.context.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor  /&gt;</span>
  <span style="color: #009900;">&lt;/property&gt;</span>
<span style="color: #009900;">&lt;/bean&gt;</span>
</span></pre>
<p>The <code>AuthenticationSimpleHttpInvokerRequestExecutor</code> will make sure that any Spring Security applied on the client side will be transferred to the server side using Basic HTTP Authentication. The filters and the XML configuration on the server side will make sure the Authentication headers are inspected and checked against the valid principals and credentials.</p>
<h3>Applying SSL</h3>
<p>As most of you probably know, Basic HTTP Authentication is pretty much the same thing as sending the authentication information over the network in plain text. This is why you will typically want to use encrypted connections whenever you are working with this type of authentication. This gets us into the core of this post, because it's here it becomes tricky.</p>
<p>In the ideal world you would just configure your web server to expose the service over HTTPS, change the target URL on the client side and be on your way. The reality however is slightly more complicated. </p>
<p>The problem is that you the built-in <code>HttpURLConnection</code> class on which the <code>AuthenticationSimpleHttpInvokerRequestExecutor</code> relies is very picky when it comes to certificates. What you want to do when working with SSL in Spring Remoting is to use the <code>CommonsHttpInvokerRequestExecutor</code>, which relies on Commons HttpClient - a more flexible and capable HTTP client. Now, the problem with this is that then you cannot use the <code>AuthenticationSimpleHttpInvokerRequestExecutor</code> anymore - they plug into the <code>HttpInvokerProxyFactoryBean</code> at the same extension point.</p>
<p>It boils down to this: if you want to use Spring Remoting and Spring Security over SSL you will need to implement your own <code>HttpInvokerRequestExecutor</code>:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> BasicAuthenticationCommonsHttpInvokerRequestExecutor <span style="color: #000000; font-weight: bold;">extends</span>
  CommonsHttpInvokerRequestExecutor <span style="color: #66cc66;">&#123;</span>
&nbsp;
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> PostMethod createPostMethod<span style="color: #66cc66;">&#40;</span>HttpInvokerClientConfiguration config<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIOException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IOException</span></a> <span style="color: #66cc66;">&#123;</span>
    PostMethod postMethod = <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">createPostMethod</span><span style="color: #66cc66;">&#40;</span>config<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    Authentication auth =
        SecurityContextHolder.<span style="color: #006600;">getContext</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getAuthentication</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>auth != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> &amp;&amp; <span style="color: #66cc66;">&#40;</span>auth.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> &amp;&amp;
          <span style="color: #66cc66;">&#40;</span>auth.<span style="color: #006600;">getCredentials</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> base64 = auth.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">&quot;:&quot;</span> + auth.<span style="color: #006600;">getCredentials</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      postMethod.<span style="color: #006600;">setRequestHeader</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Authorization&quot;</span>, <span style="color: #ff0000;">&quot;Basic &quot;</span> +
          <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#40;</span>Base64.<span style="color: #006600;">encodeBase64</span><span style="color: #66cc66;">&#40;</span>base64.<span style="color: #006600;">getBytes</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">return</span> postMethod;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now all you need to do is specify this implementation as <code>HttpInvokerRequestExecutor</code> for your client ProxyFactoryBean and you're all set:</p>
<pre class="xml">clientContext.xml
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;helloService&quot;</span>
  <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;serviceUrl&quot;</span>
      <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;https://remote-host:8080/security-remoting/hello&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;serviceInterface&quot;</span>
      <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;se.jayway.demo.server.HelloService&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;httpInvokerRequestExecutor&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;se.jayway.demo.security.BasicAuthenticationCommonsHttpInvokerRequestExecutor&quot;</span>  <span style="font-weight: bold; color: black;">/&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/property<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/09/30/spring-remoting-with-security-and-ssl/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Testing Among the Clouds</title>
		<link>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/</link>
		<comments>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 08:53:26 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[typica]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=77</guid>
		<description><![CDATA[One of the major challenges we've been facing in the Spring LDAP project is to make certain that the library works together with different LDAP servers. Different servers behave differently in certain situations; some functionality might only be supported on select servers, etc. In the ideal situation we would run our automated test suite against [...]]]></description>
			<content:encoded><![CDATA[<p>One of the major challenges we've been facing in the <a title="Spring LDAP" href="http://springframework.org/ldap" target="_blank">Spring LDAP</a> project is to make certain that the library works together with different LDAP servers. Different servers behave differently in certain situations; some functionality might only be supported on select servers, etc. In the ideal situation we would run our automated test suite against a multitude of target platforms for each change made to the code. Each developer would be able to run the test suite locally against each of these platforms, and the <a href="http://build.springframework.org:8085/browse/LDAP" target="_blank">continuous integration server</a> would automatically run them on each commit. This is the key element to automated testing: the automated tests must be relevant, and they must be quickly and easily run at any time, by any member of the team (or - in this case, being an open source project - by anyone that might have checked the source out from subversion). These conditions are imperative for any type of automated tests - if the conditions are not fulfilled the tests will not be run at all and consequently they will die.</p>
<p>In the perfect world, each developer would at all times have access to a server park with all of these different server versions installed. Reality is however almost always a different question: Being an Open Source project with limited funding and developers located throughout the world this has been impossible for us, up until now. You're probably already guessing: The answer is in the Clouds.</p>
<p>Having used <a href="http://www.amazon.com/gp/browse.html?node=201590011" target="_blank">Amazon EC2</a> in a couple of customer projects, we suddenly realized this is the answer to our problems. For those of you not completely familiar with the concept, the general idea of Amazon EC2 is that you configure one or several <strong>machine images</strong>, installing whatever software and data you might need on each image. You will then start an <strong>instance</strong> from one of these pre-configured images, which will in effect start up a virtual computer somewhere in the amazon cloud, a computer that will then be yours to play around with in any way you might like until you're finished with it and just shut the instance down. All of this is available at a very reasonable pricing - you pay only (a very modest amount) for the time that your instances have been running.</p>
<p>The concept suits us perfectly: we want a number of isolated environments, each with a known start state where we can run our test suite against a particular server setup. So that's what we've started to do: we have now created an EC2 image with an Open LDAP installation, pre-loaded with the data that our test cases expect. We then devised support classes to have the JUnit test cases automatically start an appropriate instance (using the excellent <a href="http://code.google.com/p/typica/" target="_blank">typica</a> library), run the tests against the started virtual machines, and shut down the instance after the tests are finished (regardless of the outcome - we don't want any stray instances running around costing us money <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ). We still have some more work to do with setting up more images for other server setups, but we're hoping to get that work going as we move on...</p>
<p>I'm planning to dig a little bit deeper into the details of the setup and the code involved in a later post. In the meantime: if you're really interested, feel free to check the code out from the <a href="https://springframework.svn.sourceforge.net/svnroot/springframework/spring-ldap/trunk/mvn-build" target="_blank">svn repo</a> and have a look at what we've done so far. The relevant code for this is in the test/integration-tests-openldap directory.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sweden Spring UG Birth of a new UG</title>
		<link>http://blog.jayway.com/2007/05/01/sweden-spring-ug-birth-of-a-new-ug/</link>
		<comments>http://blog.jayway.com/2007/05/01/sweden-spring-ug-birth-of-a-new-ug/#comments</comments>
		<pubDate>Tue, 01 May 2007 15:56:33 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[user group]]></category>

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=3809</guid>
		<description><![CDATA[The Java Naming and Directory Interface (JNDI) is for LDAP programming what Java Database Connectivity (JDBC) is for SQL programming. There are several similarities between JDBC and JNDI/LDAP (Java LDAP). Despite being two completely different APIs with different pros and cons, they share a number of less flattering characteristics: They require extensive plumbing code, even [...]]]></description>
			<content:encoded><![CDATA[<p><strong>The Java Naming and Directory Interface (JNDI) is for LDAP programming what Java Database Connectivity (JDBC) is for SQL programming. There are several similarities between JDBC and JNDI/LDAP (Java LDAP). Despite being two completely different APIs with different pros and cons, they share a number of less flattering characteristics:<br />
</strong></p>
<ul>
<li> They require extensive plumbing code, even to perform the simplest of tasks.
<li> All resources need to be correctly closed, no matter what happens.
<li> Exception handling is difficult.
</ul>
<p>The above points often lead to massive code duplication in common usages of the<br />
APIs. As we all know, code duplication is one of the worst code smells. All in all, it<br />
boils down to this: JDBC and LDAP programming in Java are both incredibly dull<br />
and repetitive.<br />
Spring JDBC, a part of the Spring framework, provides excellent utilities for sim-<br />
plifying SQL programming. We need a similar framework for Java LDAP program-<br />
ming. </p>
<h2>The Traditional Way </h2>
<p>Consider, for example, a method that should search some storage for all persons and<br />
return their names in a list. Using JDBC, we would create a connection and execute<br />
a query using a statement. We would then loop over the result set and retrieve the<br />
column we want, adding it to a list. By contrast, using Java LDAP, we would create a<br />
context and perform a search using a search filter. We would then loop over the re-<br />
sulting naming enumeration and retrieve the attribute we want, adding it to a list.<br />
The traditional way of implementing this person name search method in Java<br />
LDAP is this: </p>
<pre>public class TraditionalPersonDaoImpl implements
         PersonDao {
   public List getAllPersonNames() {
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY,
         ”com.sun.jndi.ldap.LdapCtxFactory”);
      env.put(Context.PROVIDER_URL,
         ”ldap://localhost:389/dc=jayway,dc=se”);
      DirContext ctx;
      try {
         ctx = new InitialDirContext(env);
      } catch (NamingException e) {
         throw new RuntimeException(e);
      }
      LinkedList list = new LinkedList();
      NamingEnumeration results = null;
      try {
         SearchControls controls =
            new SearchControls();
         controls.setSearchScope(
            SearchControls.SUBTREE_SCOPE);
         results = ctx.search(
            ””, ”(objectclass=person)”, controls);
         while (results.hasMore()) {
            SearchResult searchResult =
               (SearchResult) results.next();
            Attributes attributes =
               searchResult.getAttributes();
            Attribute attr = attributes.get(”cn”);
            String cn = (String) attr.get();
            list.add(cn);
         }
      } catch (NameNotFoundException e) {
         // The base context was not found.
         // Just clean up and exit.
      } catch (NamingException e) {
         throw new RuntimeException(e);
      } finally {
         if (results != null) {
            try {
               results.close();
            } catch (Exception e) {
               // Never mind this.
            }
         }
         if (ctx != null) {
            try {
               ctx.close();
            } catch (Exception e) {
               // Never mind this.
            }
         }
      }
      return list;
   }
} </pre>
<p>The method above produces a list containing the cn (common name) attribute of<br />
the person objects found in the database. It is important to always close the naming<br />
enumeration and the context. The same procedural manner of programming needs<br />
to be used whether you want to search, create, update or delete data. It’s easy to see<br />
how this leads to massive code duplication. </p>
<h2>Introducing Spring LDAP </h2>
<p>The above made us realize the need for help, which is why we created the Spring<br />
LDAP project. It’s a library for simpler LDAP programming in Java, built on the<br />
same principles as Spring JDBC. It was recently included as a Spring Framework<br />
sub project.<br />
Spring LDAP completely eliminates the need to worry about creating and closing<br />
<strong>DirContext</strong> and looping through <strong>NamingEnumeration</strong>. It also provides a more<br />
comprehensive unchecked exception hierarchy, built on Spring’s <strong>DataAccessEx-<br />
ception</strong>. As a bonus, it also contains classes for dynamically building LDAP filters<br />
and distinguished names. An LDAP filter corresponds somewhat to the WHERE<br />
clause in a SQL SELECT statement. A distinguished name (dn) can be seen as a<br />
handle or the path to a specific object in the LDAP database. If the dn is available,<br />
an object can be looked up directly, rather than having to be searched for.<br />
This article will present the core features of Spring LDAP and demonstrate how<br />
LDAP programming really can be made simple. </p>
<h2>Searches using AttributesMapper </h2>
<p>In this example, we will use an <strong>AttributesMapper</strong> to easily build a list of all common<br />
names of all person objects. This is exactly what we did in the earlier example using<br />
the traditional way. </p>
<pre>public class PersonDaoImpl implements PersonDao {
   private LdapTemplate ldapTemplate;
   public void setLdapTemplate(LdapTemplate ldapTemplate) {
      this.ldapTemplate = ldapTemplate;
   }
   public List getAllPersonNames() {
      return ldapTemplate.search(
         ””, ”(objectclass=person)”,
         new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs)
               throws NamingException {
               return attrs.get(”cn”).get();
            }
         });
   }
}
</pre>
<p>The inline implementation of <strong>AttributesMapper</strong> just gets the desired attribute<br />
value from the <strong>Attributes</strong> and returns it. Internally, Spring LDAP iterates over<br />
all entries found, calling the given <strong>AttributesMapper</strong> for each entry, and collects<br />
the results in a list. The list is then returned by the search method.<br />
Note that the <strong>AttributesMapper</strong> implementation could easily be modified to<br />
return a full Person object: </p>
<pre>public class PersonDaoImpl implements PersonDao {
   private LdapTemplate ldapTemplate;
   ...
   private static class PersonAttributesMapper
      implements AttributesMapper {
      public Object mapFromAttributes(Attributes attrs)
         throws NamingException {
         Person person = new Person();
         person.setFullName((String)attrs.get(”cn”).get());
         person.setLastName((String)attrs.get(”sn”).get());
         person.setDescription((String)attrs.get(”description”).get());
         return person;
      }
   }
   public List getAllPersons() {
      return ldapTemplate.search(
         ””, ”(objectclass=person)”,
         new PersonAttributesMapper();
   }
}
</pre>
<h2>Dynamically Building Distinguished Names </h2>
<p>The standard <strong>Name</strong> interface represents a generic name, which is basically an or-<br />
dered sequence of components. The <strong>Name</strong> interface also provides operations on that<br />
sequence; e.g., add or remove. Spring LDAP provides an implementation of the<br />
<strong>Name</strong> interface: <strong>DistinguishedName</strong>. Using this class greatly simplifies building<br />
distinguished names, especially considering the sometimes complex rules regarding<br />
escapings and encodings. The following example illustrates how <strong>Distinguished-<br />
Name</strong> can be used to dynamically construct a distinguished name:<br />
public static final String BASE_DN = ”dc=jayway, dc=se”; </p>
<pre>...
protected Name buildDn(Person p) {
   DistinguishedName dn = new DistinguishedName(BASE_DN);
   dn.add(”c”, p.getCountry());
   dn.add(”ou”, p.getCompany());
   dn.add(”cn”, p.getFullname());
   return dn;
}
</pre>
<p>Assuming that a Person has the following attributes: </p>
<ul>
<li> <strong>country:</strong> Sweden
<li> <strong>company:</strong> Some Company
<li> <strong>fullname:</strong> Some Person<br />
then the result of the code above would be the following dn: <strong>cn=Some<br />
Person, ou=Some Company, c=Sweden, dc=jayway, dc=se </strong>
</ul>
<h2>Managing Attributes Using the DirContextAdapter </h2>
<p>As demonstrated above, values in LDAP are managed using <strong>Attributes</strong>. Working<br />
with <strong>Attributes</strong> is as dull and verbose as the rest of the standard LDAP API. This<br />
is why the Spring LDAP library provides the <strong>DirContextAdapter</strong>.<br />
Whenever a context is found in the LDAP tree, Spring LDAP will use its <strong>At-<br />
tributes</strong> to construct a <strong>DirContextAdapter</strong>. This enables us to use a <strong>Con-<br />
textMapper</strong> instead of an <strong>AttributesMapper</strong> to transform found values: </p>
<pre>public class PersonDaoImpl implements PersonDao {
   ...
   private static class PersonContextMapper
      implements ContextMapper {
      public Object mapFromContext(Object ctx) {
         DirContextAdapter context = (DirContextAdapter)ctx;
         Person p = new Person();
         p.setFullName(context.getStringAttribute(”cn”));
         p.setLastName(context.getStringAttribute(”sn”));
         p.setDescription(context.getStringAttribute(”description”));
         return p;
      }
   }
   public List getAllPersons() {
      return ldapTemplate.search(
         ””, ”(objectclass=person)”,
         new PersonContextMapper();
   }
}
</pre>
<p>While useful in searches and lookups, the <strong>DirContextAdapter</strong> is especially use-<br />
ful when creating and updating data, which will be described below. </p>
<h2>Binding Data </h2>
<p>Inserting data in Java LDAP is called binding. In order to do that, a distinguished<br />
name that uniquely identifies the new entry is required. The following example<br />
shows how data is bound using Spring LDAP:</p>
<pre>public void create(Person p) {
   Name dn = buildDn(p);
   DirContextAdapter context = new DirContextAdapter(dn);
   context.setAttributeValues(”objectclass”,
      new String[] {”top”, ”person”});
   context.setAttributeValue(”cn”, p.getFullname());
   context.setAttributeValue(”sn”, p.getLastname());
   context.setAttributeValue(”description”,
      p.getDescription());
   ldapTemplate.bind(dn, context, null);
}
</pre>
<h2>Unbinding Data</h2>
<p>Removing data in Java LDAP is called unbinding. A distinguished name (dn) is re-<br />
quired to identify the entry, just as in the binding operation. The following example<br />
shows how data is unbound using Spring LDAP:<br />
public class PersonDaoImpl implements PersonDao { </p>
<pre>   ...
   public void delete(Person p) {
      Name dn = buildDn(p);
      ldapTemplate.unbind(dn);
   }
}
Modifying Data
In Java LDAP, data is usually modified using modifyAttributes. Using the mo-
difyAttributes method you need to keep track of the changes and construct a
ModificationItem array with the updated data - once again very tedious work.
Luckily, DirContextAdapter does this for us:
public void update(Person p) {
   Name dn = buildDn(p);
   DirContextAdapter context =
      (DirContextAdapter)ldapTemplate.lookup(dn);
   context.setAttributeValues(”objectclass”,
      new String[] {”top”, ”person”});
   context.setAttributeValue(”cn”, p.getFullname());
   context.setAttributeValue(”sn”, p.getLastname());
   context.setAttributeValue(”description”,
      p.getDescription());
   ldapTemplate.modifyAttributes(dn,
      context.getModificationItems());
}
</pre>
<h2>Conclusion </h2>
<p>We have seen how Spring LDAP can provide substantial improvements compared<br />
to code using JNDI directly. There is no longer any need for creating contexts manu-<br />
ally or looping through naming enumerations. Nor is there any risk of forgetting to<br />
close any of those.<br />
By now it should be clear that the Spring LDAP library will be of great help for<br />
any Java project that communicates with LDAP. Further information is available on<br />
the Spring LDAP home page, including a full reference manual, API documenta-<br />
tion, and links for downloading the library. </p>
<p><em>Mattias Arthursson and Ulrik Sandberg</em></p>
<h2>Resources</h2>
<p>Spring LDAP home page<br />
<a href="http://www.springframework.org/ldap">http://www.springframework.org/ldap</a><br />
Sun's JNDI pages:<br />
<a href="http://java.sun.com/products/jndi/">http://java.sun.com/products/jndi/</a></p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2006/10/01/spring-ldap-%e2%80%93-ldap-programming-in-java-made-simple/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

