<?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; WS</title>
	<atom:link href="http://blog.krecan.net/category/ws/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>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>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>
		<item>
		<title>Generovaný kód je zlo. A to i ve webových službách.</title>
		<link>http://blog.krecan.net/2010/02/21/generovany-kod-je-zlo-a-to-i-ve-webovych-sluzbach/</link>
		<comments>http://blog.krecan.net/2010/02/21/generovany-kod-je-zlo-a-to-i-ve-webovych-sluzbach/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 10:15:40 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[WS]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=511</guid>
		<description><![CDATA[Minulý týden jsem zase trochu programoval, psal jsem jednu webovou službu. Ta měla WSDL definované třetí stranou, takže to byla poměrně jednoduchá a rutinní záležitost. Vzal jsem XML schema, z něj vygeneroval XmlBeans a začal jsem implementovat. Narazil jsem ale na jeden problém, který se mi nedařilo vyřešit. Měl jsem vyrobit čtyři webové služby, jejichž [...]]]></description>
			<content:encoded><![CDATA[<p>Minulý týden jsem zase trochu programoval, psal jsem jednu webovou službu. Ta měla WSDL definované třetí stranou, takže to byla poměrně jednoduchá a rutinní záležitost. Vzal jsem XML schema, z něj vygeneroval <a href="http://xmlbeans.apache.org/">XmlBeans</a> a začal jsem implementovat. Narazil jsem ale na jeden problém, který se mi nedařilo vyřešit.</p>
<p>Měl jsem vyrobit čtyři webové služby, jejichž odpovědi se lišily jen v pár detailech. V zásadě vypadaly takto:</p>
<pre name="code" class="xml">
&lt;XXXResponse&gt;
        &lt;Version&gt;1&lt;/m:Version&gt;
        &lt;RequestId&gt;XYZ123&lt;/RequestId&gt;
        &lt;Result&gt;SUCESS&lt;/Result&gt;
        &lt;XXXTransactionId&gt;ABC456&lt;/XXXTransactionId&gt;
&lt;/XXXResponse&gt;
</pre>
<p>Místo XXX si představte různé fáze transakce. Můj problém spočíval v tom, že jsem nechtěl mít v programu čtyřikrát ten samý kus kódu pro generování odpovědi, chtěl jsem ho tam mít jen jednou. Jenže se to nedařilo, zkoušel jsem všelijaké finty s dědičností, vymýšlel jsem sofistikované wrappery, ale pořád jsem měl čtyři docela ošklivé bloky, které si byly ohromě podobné. Jediný rozdíl byl v jménu odpovědi a jménu transactionId. Ale tyto drobné rozdíly mi bránily v tom, udělat znovupoužitelný kód pro všechny webové služby.</p>
<p>Až mě napadla jednoduchá věc. Vždy jsem tvrdil, že generování kódu je zlo, kterému je potřeba se za každou cenu vyhnout. Ale u webových služeb jsem to tak nějak bral za dané. Znáte to, <a href="http://static.springsource.org/spring-ws/sites/1.5/reference/html/why-contract-first.html">contract first</a> přeci spočívá v tom, že začnu s návrhem XSD a podle něj píši kód. Je jen přirozené si ten kód pak nechat vygenerovat. A to je právě ta chyba. XML a Java jsou různé světy. Ano jsou si docela podobné, ale každý má jiný účel, jiné zvyklosti a jiné potřeby. Problém je, že, generovaný kód vždy odráží svůj původ.</p>
<p>Když generuji kód na základě XML, dostanu <a href="http://pichlik.sweb.cz/archive/2009_10_04_archive.html#3099964125087268552">anemický model</a> se kterým se mi pak špatně pracuje. Často pak skončím u toho, že mapuji vygenerované třídy na nějaké svoje vymazlené třídy a pak zase zpátky.  </p>
<p>Když na druhou stranu generuji XSD na základě Javy, riskuji, že se s výsledným XML bude mým klientům špatně pracovat, že bude špatně rozšířitelné a podobně.</p>
<p>Je to podobný problém jako u objektově relačního mapování. Objekty a tabulky jsou si hrozně podobné, ale přesto je mezi nimi obrovská propast. Pamatuji si doby, kdy jsem generoval Javovské třídy na základě tabulek. Výsledek byl vždy žalostný. V poslední době jednoduše namapuji ručně psanou Javu na ručně optimalizovanou databázi a obě strany jsou spokojené.</p>
<p>Proč něco podobného nejde u XML? Pokud jste byli na mém <a href="http://www.java.cz/article/czjug-leden-lightning-talks">lightning talku</a>, možná si vzpomenete jak jsem si stěžoval, že v roce 2010 musím ručně mapovat XML třídy na normální třídy a zpátky. Mýlil jsem se, nemusím. Mohu udělat to samé jako s databází. Díky <a href="https://jaxb.dev.java.net/tutorial/section_6_2_1-A-Survey-Of-JAXB-Annotations.html">JAXB 2</a> mohu jednoduše namapovat svoje třídy na XML. Samozřejmě, v první iteraci si mohu pro jednoduchost ty třídy vygenerovat, ale pak už je ručně upravím a nikdy je negeneruji znovu.  </p>
<p>A přesně tak jsem vyřešil svůj problém s duplicitou kódu. Ručně jsem si upravil JAXB třídy. Nejdřív jsem si vyrobil abstraktního předka všech odpovědí. To by ještě šlo zařídit úpravou XML schematu. Ale pak jsem do toho abstraktního předka přidal abstraktní metodu setTransactionId a dokonce jsem ho nechal implementovat nějaké rozhraní. To jsou koncepty, které v XML vůbec nemají smysl! Tím pádem ani nemá smysl pomýšlet na jejich generování. </p>
<p>Tím, že jsem udělal JAXB třídy nezávislé na XSD, jsem si zajistil, že je nemusím kopírovat do jiných interních tříd. Mohu svůj business kód udělat závislý jen na rozhraních, které XML třídy implementují. Konkrétně u mě to ušetřilo desítky řádků ošklivého kódu.</p>
<p>Kdybych měl dost odvahy, mohly bych dokonce i k těmto třídám přidat JPA anotace a ukládat je bez obav do databáze. Ale tak silný žaludek zatím ještě nemám.</p>
<p>Samozřejmě i tento přístup má své nevýhody. Asi největší je, že se mi může Java odchýlit od XML schematu. Může se mi stát, že udělám chybu, a začnu generovat nevalidní XML. Od toho ale máme testování, můžete použít třeba moji <a href="http://javacrumbs.net/spring-ws-test/">úžasnou knihovnu</a>, která vám to pohlídá.</p>
<p>Zkuste se nad tím zamyslet. Generovaný kód nefungoval nikdy, vždy s ním byly jen problémy. Ale u webových služeb jsem ho alespoň já bral jako hotovou věc. Když se ho ale zbavíme, ušetříme si spoustu starostí. Náš kód může vypadat o něco víc objektově a my si užijeme mnohem víc legrace s programováním užitečných věcí.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2010/02/21/generovany-kod-je-zlo-a-to-i-ve-webovych-sluzbach/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>

