<?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>Java crumbs &#187; Articles in English</title>
	<atom:link href="http://blog.krecan.net/category/articles-in-english/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.krecan.net</link>
	<description>Short remarks from Java world</description>
	<lastBuildDate>Tue, 31 Jan 2012 20:13:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Maven, Eclipse, WTP and project dependencies</title>
		<link>http://blog.krecan.net/2011/09/05/maven-eclipse-wtp-and-project-dependencies/</link>
		<comments>http://blog.krecan.net/2011/09/05/maven-eclipse-wtp-and-project-dependencies/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 19:35:45 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[ClassNotFoundException]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[m2eclipse]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[WTP]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=966</guid>
		<description><![CDATA[If you are working with Maven, Eclipse and WTP, you can encounter different problems. One of them is connected to project dependencies. Imagine that you have an in-house library A and a web application B that depends on A. Sometimes, when I run the webapp in a server using WTP, it can not find classes [...]]]></description>
			<content:encoded><![CDATA[<p>If you are working with Maven, Eclipse and WTP, you can encounter different problems. </p>
<p>One of them is connected to project dependencies. Imagine that you have an in-house library A and a web application B that depends on A. Sometimes, when I run the webapp in a server using WTP, it can not find classes (or resources) from B. It's quite confusing if you get a ClassNotFoundException even though the class is apparently there. It happens only if you are using <a href="http://m2eclipse.sonatype.org/installing-m2eclipse.html">m2eclipse extras</a>. If you have different configuration this solution will not probably help you.</p>
<p>Ok, so you have m2extras and you are getting ClassNotFoundException. What next? You have to check file <strong>A/.settings/org.eclipse.wst.common.component</strong> (I use the Navigator View to access the file)</p>
<p>If you see something like this</p>
<pre name="code" class="xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project-modules id="moduleCoreId" project-version="1.5.0"&gt;
  &lt;wb-module deploy-name="module-a"&gt;
  &lt;wb-resource deploy-path="/" source-path="/src"/&gt;
  &lt;/wb-module&gt;
&lt;/project-modules&gt;
</pre>
<p>you have found the issue. The <code>source-path</code> attribute is wrong. It's necessary to set the value to <code>/src/main/java</code>. Sometimes the path is not just wrong, but it's completely missing. In such case just add a new line with corresponding configuration and everything should work as expected.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2011/09/05/maven-eclipse-wtp-and-project-dependencies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mock socket</title>
		<link>http://blog.krecan.net/2011/08/27/mock-socket/</link>
		<comments>http://blog.krecan.net/2011/08/27/mock-socket/#comments</comments>
		<pubDate>Sat, 27 Aug 2011 12:56:47 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Tests]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Mock]]></category>
		<category><![CDATA[Socket]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=948</guid>
		<description><![CDATA[Few months ago I have written a small tool that mocks network sockets in Java. Now I have some time to describe it, so here you are. Let's imagine you want to test network communication in Java. It's not easy, you have to start some server on the other side, configure its responses and somehow [...]]]></description>
			<content:encoded><![CDATA[<p>Few months ago I have written a <a href="https://github.com/lukas-krecan/mock-socket/">small tool that mocks network sockets in Java</a>. Now I have some time to describe it, so here you are. </p>
<p>Let's imagine you want to test network communication in Java. It's not easy, you have to start some server on the other side, configure its responses and somehow verify that the data you send are correct.</p>
<p>With mock-socket it's incredibly easy.</p>
<pre name="code" class="java">
import static net.javacrumbs.mocksocket.MockSocket.*;
...

//prepare mock
byte[] dataToWrite = new byte[]{5,4,3,2};
expectCall().andReturn(emptyResponse());

//do test
Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
IOUtils.write(dataToWrite, socket.getOutputStream());
socket.close();

//verify data sent
assertThat(recordedConnections().get(0), data(is(dataToWrite)));
assertThat(recordedConnections().get(0), address(is("example.org:1234")));
</pre>
<p>You see, just statically import MockSocket class, prepare the mock, execute the test and verify the data. The library just removes the default Java socket implementation and place a mock implementation in its stead. </p>
<p>Of course, this example does not have much sense. It just tests that Java socket implementation works. But imagine that you implement some non-trivial network library. A test library can be handy.</p>
<p>Moreover, there is a HTTP extension which can be used if you want to test some HTTP client. Let's say a JSON REST client. In such case, you can write this.</p>
<pre name="code" class="java">
import static net.javacrumbs.mocksocket.http.HttpMockSocket.*;

...

//prepare mock
expectCall()
  .andWhenRequest(uri(is("/test/something.do")))
     .thenReturn(response().withStatus(404))
  .andWhenRequest(uri(is("/test/other.do")))
    .thenReturn(response().withContent("Text")).thenReturn(response().withContent("Text"));

//do your test
...

//verify
assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
</pre>
<p>Ain't great? You can do much more, please take a look at the <a href="https://github.com/lukas-krecan/mock-socket/">project page</a> if you are interested.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2011/08/27/mock-socket/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converting JSON to XML</title>
		<link>http://blog.krecan.net/2011/07/06/converting-json-to-xml/</link>
		<comments>http://blog.krecan.net/2011/07/06/converting-json-to-xml/#comments</comments>
		<pubDate>Wed, 06 Jul 2011 11:12:48 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=932</guid>
		<description><![CDATA[I have been working on a validation tool that would allow us to validate JSON messages. I could not any usable JSON validator in Java so I have decided to use RelaxNG. It had one catch. RelaxNG is designed for XML validation, not JSON. That's the reason why I have decided to convert JSON to [...]]]></description>
			<content:encoded><![CDATA[<p>I have been working on a validation tool that would allow us to validate JSON messages. I could not any usable JSON validator in Java so I have decided to use <a href="http://relaxng.org/">RelaxNG</a>. It had one catch. RelaxNG is designed for XML validation, not JSON.</p>
<p>That's the reason why I have decided to convert JSON to XML. Before we dive into the implementation, let's think about the problem in general. Both JSON and XML ale tree structures and they are quite similar. In fact, I have discovered only the following differences.</p>
<ol>
<li> JSON supports multiple top-level elements. In XML we can have only one root element. While {"a":1, "b":2} is a valid JSON document, &lt;a&gt;1&lt;/a&gt;&lt;b&gt;2&lt;/b&gt; is not valid XML.</li>
<li>JSON supports arrays, XML does not.</li>
<li>JSON has null keyword, in XML we several options how to deal with nulls. We can either represent it by an empty element or using xsi:nil attribute.</li>
<li>JSON has support for boolean and numeric types. In JSON {"a":1} has different meaning than {"a":"1"} (with double quotes). It's not possible to represent such difference in the XML.</li>
</ol>
<p>All of the problems were acceptable for my needs. There would be more problems when going in the other direction, from XML to JSON, but I did not need it. The only thing I have needed was to convert from </p>
<pre name="code">
{"root":{
	"data1":[
		[1,2,3],
        	[4,5,6]
	],
	"data2":null,
	"data3":"2011-05-30T10:00:00",
	"data4":
	{
		"a":1,
     		"b":2
	}
}
}
</pre>
<p>to </p>
<pre name="code" class="xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;root&gt;
	&lt;data1&gt;
		&lt;data1&gt;
			&lt;data1&gt;1&lt;/data1&gt;
			&lt;data1&gt;2&lt;/data1&gt;
			&lt;data1&gt;3&lt;/data1&gt;
		&lt;/data1&gt;
		&lt;data1&gt;
			&lt;data1&gt;4&lt;/data1&gt;
			&lt;data1&gt;5&lt;/data1&gt;
			&lt;data1&gt;6&lt;/data1&gt;
		&lt;/data1&gt;
	&lt;/data1&gt;
	&lt;data2/&gt;
	&lt;data3&gt;2011-05-30T10:00:00&lt;/data3&gt;
	&lt;data4&gt;
		&lt;a&gt;1&lt;/a&gt;
		&lt;b&gt;2&lt;/b&gt;
	&lt;/data4&gt;
&lt;/root&gt;
</pre>
<p>There already is a project <a href="http://jettison.codehaus.org/">Jettison</a>, that is able to convert between JSON and XML but it does not handle JSON arrays properly. Moreover, I have encountered some bugs like <a href="http://jira.codehaus.org/browse/JETTISON-100">this one</a>. It's trivial to fix but it's there for more than half a year. Strange.</p>
<p>One nice Saturday morning I have decided to implement it. And I have found that it's incredibly easy. It's just matter of using <a href="http://wiki.fasterxml.com/JacksonInFiveMinutes#Streaming_API_Example">Jackson pull parser</a> and generating SAX events based on it. It's about <a href="https://github.com/lukas-krecan/json2xml/blob/master/src/main/java/net/javacrumbs/json2xml/JsonSaxAdapter.java">200 lines of code</a> that you can enjoy here <a href="https://github.com/lukas-krecan/json2xml">here</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2011/07/06/converting-json-to-xml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Jing for Relax NG validation</title>
		<link>http://blog.krecan.net/2011/05/02/using-jing-for-relax-ng-validation/</link>
		<comments>http://blog.krecan.net/2011/05/02/using-jing-for-relax-ng-validation/#comments</comments>
		<pubDate>Mon, 02 May 2011 21:21:51 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[RelaxNG]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=906</guid>
		<description><![CDATA[I just ant to jot down how to programmatically use Jing for Relax NG validation. It has a simple API but I could not find any description besides the JavaDoc. It took me some time to figure out how to use it. If you want to validate a XML file, just use ValidationDriver. If you [...]]]></description>
			<content:encoded><![CDATA[<p>I just ant to jot down how to programmatically use <a href="http://code.google.com/p/jing-trang/">Jing</a>  for <a href="http://relaxng.org/">Relax NG</a> validation. It has a <a href="http://www.thaiopensource.com/relaxng/api/jing/index.html">simple API</a> but I could not find any description besides the JavaDoc. It took me some time to figure out how to use it.</p>
<p>If you want to validate a XML file, just use <a href="http://www.thaiopensource.com/relaxng/api/jing/com/thaiopensource/validate/ValidationDriver.html">ValidationDriver</a>. If you have a DOM Document or StAX source, just do the following</p>
<pre name="code" class="java">
//we are using Relax NG compact format
SchemaReader schemaReader = CompactSchemaReader.getInstance();

//schema can be reused, it's thread safe
Schema schema = schemaReader.createSchema(ValidationDriver.fileInputSource(new File("your_schema.txt)), PropertyMap.EMPTY);

//can use different error handler here (try DraconianErrorHandler http://www.thaiopensource.com/relaxng/api/jing/com/thaiopensource/xml/sax/DraconianErrorHandler.html)
ErrorHandler seh = new ErrorHandlerImpl();
PropertyMapBuilder  builder = new PropertyMapBuilder();
builder.put(ValidateProperty.ERROR_HANDLER, seh);

//Validator is NOT thread safe
Validator validator = schema.createValidator(builder.toPropertyMap());

Source source = ...//your XML source

TransformerFactory.newInstance().newTransformer().transform(source, new SAXResult(validator.getContentHandler()));
</pre>
<p>And that's it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2011/05/02/using-jing-for-relax-ng-validation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Visualizing Fork/Join</title>
		<link>http://blog.krecan.net/2011/03/27/visualizing-forkjoin/</link>
		<comments>http://blog.krecan.net/2011/03/27/visualizing-forkjoin/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 18:20:16 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[gpars]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=892</guid>
		<description><![CDATA[Last Friday I have participated on GPars Hackathon. Together with Jety we have picked the task "Catchy visual demos". Neither of us had used Swing for several years and we are newbies in both Groovy and GPars. But Václav helped us to solve several Groovy mean tricks and at the end we managed to create [...]]]></description>
			<content:encoded><![CDATA[<p>Last Friday I have participated on <a href="http://gpars.codehaus.org/">GPars</a>  <a href="http://gpars.codehaus.org/Hackergarten">Hackathon</a>.  Together with <a href="http://jetensky.net/blog/">Jety</a> we have picked the task "<a href="http://jira.codehaus.org/browse/GPARS-96">Catchy visual demos</a>". Neither of us had used Swing for several years and we are newbies in both Groovy and GPars. But <a href="http://www.jroller.com/vaclav/">Václav</a> helped us to solve several Groovy  mean tricks and at the end we managed to create really nice demo. It's a visualization of Fork/Join based merge-sort. You can enjoy it <a href="http://javacrumbs.net/fj-demo/fj-demo.jnlp">here</a>. You can really see how fork/join aka <a href="http://g.oswego.edu/dl/concurrency-interest/">jsr166y</a> works. Cool.</p>
<p><a href="http://javacrumbs.net/fj-demo/fj-demo.jnlp">THE DEMO</a> (alternatively you can download and execute this <a href="http://javacrumbs.net/fj-demo/fj-demo-1.0-SNAPSHOT-jar-with-dependencies.jar">jar</a>) </p>
<p>The source code can be downloaded <a href="http://git.codehaus.org/gitweb.cgi?p=gpars.git;a=blob;f=src/test/groovy/groovyx/gpars/samples/forkjoin/DemoVisualForkJoinMergeSort.groovy;h=6255691b9b4798133c76f0c155a5401af161bc04;hb=HEAD">here</a> although it's much less enjoyable than the application itself. I have to confess that I enjoyed it so much that I have rewritten it to Java and in fact that's what you are really looking at. In Java it's less elegant, but you do not have to download 5Mb of Groovy libraries. I also hoped that in Java it would run in sandbox without special permissions.  Unfortunately the <a href="http://g.oswego.edu/dl/concurrency-interest/">jsr166</a> library uses <a href="http://www.docjar.com/docs/api/sun/misc/Unsafe.html">sun.misc.Unsafe</a> class which is not only unsafe but also from nonpublic API so it is not possible to run the demo in the sandbox. That's why you have to trust my self-signed certificate. The Java source can be downloaded from <a href="https://github.com/lukas-krecan/fj-demo">GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2011/03/27/visualizing-forkjoin/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>WS testing</title>
		<link>http://blog.krecan.net/2011/03/08/on-ws-testing/</link>
		<comments>http://blog.krecan.net/2011/03/08/on-ws-testing/#comments</comments>
		<pubDate>Tue, 08 Mar 2011 17:32:04 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Tests]]></category>
		<category><![CDATA[WS]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=836</guid>
		<description><![CDATA[This post recaps some results of my experiments with WS testing. In last few months I have been working on several projects – Spring WS Test, Spring WS 2.0 testing support and finally on Smock. All of them reflect different approaches to WS testing. Today I am going recapitulate my findings focusing on testing producer/server [...]]]></description>
			<content:encoded><![CDATA[<p>This post recaps some results of my experiments with WS testing. In last few months I have been working on several projects – <a href="http://javacrumbs.net/spring-ws-test/">Spring WS Test</a>, <a href="http://static.springsource.org/spring-ws/sites/2.0/reference/html/server.html#d0e3303">Spring WS 2.0 testing support</a> and finally on <a href="http://code.google.com/p/smock/">Smock</a>. All of them reflect different approaches to WS testing. Today I am going recapitulate my findings focusing on testing producer/server side code. Consumer/client side will be covered in a following post.</p>
<p><strong>Simple service, simple test</strong></p>
<p>You may wonder what's the problem? Testing web services is easy. We just need to call the endpoint end verify the response. For a simple web service we can write a simple test like this</p>
<pre name="code" class="java">
@Test
public void testPlus()
{
	assertEquals(3, endpoint.plus(1, 2));
}
</pre>
<p>The test is same as if I was testing a normal method. </p>
<p><strong>Web Services tend to be complex</strong></p>
<p>The trouble is that web services tend to be complex. Normal Java methods usually have few relatively simple parameters. On the other hand, web service request or response could be quite complicated which makes the service endpoint hard to test. </p>
<pre name="code" class="java">
GetFlightsRequest request = new GetFlightsRequest();
request.setFrom("PRG");
request.setTo("DUB");
request.setServiceClass(ServiceClass.BUSINESS);
request.setDepartureDate(DatatypeFactory.newInstance().newXMLGregorianCalendarDate(2011, 02, 23, 0));
//more setter calls could be here

GetFlightsResponse response = endpoint.getFlights(request);

List&lt;Flight&gt; flights = response.getFlight();
assertEquals(1, flights.size());
assertEquals(ServiceClass.BUSINESS, flights.get(0).getServiceClass());
//more assertions here
</pre>
<p>Such tests are bearable only until certain level of complexity. From certain level it's real pain. I really hate to call  twenty setters to construct several levels of nested XML hierarchy and then to call dozens of getters to validate the response. </p>
<p><strong>To define XML use ... the XML</strong><br />
The problem is that we want to create or validate an XML structure using wrong language. Java is just not suitable for the task. The best language to describe XML is, surprise, surprise, the XML. Would not it be easier to create XML files containing the request and response and just use them in the test?</p>
<pre name="code" class="java">
GetFlightsRequest request = JAXB.unmarshal(getStream("request1.xml"), GetFlightsRequest.class);

GetFlightsResponse response = endpoint.getFlights(request);

DOMResult domResponse = new DOMResult();
JAXB.marshal(response, domResponse);

XMLUnit.setIgnoreWhitespace(true);
XMLAssert.assertXMLEqual(getDocument("response1.xml"), (Document)domResponse.getNode());
</pre>
<p>It's much better. This test will look exactly the same way regardless the complexity of the service. But it still have some shortcomings. The biggest one is that usually testing using only one request is not sufficient. I'd like to test the service using different inputs. In such case I have to create lot of  XML files that differ just in few elements. It's a maintenance nightmare. If you change the service, you also have to change all the XML files. </p>
<p><strong>Smock comes to help</strong><br />
Up until now we managed to test without any special framework except <code>XMLUnit</code>. Now we will start to use my precious <a href="http://code.google.com/p/smock/">Smock</a> library. The test above can be rewritten to this form.</p>
<pre name="code" class="java">
Map&lt;String, Object&gt; params = new HashMap&lt;String, Object&gt;();
params.put("from", "DUB");
params.put("to", "JFK");
params.put("serviceClass", "economy");
GetFlightsRequest request = createRequest(
					withMessage("request-context-groovy.xml")
					.withParameters(params), GetFlightsRequest.class);

GetFlightsResponse response = endpoint.getFlights(request);

validate(response, request)
	.andExpect(message("response-context-groovy.xml")
	.withParameter("serviceClass", "economy"));
</pre>
<p>The test is quite similar as the previous one. The difference is that it uses statically imported method <code>createRequest</code> to create a request and <code>validate</code> method to validate the response. The main advantage is that Smock methods support templates. So we can set just values we want to, the rest can be driven by the template. Moreover we do not need to deal with the request structure, parameters can be set into a simple flat map.</p>
<pre name="code" class="xml">
&lt;ns1:GetFlightsRequest&gt;
	&lt;ns1:from&gt;${from}&lt;/ns1:from&gt;
	&lt;ns1:to&gt;${to}&lt;/ns1:to&gt;
	&lt;ns1:departureDate&gt;2001-01-01&lt;/ns1:departureDate&gt;
	&lt;ns1:serviceClass&gt;${serviceClass}&lt;/ns1:serviceClass&gt;
&lt;/ns1:GetFlightsRequest&gt;
</pre>
<p>Templates are even more useful when comparing the response</p>
<pre name="code" class="xml">
&lt;ns3:GetFlightsResponse&gt;
	&lt;ns3:flight&gt;
		&lt;ns2:number&gt;OK1324&lt;/ns2:number&gt;
		&lt;ns2:departureTime&gt;2011-02-19T10:00:00&lt;/ns2:departureTime&gt;
		&lt;ns2:from&gt;
			&lt;ns2:code&gt;${GetFlightsRequest.from}&lt;/ns2:code&gt;
			&lt;ns2:name&gt;${IGNORE}&lt;/ns2:name&gt;
			&lt;ns2:city&gt;${IGNORE}&lt;/ns2:city&gt;
		&lt;/ns2:from&gt;
		&lt;ns2:arrivalTime&gt;2011-02-19T12:00:00&lt;/ns2:arrivalTime&gt;
		&lt;ns2:to&gt;
			&lt;ns2:code&gt;${GetFlightsRequest.to}&lt;/ns2:code&gt;
			&lt;ns2:name&gt;${IGNORE}&lt;/ns2:name&gt;
			&lt;ns2:city&gt;${IGNORE}&lt;/ns2:city&gt;
		&lt;/ns2:to&gt;
		&lt;ns2:serviceClass&gt;${serviceClass}&lt;/ns2:serviceClass&gt;
	&lt;/ns3:flight&gt;
&lt;/ns3:GetFlightsResponse&gt;
</pre>
<p>We can ignore some elements, we can compare values based on the request elements and so on. Moreover, when we are using Smock library, we can leverage Spring WS 2.0 testing capabilities that Smock builds on. We can for example validate that the response is valid regarding to its schema.</p>
<pre name="code" class="java">
validate(response).andExpect(validPayload(resource("xsd/messages.xsd")));
</pre>
<p>Cool, isn't it?</p>
<p><strong>Testing the configuration</strong><br />
Sometimes unit test are not sufficient. Sometimes we want to test the configuration, interceptors, error handling and so on. No problem. If you are using Spring WS 2, you can use the built-in testing library. If you need templates or if you are using different framework like Axis 2, you can use Smock. The test looks similar.</p>
<pre name="code" class="java">
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring-ws-servlet.xml")
public class GroovyEndpointTest {

	private MockWebServiceClient wsMockClient;

	@Autowired
	public void setApplicationContext(ApplicationContext context)
	{
		wsMockClient = createClient(context);
	}

	@Test
	public void testResponseTemplate() throws Exception {
		Map&lt;String, Object&gt; params = new HashMap&lt;String, Object&gt;();
		params.put("from", "DUB");
		params.put("to", "JFK");
		params.put("serviceClass", "economy");
		wsMockClient.sendRequest(
			withMessage("request-context-groovy.xml")
			  .withParameters(params))
			.andExpect(message("response-context-groovy.xml")
			  .withParameter("serviceClass", "economy"));
	}
</pre>
<p>The only difference is that we have to bootstrap the application context. Having done this, we can use the mock web service client to call our services. Even though this kind of tests is more complicated, we can use it to test object-XML mapping, endpoint resolution, error handling and configuration in general.</p>
<p>We have seen several different methods of WS testing. Each of them have advantages and disadvantages. If you keep you services simple, your tests are simple too. If the service is more complex, it makes sense to use XML for the test. Either using your own helper methods, <a href="http://static.springsource.org/spring-ws/sites/2.0/reference/html/server.html#d0e3303">Spring WS 2.0 test support</a> or <a href="http://code.google.com/p/smock/">Smock</a>. </p>
<p><em>All the samples could be downloaded from <a href="http://code.google.com/p/smock/wiki/Samples">here</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2011/03/08/on-ws-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where does this class came from?</title>
		<link>http://blog.krecan.net/2010/11/01/where-this-class-came-from/</link>
		<comments>http://blog.krecan.net/2010/11/01/where-this-class-came-from/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 21:18:09 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[classloader]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=770</guid>
		<description><![CDATA[Today I have been debugging some nasty problem on Weblogic. The application worked on one version but did not work on an older one. Apparently some classes were not compatible. But it's quite difficult to debug such problem. You need to find out from which JAR given class was taken from. It's not trivial in [...]]]></description>
			<content:encoded><![CDATA[<p>Today I have been debugging some nasty problem on Weblogic. The application worked on one version but did not work on an older one. Apparently some classes were not compatible. But it's quite difficult to debug such problem. You need to find out from which JAR given class was taken from. It's not trivial in enterprise environment. The class can be part of J2SE, application server and your EAR at the same time. Especially if the class has something to do with XML or web services. End if you have such class, you need some trick to determine which version was actually used.</p>
<p>The trick is simple yet not widely known. In fact I have encountered it in a <a href="http://speaking-my-language.blogspot.com/2009/11/embedded-scala-interpreter.html"> Scala related article</a>. You just call this code from JSP or some other suitable place.</p>
<pre name="code" class="java">
YourClass.class.getProtectionDomain().getCodeSource().getLocation()
</pre>
<p>And that's all, this command will return path to your mystery class JAR.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2010/11/01/where-this-class-came-from/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Kindlology</title>
		<link>http://blog.krecan.net/2010/10/01/kindlology/</link>
		<comments>http://blog.krecan.net/2010/10/01/kindlology/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 10:49:13 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=726</guid>
		<description><![CDATA[Most readers get as far as the Future Semiconditionally Modified Subinverted Plagal Past Subjunctive Intentional before giving up; and in fact in later editions of the book all pages beyond this point have been left blank to save on printing costs. Hitchhiker's Guide to the Galaxy I am new Kindle user and the more I [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>Most readers get as far as the Future Semiconditionally Modified Subinverted Plagal Past Subjunctive Intentional before giving up; and in fact in later editions of the book all pages beyond this point have been left blank to save on printing costs.</p>
<p>Hitchhiker's Guide to the Galaxy
 </p></blockquote>
<p>I am new <a href="http://www.amazon.com/gp/product/B002Y27P3M?ie=UTF8&#038;tag=javac0c-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=B002Y27P3M">Kindle</a><img src="http://www.assoc-amazon.com/e/ir?t=javac0c-20&#038;l=as2&#038;o=1&#038;a=B002Y27P3M" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> user and the more I use it, the more I like it. Although it probably will never have the same feeling as reading a book there are two features that gives it some edge. </p>
<ol>
<li>
It's always with me. Even if I do not have it in my backpack, I do have my Android cell phone with Kindle app installed. And what's best, the application knows where I have stopped reading and I can simply continue.</li>
<li>Highlights and bookmarking are much better. Even if I have pencil when reading a book the highlights are hard to find. I love to quote authorities. But it's always hard to find the right page even though I have underlined it. Kindle solves it quite well. You can highlight whatever you want, you can search the notes and highlights, you can access it on-line and you can even tweet it right from the device. You can even see paragraphs frequently highlighted by other readers! (Although I am thinking about switching this feature off, it's a bit disturbing.)</li>
</ol>
<p>But I do not want to praise Kindle here, I'd like to think about the consequences. There is the other side of the coin. To be able to implement this features, Amazon has to know about every page turn you make. It brings some privacy issues, but I do not want to talk about that neither.</p>
<p>I'd like to imagine how such data could be used for “scientific” purposes. I'd like to know what's my reading speed. Is it lower in the evening? Is it faster when reading thrillers? What's European reading speed? Is it higher than American? Do I skip paragraphs? Do other readers skip the same paragraphs? Is there some part of given book that force people to take a break? Do people make more notes at the beginning of the book? Is there a book that readers usually do not finish? What's the finish rate in general? Are there some books that people just buy but do not even start to read? </p>
<p>You see, there is lot of questions that we can finally find answers for. The only think we need is to persuade Amazon to publish the data and some PhD students to do the statistics. Even without that the data give some interesting result right now. You can see that readers make highlights in fiction books like Eat Pray and Love. I would not expect that. You can see it yourself on <a href="http://kindle.amazon.com?_encoding=UTF8&#038;tag=javac0c-20">http://kindle.amazon.com</a></p>
<p>PS: I am not the first one who had the same idea, here is one of my predecessor's <a href="http://blogs.telegraph.co.uk/technology/shanerichmond/100004861/why-amazon-should-free-its-kindle-data/">articles</a>. </p>
<p><img src="/files/kindle-bookmarks.png" alt="Kindle Bookmarks" /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2010/10/01/kindlology/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Writing fluent API</title>
		<link>http://blog.krecan.net/2010/07/10/writing-fluent-api/</link>
		<comments>http://blog.krecan.net/2010/07/10/writing-fluent-api/#comments</comments>
		<pubDate>Sat, 10 Jul 2010 13:12:19 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[WS]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=603</guid>
		<description><![CDATA[In recent weeks I have been working with Arjen Poutsma on a brand new testing support for Spring Web Services. At least Arjen has been working, I have been just generating crazy ideas and he kept explaining me why we can't use them. But it was quite interesting experience and I have learned a lot [...]]]></description>
			<content:encoded><![CDATA[<p>In recent weeks I have been working with Arjen Poutsma on a brand new testing support for <a href="http://static.springsource.org/spring-ws/sites/1.5/">Spring Web Services</a>. At least Arjen has been working, I have been just generating crazy ideas and he kept explaining me why we can't use them.</p>
<p>But it was quite interesting experience and I have learned a lot about fluent API design. Since it was my first fluent API and I am not an API expert, please take everything I mention here with grain of salt.</p>
<p>The task is simple. We need a way how to configure a mock. This mock has to validate that requests generated by our application are correct and after that the mock has to return some response. We want to write something like this:</p>
<blockquote><p>Computer, when someone is trying to send a request, verify that the request contains value “a”, has header “header” and then respond with value “b”.</p></blockquote>
<p>The requirements for the API are following:</p>
<ul>
<li>It has to be simple for users. Mainly it has to be friendly to GUI addicts like me, that rely on code-completion all the time.</li>
<li>The library itself has to be simple</li>
<li>The API should be as fluent as possible</li>
<li>It has to be extensible</li>
</ul>
<p>In the next part, I will try to describe several variants of the solution, each of them fulfilling the requirements differently. Please keep in mind that the code is simplified, it focuses solely on the API, not on the implementation. Moreover, the classes have been renamed to show what their main purpose is. </p>
<blockquote><p>All characters appearing in this work are fictitious. Any resemblance to real persons, living or dead, is purely coincidental.</p></blockquote>
<h2>Interface based version</h2>
<p><a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/fluentapi/src/main/java/net/javacrumbs/fluentapi1/">code</a><br />
The first variant is based mainly on interfaces. The test itself looks like this</p>
<pre name="code" class="java">
	@Test
	public void testMock()
	{
		Mock mock = new Mock();
		mock.whenConnecting().expectValue("a").and().expectHeader("header").andRespondWithValue("b");

		//test code

		mock.verify();
	}
</pre>
<p>There is one entry point, class Mock</p>
<pre name="code" class="java">
public class Mock {

	public RequestExpectations whenConnecting()
	{
		return new MockInternal();
	}

	public void verify()
	{
		//do something
	}
}
</pre>
<p>It just returns an internal class that implements RequestExpectations interface. </p>
<pre name="code" class="java">
public interface RequestExpectations {

    ResponseActions expectValue(String value);

    ResponseActions expectHeader(String name);
}
</pre>
<p>All methods of this interface return ResponseActions interface </p>
<pre name="code" class="java">
public interface ResponseActions {

	RequestExpectations and();

	void andRespondWithValue(String value);

	void andRespondWithError();

}
</pre>
<p>Please note that and() method allows chaining of request expectation. </p>
<p>This API is really IDE friendly. Code completion works like a charm. It's quite simple both from outside and inside. But this API  has one big flaw. It's not extensible. Imagine that we would like to add an expectation that verifies a digital signature. We would have to add a method to the RequestExpectations interface. It is not possible neither for third parties nor for us, since this change would break backward compatibility. </p>
<h2>Static factory</h2>
<p><a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/fluentapi/src/main/java/net/javacrumbs/fluentapi2/">code</a><br />
We can split the functionality and allow others to provide their own validators and response generators. We just have to change the interfaces</p>
<pre name="code" class="java">
public interface RequestExpectations {

    ResponseActions expect(RequestMatcher matcher);
}
</pre>
<p>and</p>
<pre name="code" class="java">
public interface ResponseActions {

	RequestExpectations and();

	void andRespond(ResponseCallback callback);
}
</pre>
<p>Now we have made the API extensible, but we have to provide an easy way how to create RequestMatchers and ResponseCallbacks. One way how to do it is a statically imported static factory. </p>
<pre name="code" class="java">
public class StaticFactory {
	public static RequestMatcher value(String value)
	{
		return new RequestMatcher() {
			public void match(Object someParams) {
				//do something
			}
		};
	}
	public static ResponseCallback withValue(String value)
	{
		return new ResponseCallback() {
			public void doWithResponse(Object someParams) {
				//do something
			}
		};
	}
}
</pre>
<p>The test then can look like this.</p>
<pre name="code" class="java">
import static net.javacrumbs.fluentapi2.StaticFactory.*;

public class MockTest {

	@Test
	public void testMock()
	{
		Mock mock = new Mock();
		mock.whenConnecting().expect(value("a")).and().expect(header("header")).andRespond(withValue("b"));

		//test code

		mock.verify();
	}
}
</pre>
<p>Such API is also fluent. It even resembles <a href="http://easymock.org/">EasyMock</a> API. The issue here is that code completion does not work as well as before. In Eclipse you have to type first letter of the method name before Ctrl+Space starts working. In Idea you have to press Ctrl+Shift+Space. But the advantage is that everyone can provide their own factory and extend  the library seamlessly and consistently.</p>
<h2>Super-static variant</h2>
<p><a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/fluentapi/src/main/java/net/javacrumbs/fluentapi3/">code</a><br />
We can go event further. We can get rid of RequestExpectations interface, remove Mock class and do statically most of the stuff. The test can look like this</p>
<pre name="code" class="java">
import static net.javacrumbs.fluentapi3.StaticFactory.*;

public class MockTest {

	@Test
	public void testMock()
	{
		expect(value("a")).andExpect(header("header")).andRespond(withValue("b"));

		//test code

		verify();
	}
}
</pre>
<p>It's simple and elegant. We even got rid of the strange and() method. The downside is that we usually have to use some ThreadLocals internally. But it looks almost like EasyMock. Cool.</p>
<h2>Inheritance</h2>
<p><a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/fluentapi/src/main/java/net/javacrumbs/fluentapi4/">code</a><br />
Some people (like me) do not like static methods. It does not feel right, it's not object oriented programming. Can we do something similar, but dynamic? Yes, we can.</p>
<p>We just have to use inheritance. Just delete static keywords from the methods in StaticFactory class. We will also  rename the class itself because it's not static any more.</p>
<p>We get</p>
<pre name="code" class="java">
public class MockTest extends MockFactory{

	@Test
	public void testMock()
	{
		expect(value("a")).andExpect(header("header")).andRespond(withValue("b"));

		//test code

		verify();
	}
}
</pre>
<p>The downside is, that we have to extend our class from MockFactory. Sometimes it's not possible. No problem, we can use a trick I have seen in <a href="http://camel.apache.org/routes.html">Apache Camel DSL</a>.</p>
<pre name="code" class="java">
public class MockTest{
	@Test
	public void testMock()
	{
		MockFactory mockFactory = new MockFactory()
		{
			protected void configure() {
				expect(value("a")).andExpect(header("header")).andRespond(withValue("b"));
			};
		};

		//test code

		mockFactory.verify();
	}
}
</pre>
<p>It's not as elegant as the direct inheritance, but it works. If we are brave enough, we can even use a closure.</p>
<pre name="code" class="java">
public class MockTest extends MockFactory{
	@Test
	public void testMockClosure()
	{
		MockFactory mockFactory = new MockFactory()
		{{
				expect(value("a")).andExpect(header("header")).andRespond(withValue("b"));
		}};

		//test code

		mockFactory.verify();
	}
}
</pre>
<p>(I bet you did not know that Java has closures already). </p>
<p>So I have shown you four variants, which one is the best? I do not know, each of them has it's pros and cons. I personally like the last one the most. But the super static variant is not bad neither. Or the static? Or some mix between them? Some other? You have to make your own opinion.</p>
<p>References:<br />
<a href="http://martinfowler.com/bliki/FluentInterface.html">http://martinfowler.com/bliki/FluentInterface.html</a><br />
<a href="http://martinfowler.com/dslwip/InternalOverview.html">http://martinfowler.com/dslwip/InternalOverview.html</a><br />
<a href="http://camel.apache.org/routes.html">http://camel.apache.org/routes.html</a><br />
<a href="http://easymock.org/">http://easymock.org/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2010/07/10/writing-fluent-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring WS Security on both client and server</title>
		<link>http://blog.krecan.net/2010/06/07/spring-ws-security-on-both-client-and-server/</link>
		<comments>http://blog.krecan.net/2010/06/07/spring-ws-security-on-both-client-and-server/#comments</comments>
		<pubDate>Mon, 07 Jun 2010 11:17:13 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[WS]]></category>
		<category><![CDATA[client]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[spring-ws]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=578</guid>
		<description><![CDATA[Recently, I have been playing with Spring WS with WS-Security. I just want to write down how it works. Do not except anything special, just simple example of basic security operations. The example We want to implement both client and server side. The client will sign the message, encrypt some part of it and add [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I have been playing with Spring WS with WS-Security. I just want to write down how it works. Do not except anything special, just simple example of basic security operations.</p>
<h2>The example</h2>
<p>We want to implement both client and server side. The client will sign the message, encrypt some part of it and add a timestamp. To make it more complex and real-life like we will sign the message using private key with alias “client” and encrypt the message using public key called “server”. Server will validate that the request is valid and will just sign the response using his key called “server”. Please note that I have picked <a href="http://ws.apache.org/wss4j/">Wss4j</a> implementation because the configuration seemed to be easier than Xws.</p>
<h2>Client</h2>
<p>It's easy to do configure client interceptor like this (<a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/simple-server-test/branches/simple-server-test-security/simple-server-test/src/main/resources/spring/client/secured-client-config.xml">full configuration</a>).</p>
<pre name="code" class="xml">
&lt;bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate"&gt;
	&lt;property name="interceptors"&gt;
		&lt;list&gt;
			&lt;ref local="wsClientSecurityInterceptor"/&gt;
		&lt;/list&gt;
	&lt;/property&gt;
	...
&lt;/bean&gt;

&lt;bean id="wsClientSecurityInterceptor"
	class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor"&gt;
	&lt;property name="securementActions" value="Timestamp Signature Encrypt" /&gt;
	&lt;!-- Key alias for signature --&gt;
	&lt;property name="securementUsername" value="client" /&gt;
	&lt;property name="securementPassword" value="" /&gt;
	&lt;property name="securementSignatureCrypto" ref="clientCrypto"/&gt;
	&lt;property name="securementEncryptionCrypto" ref="clientCrypto"/&gt;
	&lt;property name="securementEncryptionParts" value="{Content}{http://javacrumbs.net/calc}a"/&gt;
	&lt;!-- Key alias for encryption --&gt;
	&lt;property name="securementEncryptionUser" value="server"/&gt;

	&lt;!-- Validation config --&gt;
	&lt;property name="validationActions" value="Signature" /&gt;
	&lt;property name="validationSignatureCrypto" ref="clientCrypto"/&gt;
&lt;/bean&gt;

&lt;bean id="clientCrypto" class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean"&gt;
    &lt;property name="keyStorePassword" value="mypasswd"/&gt;
    &lt;property name="keyStoreLocation" value="classpath:security/client-keystore.jks"/&gt;
&lt;/bean&gt;
</pre>
<p>As you can see, there is nothing special. We just define which actions to take and properties. The only confusing part is, that key alias is defined as “securementUsername”.</p>
<p>Whit this configuration we will get following SOAP message.</p>
<pre name="code" class="xml">
&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
	xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"&gt;
	&lt;SOAP-ENV:Header&gt;
		&lt;wsse:Security
			xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
			SOAP-ENV:mustUnderstand="1"&gt;
			&lt;xenc:EncryptedKey Id="EncKeyId-F5114C147B958E706212759086159355"
				xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"&gt;
				&lt;xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" /&gt;
				&lt;ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"&gt;
					&lt;wsse:SecurityTokenReference
						xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"&gt;
						&lt;ds:X509Data&gt;
							&lt;ds:X509IssuerSerial&gt;
								&lt;ds:X509IssuerName&gt;CN=Test Server,OU=Test&lt;/ds:X509IssuerName&gt;
								&lt;ds:X509SerialNumber&gt;1275904530&lt;/ds:X509SerialNumber&gt;
							&lt;/ds:X509IssuerSerial&gt;
						&lt;/ds:X509Data&gt;
					&lt;/wsse:SecurityTokenReference&gt;
				&lt;/ds:KeyInfo&gt;
				&lt;xenc:CipherData&gt;
					&lt;xenc:CipherValue&gt;fwFM7ShJ1xd7dTGrkh0410sTmW92OPB1q1fpzB21XFIe36siDDJWGgbw5B94yjmGK2YaPOWLb7cpVTYPzc9VUDs7Jc42CtrhT2H6eZ7CDiA60Ugz+qi2UyyfMDK6Vrdj9J68rij5P12AiBeTnd2wlhI29+71XbUpD5weHDHjMtQ=
					&lt;/xenc:CipherValue&gt;
				&lt;/xenc:CipherData&gt;
				&lt;xenc:ReferenceList&gt;
					&lt;xenc:DataReference URI="#EncDataId-4" /&gt;
				&lt;/xenc:ReferenceList&gt;
			&lt;/xenc:EncryptedKey&gt;
			&lt;ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
				Id="Signature-2"&gt;
				&lt;ds:SignedInfo&gt;
					&lt;ds:CanonicalizationMethod
						Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /&gt;
					&lt;ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /&gt;
					&lt;ds:Reference URI="#id-3"&gt;
						&lt;ds:Transforms&gt;
							&lt;ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /&gt;
						&lt;/ds:Transforms&gt;
						&lt;ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /&gt;
						&lt;ds:DigestValue&gt;AU9utUgz5RylYCRDUAO0JWM48kM=&lt;/ds:DigestValue&gt;
					&lt;/ds:Reference&gt;
				&lt;/ds:SignedInfo&gt;
				&lt;ds:SignatureValue&gt;
					NHjjgpb9/alUOq50CqPKLcdYrp7edYdKJDNvIhh+2OAhYdDvZmD1qGsVKd1H9oKPF17uaF2Sv3aY
					0le6BrvzVx3n2+nYYlHwAWlzBk7wsBt4vLll6q6juLCP+siupTIb1PeZDf3WrAbHUQh5oqjD6cZB
					Sc89pDspWRABQ8wPxYE=
&lt;/ds:SignatureValue&gt;
				&lt;ds:KeyInfo Id="KeyId-F5114C147B958E706212759086157652"&gt;
					&lt;wsse:SecurityTokenReference
						xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
						wsu:Id="STRId-F5114C147B958E706212759086157673"
						xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"&gt;
						&lt;ds:X509Data&gt;
							&lt;ds:X509IssuerSerial&gt;
								&lt;ds:X509IssuerName&gt;CN=Lukas Krecan,OU=Test&lt;/ds:X509IssuerName&gt;
								&lt;ds:X509SerialNumber&gt;1275900789&lt;/ds:X509SerialNumber&gt;
							&lt;/ds:X509IssuerSerial&gt;
						&lt;/ds:X509Data&gt;
					&lt;/wsse:SecurityTokenReference&gt;
				&lt;/ds:KeyInfo&gt;
			&lt;/ds:Signature&gt;
			&lt;wsu:Timestamp
				xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
				wsu:Id="Timestamp-1"&gt;
				&lt;wsu:Created&gt;2010-06-07T11:03:35.749Z&lt;/wsu:Created&gt;
				&lt;wsu:Expires&gt;2010-06-07T11:08:35.749Z&lt;/wsu:Expires&gt;
			&lt;/wsu:Timestamp&gt;
		&lt;/wsse:Security&gt;
	&lt;/SOAP-ENV:Header&gt;
	&lt;SOAP-ENV:Body
		xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
		wsu:Id="id-3"&gt;
		&lt;ns2:plusRequest xmlns:ns2="http://javacrumbs.net/calc"&gt;
			&lt;ns2:a&gt;
				&lt;xenc:EncryptedData Id="EncDataId-4"
					Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"&gt;
					&lt;xenc:EncryptionMethod
						Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc" /&gt;
					&lt;ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"&gt;
						&lt;wsse:SecurityTokenReference
							xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"&gt;
							&lt;wsse:Reference URI="#EncKeyId-F5114C147B958E706212759086159355"
								xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" /&gt;
						&lt;/wsse:SecurityTokenReference&gt;
					&lt;/ds:KeyInfo&gt;
					&lt;xenc:CipherData&gt;
						&lt;xenc:CipherValue&gt;81TEtUhHXo6iZeAmYrtYlm2ObAqOBpjfzf2VOVUg4Hs=
						&lt;/xenc:CipherValue&gt;
					&lt;/xenc:CipherData&gt;
				&lt;/xenc:EncryptedData&gt;
			&lt;/ns2:a&gt;
			&lt;ns2:b&gt;2&lt;/ns2:b&gt;
		&lt;/ns2:plusRequest&gt;
	&lt;/SOAP-ENV:Body&gt;
&lt;/SOAP-ENV:Envelope&gt;
</pre>
<h2>Server config</h2>
<p>To configure server, you have to define Spring WS server interceptor like this (<a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/simple-server-test/branches/simple-server-test-security/simple-server-test/src/main/webapp/WEB-INF/secured-spring-ws-servlet.xml">full example</a>).</p>
<pre name="code" class="xml">
&lt;bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"&gt;
	&lt;property name="interceptors"&gt;
		&lt;list&gt;
			&lt;ref local="wsServerSecurityInterceptor" /&gt;
		&lt;/list&gt;
	&lt;/property&gt;
&lt;/bean&gt;

&lt;bean id="wsServerSecurityInterceptor"	class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor"&gt;
	&lt;!-- Validation part --&gt;
	&lt;property name="validationActions" value="Timestamp Signature Encrypt"/&gt;
	&lt;property name="validationSignatureCrypto" ref="serverCrypto"/&gt;
	&lt;property name="validationDecryptionCrypto" ref="serverCrypto"/&gt;
	&lt;property name="validationCallbackHandler"&gt;
		&lt;bean class="org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler"&gt;
			&lt;property name="keyStore"&gt;
				&lt;bean class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean"&gt;
				    &lt;property name="password" value="mypasswd"/&gt;
				&lt;/bean&gt;
			&lt;/property&gt;
			&lt;property name="privateKeyPassword" value=""/&gt;
		&lt;/bean&gt;
	&lt;/property&gt;
	&lt;!-- Sign the response --&gt;
	&lt;property name="securementActions" value="Signature" /&gt;
	&lt;property name="securementUsername" value="server" /&gt;
	&lt;property name="securementPassword" value="" /&gt;
	&lt;property name="securementSignatureCrypto" ref="serverCrypto"/&gt;
&lt;/bean&gt;

&lt;bean id="serverCrypto" class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean"&gt;
    &lt;property name="keyStorePassword" value="mypasswd"/&gt;
    &lt;property name="keyStoreLocation" value="classpath:security/server-keystore.jks"/&gt;
&lt;/bean&gt;
</pre>
<p>No surprise here neither.  The response will look like this.</p>
<pre name="code" class="xml">
&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&gt;
	&lt;SOAP-ENV:Header&gt;
		&lt;wsse:Security
			xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
			SOAP-ENV:mustUnderstand="1"&gt;
			&lt;ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
				Id="Signature-6"&gt;
				&lt;ds:SignedInfo&gt;
					&lt;ds:CanonicalizationMethod
						Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /&gt;
					&lt;ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /&gt;
					&lt;ds:Reference URI="#id-7"&gt;
						&lt;ds:Transforms&gt;
							&lt;ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /&gt;
						&lt;/ds:Transforms&gt;
						&lt;ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /&gt;
						&lt;ds:DigestValue&gt;hEdDfxM6Nfs62Jxe8EOsELCDtUk=&lt;/ds:DigestValue&gt;
					&lt;/ds:Reference&gt;
					&lt;ds:Reference URI="#SigConf-5"&gt;
						&lt;ds:Transforms&gt;
							&lt;ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /&gt;
						&lt;/ds:Transforms&gt;
						&lt;ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /&gt;
						&lt;ds:DigestValue&gt;TTSRri5KJqXeMJfjzXyVmUewPxc=&lt;/ds:DigestValue&gt;
					&lt;/ds:Reference&gt;
				&lt;/ds:SignedInfo&gt;
				&lt;ds:SignatureValue&gt;
					V5by3bOoGQNajfs7i9xQ+cbAqIkI0NS9N9FQlLb/dAuQfguE7jKRP9iypOeRLHCPr7g3BNg+NCrX
					6YcgDQ0TfXNhdL00AmoEfDmWSNvIVNE49kZEn3Ji/RW4VtdEiV79VD7Vuay0YAYGo9DSQvzq3FP6
					YEhfzfMqvfbWMdEKcO8=
&lt;/ds:SignatureValue&gt;
				&lt;ds:KeyInfo Id="KeyId-F5114C147B958E706212759086160837"&gt;
					&lt;wsse:SecurityTokenReference
						xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
						wsu:Id="STRId-F5114C147B958E706212759086160838"
						xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"&gt;
						&lt;ds:X509Data&gt;
							&lt;ds:X509IssuerSerial&gt;
								&lt;ds:X509IssuerName&gt;CN=Test Server,OU=Test&lt;/ds:X509IssuerName&gt;
								&lt;ds:X509SerialNumber&gt;1275904530&lt;/ds:X509SerialNumber&gt;
							&lt;/ds:X509IssuerSerial&gt;
						&lt;/ds:X509Data&gt;
					&lt;/wsse:SecurityTokenReference&gt;
				&lt;/ds:KeyInfo&gt;
			&lt;/ds:Signature&gt;
			&lt;wsse11:SignatureConfirmation
				xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"
				xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
				Value="NHjjgpb9/alUOq50CqPKLcdYrp7edYdKJDNvIhh+2OAhYdDvZmD1qGsVKd1H9oKPF17uaF2Sv3aY0le6BrvzVx3n2+nYYlHwAWlzBk7wsBt4vLll6q6juLCP+siupTIb1PeZDf3WrAbHUQh5oqjD6cZBSc89pDspWRABQ8wPxYE="
				wsu:Id="SigConf-5" /&gt;
		&lt;/wsse:Security&gt;
	&lt;/SOAP-ENV:Header&gt;
	&lt;SOAP-ENV:Body
		xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
		wsu:Id="id-7"&gt;
		&lt;ns2:plusResponse xmlns:ns2="http://javacrumbs.net/calc"&gt;
			&lt;ns2:result&gt;3&lt;/ns2:result&gt;
		&lt;/ns2:plusResponse&gt;
	&lt;/SOAP-ENV:Body&gt;
&lt;/SOAP-ENV:Envelope&gt;
</pre>
<p>As we have seen it's possible to configure WS-Security without much hassle. To learn more, visit the official <a href="http://static.springsource.org/spring-ws/sites/1.5/reference/html/security.html">Spring WS reference</a>. You can download full example <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/simple-server-test/branches/simple-server-test-security/simple-server-test/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2010/06/07/spring-ws-security-on-both-client-and-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

