Spring Ws Reference
Spring Ws Reference
Preface ................................................................................................................................... iv
I. Introduction .......................................................................................................................... 1
1. What is Spring Web Services? ...................................................................................... 2
1.1. Introduction ....................................................................................................... 2
1.2. Runtime environment ........................................................................................ 2
2. Why Contract First? ..................................................................................................... 4
2.1. Introduction ....................................................................................................... 4
2.2. Object/XML Impedance Mismatch ..................................................................... 4
2.2.1. XSD extensions ...................................................................................... 4
2.2.2. Unportable types ..................................................................................... 4
2.2.3. Cyclic graphs ......................................................................................... 5
2.3. Contract-first versus Contract-last ....................................................................... 6
2.3.1. Fragility ................................................................................................. 6
2.3.2. Performance ........................................................................................... 7
2.3.3. Reusability ............................................................................................. 7
2.3.4. Versioning .............................................................................................. 7
3. Writing Contract-First Web Services ............................................................................. 8
3.1. Introduction ....................................................................................................... 8
3.2. Messages .......................................................................................................... 8
3.2.1. Holiday .................................................................................................. 8
3.2.2. Employee ............................................................................................... 8
3.2.3. HolidayRequest ...................................................................................... 9
3.3. Data Contract .................................................................................................... 9
3.4. Service contract ............................................................................................... 11
3.5. Creating the project ......................................................................................... 13
3.6. Implementing the Endpoint .............................................................................. 14
3.6.1. Handling the XML Message .................................................................. 14
3.6.2. Routing the Message to the Endpoint ..................................................... 16
3.7. Publishing the WSDL ...................................................................................... 17
II. Reference .......................................................................................................................... 19
4. Shared components ..................................................................................................... 20
4.1. Web service messages ..................................................................................... 20
4.1.1. WebServiceMessage .............................................................................. 20
4.1.2. SoapMessage ......................................................................................... 20
4.1.3. Message Factories ................................................................................. 20
4.1.4. MessageContext .................................................................................... 22
4.2. TransportContext ........................................................................................... 22
4.3. Handling XML With XPath ............................................................................. 23
4.3.1. XPathExpression .................................................................................. 23
4.3.2. XPathTemplate ..................................................................................... 24
4.4. Message Logging and Tracing .......................................................................... 25
5. Creating a Web service with Spring-WS ...................................................................... 26
5.1. Introduction ..................................................................................................... 26
5.2. The MessageDispatcher .................................................................................. 26
5.3. Transports ....................................................................................................... 27
5.3.1. MessageDispatcherServlet .................................................................. 27
5.3.2. Wiring up Spring-WS in a DispatcherServlet ....................................... 30
5.3.3. JMS transport ....................................................................................... 31
5.3.4. Email transport ..................................................................................... 31
ii
32
33
34
36
40
41
42
45
45
46
46
46
49
49
51
51
51
51
54
55
55
56
56
57
59
60
62
62
62
63
65
70
72
73
74
74
75
75
78
78
80
82
83
84
iii
Preface
In the current age of Service Oriented Architectures, more and more people are using Web Services
to connect previously unconnected systems. Initially, Web services were considered to be just another
way to do a Remote Procedure Call (RPC). Over time however, people found out that there is a big
difference between RPCs and Web services. Especially when interoperability with other platforms is
important, it is often better to send encapsulated XML documents, containing all the data necessary
to process the request. Conceptually, XML-based Web services are better off being compared to
message queues rather than remoting solutions. Overall, XML should be considered the platformneutral representation of data, the interlingua of SOA. When developing or using Web services, the
focus should be on this XML, and not on Java.
Spring Web Services focuses on creating these document-driven Web services. Spring Web Services
facilitates contract-first SOAP service development, allowing for the creation of flexible web services
using one of the many ways to manipulate XML payloads. Spring-WS provides a powerful message
dispatching framework, a WS-Security solution that integrates with your existing application security
solution, and a Client-side API that follows the familiar Spring template pattern.
This document provides a reference guide to Spring-WS's features. Since this document is still a workin-progress, if you have any requests or comments, please post them on the support forums at http://
forum.springframework.org/forumdisplay.php?f=39.
iv
Part I. Introduction
This first part of the reference documentation is an overview of Spring Web Services and the underlying concepts.
Spring-WS is then introduced, and the concepts behind contract-first Web service development are explained.
<simpleType name="AirportCode">
<restriction base="string">
<pattern value="[A-Z][A-Z][A-Z]"/>
</restriction>
</simpleType>
This type restricts a XSD string by ways of a regular expression, allowing only three upper case letters.
If this type is converted to Java, we will end up with an ordinary java.lang.String; the regular
expression is lost in the conversion process, because Java does not allow for these sorts of extensions.
Most of the contents in this section was inspired by [alpine] and [effective-enterprise-java].
Undoubtedly, the contents of this map can be converted into some sort of XML, but since there is
no standard way to describe a map in XML, it will be proprietary. Also, even if it can be converted
to XML, many platforms do not have a data structure similar to the TreeMap. So when a .NET client
accesses your Web service, it will probably end up with a System.Collections.Hashtable, which
has different semantics.
This problem is also present when working on the client side. Consider the following XSD snippet,
which describes a service contract:
<element name="GetFlightsRequest">
<complexType>
<all>
<element name="departureDate" type="date"/>
<element name="from" type="string"/>
<element name="to" type="string"/>
</all>
</complexType>
</element>
This contract defines a request that takes an date, which is a XSD datatype representing a year,
month, and day. If we call this service from Java, we will probably use either a java.util.Date
or java.util.Calendar. However, both of these classes actually describe times, rather than dates.
So, we will actually end up sending data that represents the fourth of April 2007 at midnight
(2007-04-04T00:00:00), which is not the same as 2007-04-04.
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
...
which will take a pretty long time to finish, because there is no stop condition for this loop.
One way to solve this problem is to use references to objects that were already marshalled, like so:
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight href="KL1117" />
</passenger>
...
</passengers>
</flight>
This solves the recursiveness problem, but introduces new ones. For one, you cannot use an XML
validator to validate this structure. Another issue is that the standard way to use these references in
SOAP (RPC/encoded) has been deprecated in favor of document/literal (see WS-I Basic Profile [http://
www.ws-i.org/Profiles/BasicProfile-1.1.html#SOAP_encodingStyle_Attribute]).
These are just a few of the problems when dealing with O/X mapping. It is important to respect these
issues when writing Web services. The best way to respect them is to focus on the XML completely,
while using Java as an implementation language. This is what contract-first is all about.
2.3.1. Fragility
As mentioned earlier, the contract-last development style results in your web service contract (WSDL
and your XSD) being generated from your Java contract (usually an interface). If you are using this
approach, you will have no guarantee that the contract stays constant over time. Each time you change
your Java contract and redeploy it, there might be subsequent changes to the web service contract.
Aditionally, not all SOAP stacks generate the same web service contract from a Java contract. This
means changing your current SOAP stack for a different one (for whatever reason), might also change
your web service contract.
2.3.2. Performance
When Java is automatically transformed into XML, there is no way to be sure as to what is sent across
the wire. An object might reference another object, which refers to another, etc. In the end, half of
the objects on the heap in your virtual machine might be converted into XML, which will result in
slow response times.
When using contract-first, you explicitly describe what XML is sent where, thus making sure that it
is exactly what you want.
2.3.3. Reusability
Defining your schema in a separate file allows you to reuse that file in different scenarios. If you define
an AirportCode in a file called airline.xsd, like so:
<simpleType name="AirportCode">
<restriction base="string">
<pattern value="[A-Z][A-Z][A-Z]"/>
</restriction>
</simpleType>
You can reuse this definition in other schemas, or even WSDL files, using an import statement.
2.3.4. Versioning
Even though a contract must remain constant for as long as possible, they do need to be changed
sometimes. In Java, this typically results in a new Java interface, such as AirlineService2, and a
(new) implementation of that interface. Of course, the old service must be kept around, because there
might be clients who have not migrated yet.
If using contract-first, we can have a looser coupling between contract and implementation. Such
a looser coupling allows us to implement both versions of the contract in one class. We could, for
instance, use an XSLT stylesheet to convert any "old-style" messages to the "new-style" messages.
3.2. Messages
In this section, we will focus on the actual XML messages that are sent to and from the Web service.
We will start out by determining what these messages look like.
3.2.1. Holiday
In the scenario, we have to deal with holiday requests, so it makes sense to determine what a holiday
looks like in XML:
<Holiday xmlns="http://mycompany.com/hr/schemas">
<StartDate>2006-07-03</StartDate>
<EndDate>2006-07-07</EndDate>
</Holiday>
A holiday consists of a start date and an end date. We have also decided to use the standard ISO 8601
[http://www.cl.cam.ac.uk/~mgk25/iso-time.html] date format for the dates, because that will save a
lot of parsing hassle. We have also added a namespace to the element, to make sure our elements can
used within other XML documents.
3.2.2. Employee
There is also the notion of an employee in the scenario. Here is what it looks like in XML:
<Employee xmlns="http://mycompany.com/hr/schemas">
<Number>42</Number>
<FirstName>Arjen</FirstName>
<LastName>Poutsma</LastName>
</Employee>
3.2.3. HolidayRequest
Both the holiday and employee element can be put in a <HolidayRequest/>:
<HolidayRequest xmlns="http://mycompany.com/hr/schemas">
<Holiday>
<StartDate>2006-07-03</StartDate>
<EndDate>2006-07-07</EndDate>
</Holiday>
<Employee>
<Number>42</Number>
<FirstName>Arjen</FirstName>
<LastName>Poutsma</LastName>
</Employee>
</HolidayRequest>
The order of the two elements does not matter: <Employee/> could have been the first element just as
well. What is important is that all of the data is there. In fact, the data is the only thing that is important:
we are taking a data-driven approach.
This generated schema obviously can be improved. The first thing to notice is that every type has a
root-level element declaration. This means that the Web service should be able to accept all of these
elements as data. This is not desirable: we only want to accept a <HolidayRequest/>. By removing
the wrapping element tags (thus keeping the types), and inlining the results, we can accomplish this.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:hr="http://mycompany.com/hr/schemas"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="Holiday" type="hr:HolidayType"/>
<xs:element name="Employee" type="hr:EmployeeType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="HolidayType">
<xs:sequence>
<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="EmployeeType">
<xs:sequence>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
The schema still has one problem: with a schema like this, you can expect the following messages
to validate:
10
Clearly, we must make sure that the start and end date are really dates. XML Schema has an excellent
built-in date type which we can use. We also change the NCNames to strings. Finally, we change the
sequence in <HolidayRequest/> to all. This tells the XML parser that the order of <Holiday/> and
<Employee/> is not significant. Our final XSD now looks like this:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:hr="http://mycompany.com/hr/schemas"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:all>
<xs:element name="Holiday" type="hr:HolidayType"/>
<xs:element name="Employee" type="hr:EmployeeType"/>
</xs:all>
</xs:complexType>
</xs:element>
<xs:complexType name="HolidayType">
<xs:sequence>
<xs:element name="StartDate" type="xs:date"/>
<xs:element name="EndDate" type="xs:date"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="EmployeeType">
<xs:sequence>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:string"/>
<xs:element name="LastName" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
all
We use the xsd:date data type, which consist of a year, month, and day, for <StartDate/> and
<EndDate/>.
xsd:string is used for the first and last name.
tells the XML parser that the order of <Holiday/> and <Employee/> is not significant.
11
Next, we add our messages based on the written schema types. We only have one message: one with
the <HolidayRequest/> we put in the schema:
<wsdl:message name="HolidayRequest">
<wsdl:part element="schema:HolidayRequest" name="HolidayRequest"/>
</wsdl:message>
<wsdl:portType name="HumanResource">
<wsdl:operation name="Holiday">
<wsdl:input message="tns:HolidayRequest" name="HolidayRequest"/>
</wsdl:operation>
</wsdl:portType>
That finished the abstract part of the WSDL (the interface, as it were), and leaves the concrete part.
The concrete part consists of a binding, which tells the client how to invoke the operations you've just
defined; and a service, which tells it where to invoke it.
Adding a concrete part is pretty standard: just refer to the abstract part you defined previously, make
sure you use document/literal for the soap:binding elements (rpc/encoded is deprecated), pick a
soapAction for the operation (in this case http://mycompany.com/RequestHoliday, but any URI
will do), and determine the location URL where you want request to come in (in this case http://
mycompany.com/humanresources):
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:schema="http://mycompany.com/hr/schemas"
xmlns:tns="http://mycompany.com/hr/definitions"
targetNamespace="http://mycompany.com/hr/definitions">
<wsdl:types>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:import namespace="http://mycompany.com/hr/schemas"
schemaLocation="hr.xsd"/>
</xsd:schema>
</wsdl:types>
<wsdl:message name="HolidayRequest">
<wsdl:portType name="HumanResource">
<wsdl:operation name="Holiday">
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
12
We define the HumanResource port type, which gets used in the binding.
The soapAction attribute signifies the SOAPAction HTTP header that will be sent with every
request.
The http://localhost:8080/holidayService/ address is the URL where the Web service can
be invoked.
This is the final WSDL. We will describe how to implement the resulting schema and WSDL in the
next section.
This command will create a new directory called holidayService. In this directory, there is a
'src/main/webapp' directory, which will contain the root of the WAR file. You will find the
standard web application deployment descriptor 'WEB-INF/web.xml' here, which defines a SpringWS MessageDispatcherServlet and maps all incoming requests to this servlet.
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
13
In addition to the above 'WEB-INF/web.xml' file, you will also need another, Spring-WS-specific
configuration file, named 'WEB-INF/spring-ws-servlet.xml'. This file contains all of the SpringWS-specific beans such as EndPoints, WebServiceMessageReceivers, and suchlike, and is used
to create a new Spring container. The name of this file is derived from the name of the
attendant servlet (in this case 'spring-ws') with '-servlet.xml' appended to it. So if you defined
a MessageDispatcherServlet with the name 'dynamite', the name of the Spring-WS-specific
configuration file would be 'WEB-INF/dynamite-servlet.xml'.
(You can see the contents of the 'WEB-INF/spring-ws-servlet.xml' file for this example in ???.)
org.springframework.beans.factory.annotation.Autowired;
org.springframework.ws.server.endpoint.annotation.Endpoint;
org.springframework.ws.server.endpoint.annotation.PayloadRoot;
org.springframework.ws.server.endpoint.annotation.RequestPayload;
import
import
import
import
import
com.mycompany.hr.service.HumanResourceService;
org.jdom.Element;
org.jdom.JDOMException;
org.jdom.Namespace;
org.jdom.xpath.XPath;
@Endpoint
public class HolidayEndpoint {
14
The HolidayEndpoint is annotated with @Endpoint. This marks the class as a special sort of
@Component, suitable for handling XML messages in Spring-WS, and also making it eligible for
suitable for component scanning.
The HolidayEndpoint requires the HumanResourceService business service to operate, so
we inject the dependency via the constructor and annotate it with @Autowired. Next, we set
up XPath expressions using the JDOM API. There are three expressions: //hr:StartDate
for extracting the <StartDate> text value, //hr:EndDate for extracting the end date and
concat(//hr:FirstName,' ',//hr:LastName) for extracting and concatenating the names of
the employee.
The @PayloadRoot annotation tells Spring-WS that the handleHolidayRequest method is
suitable for handling XML messages. The sort of message that this method can handle is indicated
by the annotation values, in this case, it can handle XML elements that have the HolidayRequest
local part and the http://mycompany.com/hr/schemas namespace. More information about
mapping messages to endpoints is provided in the next section.
The handleHolidayRequest(..) method is the main handling method method, which gets passed
with the <HolidayRequest/> element from the incoming XML message. The @RequestPayload
annotation indicates that the holidayRequest parameter should be mapped to the payload of
the request message. We use the XPath expressions to extract the string values from the XML
messages, and convert these values to Date objects using a SimpleDateFormat. With these values,
we invoke a method on the business service. Typically, this will result in a database transaction
being started, and some records being altered in the database. Finally, we define a void return
15
Here is how we would configure these classes in our spring-ws-servlet.xml Spring XML
configuration file, by using component scanning. We also instruct Spring-WS to use annotation-driven
endpoints, with the <sws:annotation-driven> element.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schem
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-service
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-c
<context:component-scan base-package="com.mycompany.hr"/>
<sws:annotation-driven/>
</beans>
16
basically means that whenever an XML message is received with the namespace http://
mycompany.com/hr/schemas and the HolidayRequest local name, it will be routed to the
handleHolidayRequest method. By using the <sws:annotation-driven> element in our
configuration, we enable the detection of the @PayloadRoot annotations. It is possible (and quite
common) to have multiple, related handling methods in an endpoint, each of them handling different
XML messages.
There are also other ways to map endpoints to XML messages, which will be described in the next
chapter.
locationUri="/holidayService/"
targetNamespace="http://mycompany.com/hr/definitions">
<sws:xsd location="/WEB-INF/hr.xsd"/>
</sws:dynamic-wsdl>
portTypeName="HumanResource"
The id determines the URL where the WSDL can be retrieved. In this case, the id is holiday,
which means that the WSDL can be retrieved as holiday.wsdl in the servlet context. The full
URL will typically be http://localhost:8080/holidayService/holiday.wsdl.
Next, we set the WSDL port type to be HumanResource.
We set the location where the service can be reached: /holidayService/. We use a relative URI
and we instruct the framework to transform it dynamically to an absolute URI. Hence, if the
service is deployed to different contexts we don't have to change the URI manually. For more
information, please refer to Section 5.3.1.1, Automatic WSDL exposure
For the location transformation to work, we need to add one more parameter to the web.xml:
<init-param>
<param-name>transformWsdlLocations</param-name>
<param-value>true</param-value>
</init-param>
We define the target namespace for the WSDL definition itself. Setting this attribute is not
required. If not set, the WSDL will have the same namespace as the XSD schema.
The xsd element refers to the human resource schema we defined in Section 3.3, Data Contract.
We simply placed the schema in the WEB-INF directory of the application.
You can create a WAR file using mvn install. If you deploy the application (to Tomcat, Jetty,
etc.), and point your browser at this location [http://localhost:8080/holidayService/holiday.wsdl], you
will see the generated WSDL. This WSDL is ready to be used by clients, such as soapUI [http://
www.soapui.org/], or other SOAP frameworks.
That concludes this tutorial. The tutorial code can be found in the full distribution of Spring-WS. The
next step would be to look at the echo sample application that is part of the distribution. After that, look
17
18
19
javax.xml.transform.dom.DOMSource
org.w3c.dom.Node
javax.xml.transform.dom.DOMResult
org.w3c.dom.Node
javax.xml.transform.sax.SAXSource
org.xml.sax.InputSource
and
org.xml.sax.XMLReader
javax.xml.transform.sax.SAXResult
org.xml.sax.ContentHandler
javax.xml.transform.stream.StreamSource
java.io.File,
java.io.InputStream,
or
java.io.OutputStream,
or
java.io.Reader
javax.xml.transform.stream.StreamResult
java.io.File,
java.io.Writer
In addition to reading from and writing to the payload, a Web service message can write itself to an
output stream.
4.1.2. SoapMessage
The SoapMessage is a subclass of WebServiceMessage. It contains SOAP-specific methods, such
as getting SOAP Headers, SOAP Faults, etc. Generally, your code should not be dependent on
SoapMessage, because the content of the SOAP Body (the payload of the message) can be obtained via
getPayloadSource() and getPayloadResult() in the WebServiceMessage. Only when it is necessary
to perform SOAP-specific actions, such as adding a header, getting an attachment, etc., should you
need to cast WebServiceMessage to SoapMessage.
20
Shared components
4.1.3.1. SaajSoapMessageFactory
The SaajSoapMessageFactory uses the SOAP with Attachments API for Java to create SoapMessage
implementations. SAAJ is part of J2EE 1.4, so it should be supported under most modern application
servers. Here is an overview of the SAAJ versions supplied by common application servers:
Application Server
SAAJ Version
BEA WebLogic 8
1.1
BEA WebLogic 9
1.1/1.2a
IBM WebSphere 6
1.2
SUN Glassfish 1
1.3
Weblogic 9 has a known bug in the SAAJ 1.2 implementation: it implement all the 1.2 interfaces, but throws a
when called. Spring Web Services has a workaround: it uses SAAJ 1.1 when operating on
WebLogic 9.
UnsupportedOperationException
Additionally, Java SE 6 includes SAAJ 1.3. You wire up a SaajSoapMessageFactory like so:
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
Note
SAAJ is based on DOM, the Document Object Model. This means that all SOAP messages
are stored in memory. For larger SOAP messages, this may not be very performant. In that
case, the AxiomSoapMessageFactory might be more applicable.
4.1.3.2. AxiomSoapMessageFactory
The AxiomSoapMessageFactory uses the AXis 2 Object Model to create SoapMessage
implementations. AXIOM is based on StAX, the Streaming API for XML. StAX provides a pull-based
mechanism for reading XML messages, which can be more efficient for larger messages.
To increase reading performance on the AxiomSoapMessageFactory, you can set the payloadCaching
property to false (default is true). This will read the contents of the SOAP body directly from the socket
stream. When this setting is enabled, the payload can only be read once. This means that you have to
make sure that any pre-processing (logging etc.) of the message does not consume it.
You use the AxiomSoapMessageFactory as follows:
In addition to payload caching, AXIOM also supports full streaming messages, as defined in the
StreamingWebServiceMessage. This means that the payload can be directly set on the response
message, rather than being written to a DOM tree or buffer.
Full streaming for AXIOM is used when a handler method returns a JAXB2-supported object. It will
automatically set this marshalled object into the response message, and write it out to the outgoing
socket stream when the response is going out.
For
more
information
to
the
class-level
Javadoc
for
21
Shared components
4.1.3.3. SOAP 1.1 or 1.2
Both the SaajSoapMessageFactory and the AxiomSoapMessageFactory have a soapVersion property,
where you can inject a SoapVersion constant. By default, the version is 1.1, but you can set it to 1.2
like so:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12"/>
</property>
</bean>
</beans>
In the example above, we define a SaajSoapMessageFactory that only accepts SOAP 1.2 messages.
Caution
Even though both versions of SOAP are quite similar in format, the 1.2 version is not
backwards compatible with 1.1 because it uses a different XML namespace. Other major
differences between SOAP 1.1 and 1.2 include the different structure of a Fault, and the
fact that SOAPAction HTTP headers are effectively deprecated, thought they still work.
One important thing to note with SOAP version numbers, or WS-* specification version
numbers in general, is that the latest version of a specification is generally not the most
popular version. For SOAP, this means that currently, the best version to use is 1.1. Version
1.2 might become more popular in the future, but currently 1.1 is the safest bet.
4.1.4. MessageContext
Typically, messages come in pairs: a request and a response. A request is created on the client-side,
which is sent over some transport to the server-side, where a response is generated. This response gets
sent back to the client, where it is read.
In Spring Web Services, such a conversation is contained in a MessageContext, which has properties
to get request and response messages. On the client-side, the message context is created by the
WebServiceTemplate. On the server-side, the message context is read from the transport-specific input
stream. For example, in HTTP, it is read from the HttpServletRequest and the response is written
back to the HttpServletResponse.
4.2. TransportContext
One of the key properties of the SOAP protocol is that it tries to be transport-agnostic. This is why,
for instance, Spring-WS does not support mapping messages to endpoints by HTTP request URL, but
rather by mesage content.
22
Shared components
However, sometimes it is necessary to get access to the underlying transport, either on the client or
server side. For this, Spring Web Services has the TransportContext. The transport context allows
access to the underlying WebServiceConnection, which typically is a HttpServletConnection on the
server side; or a HttpUrlConnection or CommonsHttpConnection on the client side. For example, you
can obtain the IP address of the current request in a server-side endpoint or interceptor like so:
4.3.1. XPathExpression
The XPathExpression is an abstraction over a compiled XPath expression, such as the Java 5
javax.xml.xpath.XPathExpression, or the Jaxen XPath class. To construct an expression in an
application context, there is the XPathExpressionFactoryBean. Here is an example which uses this
factory bean:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="nameExpression" class="org.springframework.xml.xpath.XPathExpressionFactoryBean">
<property name="expression" value="/Contacts/Contact/Name"/>
</bean>
<bean id="myEndpoint" class="sample.MyXPathClass">
<constructor-arg ref="nameExpression"/>
</bean>
</beans>
The expression above does not use namespaces, but we could set those using the namespaces property
of the factory bean. The expression can be used in the code as follows:
package sample;
23
Shared components
For a more flexible approach, you can use a NodeMapper, which is similar to the RowMapper in Spring's
JDBC support. The following example shows how we can use it:
package sample;
public class MyXPathClass
Similar to mapping rows in Spring JDBC's RowMapper, each result node is mapped using an anonymous
inner class. In this case, we create a Contact object, which we use later on.
4.3.2. XPathTemplate
The XPathExpression only allows you to evaluate a single, pre-compiled expression. A more flexible,
though slower, alternative is the XpathTemplate. This class follows the common template pattern used
throughout Spring (JdbcTemplate, JmsTemplate, etc.). Here is an example:
package sample;
public class MyXPathClass {
private XPathOperations template = new Jaxp13XPathTemplate();
public void doXPath(Source source) {
String name = template.evaluateAsString("/Contacts/Contact/Name", request);
// do something with name
}
24
Shared components
}
Caution
Make sure to use Commons Logging version 1.1 or higher. Earlier versions have class
loading issues, and do not integrate with the Log4J TRACE level.
To log all server-side messages, simply set the org.springframework.ws.server.MessageTracing
logger to level DEBUG or TRACE. On the debug level, only the payload root element
is logged; on the TRACE level, the entire message content. If you only want to log
sent messages, use the org.springframework.ws.server.MessageTracing.sent logger; or
org.springframework.ws.server.MessageTracing.received to log received messages.
On the client-side, similar loggers exist: org.springframework.ws.client.MessageTracing.sent
and org.springframework.ws.client.MessageTracing.received.
Here is an example log4j.properties configuration, logging the full content of sent messages on the
client side, and only the payload root element for client-side received messages. On the server-side,
the payload root is logged for both sent and received messages:
log4j.rootCategory=INFO, stdout
log4j.logger.org.springframework.ws.client.MessageTracing.sent=TRACE
log4j.logger.org.springframework.ws.client.MessageTracing.received=DEBUG
log4j.logger.org.springframework.ws.server.MessageTracing=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%p [%c{3}] %m%n
25
26
5.3. Transports
Spring Web Services supports multiple transport protocols. The most common is the HTTP transport,
for which a custom servlet is supplied, but it is also possible to send messages over JMS, and even
email.
5.3.1. MessageDispatcherServlet
The MessageDispatcherServlet is a standard Servlet which conveniently extends from the standard
Spring Web DispatcherServlet, and wraps a MessageDispatcher. As such, it combines the attributes
of these into one: as a MessageDispatcher, it follows the same request handling flow as described in
the previous section. As a servlet, the MessageDispatcherServlet is configured in the web.xml of your
web application. Requests that you want the MessageDispatcherServlet to handle will have to be
mapped using a URL mapping in the same web.xml file. This is standard Java EE servlet configuration;
an example of such a MessageDispatcherServlet declaration and mapping can be found below.
<web-app>
<servlet>
<servlet-name>spring-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
27
In the example above, all requests will be handled by the 'spring-ws' MessageDispatcherServlet.
This is only the first step in setting up Spring Web Services, because the various component beans
used by the Spring-WS framework also need to be configured; this configuration consists of standard
Spring XML <bean/> definitions. Because the MessageDispatcherServlet is a standard Spring
DispatcherServlet, it will look for a file named [servlet-name]-servlet.xml in the WEB-INF
directory of your web application and create the beans defined there in a Spring container. In the
example above, that means that it looks for '/WEB-INF/spring-ws-servlet.xml'. This file will contain
all of the Spring Web Services beans such as endpoints, marshallers and suchlike.
5.3.1.1. Automatic WSDL exposure
The MessageDispatcherServlet will automatically detect any WsdlDefinition beans defined in
it's Spring container. All such WsdlDefinition beans that are detected will also be exposed via a
WsdlDefinitionHandlerAdapter; this is a very convenient way to expose your WSDL to clients
simply by just defining some beans.
By way of an example, consider the following <static-wsdl>definition, defined in the Spring-WS
configuration file (/WEB-INF/[servlet-name]-servlet.xml). Take notice of the value of the 'id'
attribute, because this will be used when exposing the WSDL.
<sws:static-wsdl id="orders" location="/WEB-INF/wsdl/orders.wsdl"/>
The WSDL defined in the 'Orders.wsdl' file can then be accessed via GET requests to a URL of the
following form (substitute the host, port and servlet context path as appropriate).
http://localhost:8080/spring-ws/orders.wsdl
Note
All WsdlDefinition bean definitions are exposed by the MessageDispatcherServlet
under their bean id (or bean name) with the suffix .wsdl. So if the bean id is echo, the
host name is "server", and the Servlet context (war name) is "spring-ws", the WSDL can
be obtained via http://server/spring-ws/echo.wsdl
Another
nice
feature
of
28
Consult the class-level Javadoc on the WsdlDefinitionHandlerAdapter class to learn more about the
whole transformation process.
As an alternative to writing the WSDL by hand, and exposing it with <static-wsdl>, Spring Web
Services can also generate a WSDL from an XSD schema. This is the approach shown in Section 3.7,
Publishing the WSDL. The next application context snippet shows how to create such a dynamic
WSDL file:
<sws:dynamic-wsdl id="orders"
portTypeName="Orders"
locationUri="http://localhost:8080/ordersService/">
<sws:xsd location="/WEB-INF/xsd/Orders.xsd"/>
</sws:dynamic-wsdl>
The <dynamic-wsdl> builds a WSDL from a XSD schema by using conventions. It iterates over all
element elements found in the schema, and creates a message for all elements. Next, it creates WSDL
operation for all messages that end with the defined request or response suffix. The default request
suffix is Request; the default response suffix is Response, though these can be changed by setting
the requestSuffix and responseSuffix attributes on <dynamic-wsdl />, respectively. It also builds a
portType, binding, and service based on the operations.
For instance, if our Orders.xsd schema defines the GetOrdersRequest and GetOrdersResponse
elements, <dynamic-wsdl> will create a GetOrdersRequest and GetOrdersResponse message, and a
GetOrders operation, which is put in a Orders port type.
If you want to use multiple schemas, either by includes or imports, you will want to put Commons
XMLSchema on the class path. If Commons XMLSchema is on the class path, the above <dynamicwsdl> element will follow all XSD imports and includes, and will inline them in the WSDL as a single
XSD. This greatly simplifies the deployment of the schemas, which still making it possible to edit
them separately.
The <dynamic-wsdl> element depends on the DefaultWsdl11Definition class. This definition
class uses WSDL providers in the org.springframework.ws.wsdl.wsdl11.provider package and the
ProviderBasedWsdl4jDefinition to generate a WSDL the first time it is requested. Refer to the classlevel Javadoc of these classes to see how you can extend this mechanism, if necessary.
Caution
Even though it can be quite handy to create the WSDL at runtime from your XSDs, there
are a couple of drawbacks to this approach. First off, though we try to keep the WSDL
generation process consistent between releases, there is still the possibility that it changes
29
30
31
Web
Services
32
For
more
information
on
the
SimpleHttpServerFactoryBean,
refer
to
the Javadoc [http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/remoting/
support/SimpleHttpServerFactoryBean.html].
33
5.4. Endpoints
Endpoints are the central concept in Spring-WS's server-side support. Endpoints provide access to the
application behavior which is typically defined by a business service interface. An endpoint interprets
the XML request message and uses that input to invoke a method on the business service (typically).
The result of that service invocation is represented as a response message. Spring-WS has a wide
variety of endpoints, using various ways to handle the XML message, and to create a response.
You create an endpoint by annotating a class with the @Endpoint annotation. In the class, you define
one or more methods that handle the incoming XML request, by using a wide variety of parameter
types (such as DOM elements, JAXB2 objects, etc). You indicate the sort of messages a method can
handle by using another annotation (typically @PayloadRoot).
Consider the following sample endpoint:
package samples;
import org.w3c.dom.Element;
import
import
import
import
org.springframework.beans.factory.annotation.Autowired;
org.springframework.ws.server.endpoint.annotation.Endpoint;
org.springframework.ws.server.endpoint.annotation.PayloadRoot;
org.springframework.ws.soap.SoapHeader;
@Endpoint
public class AnnotationOrderEndpoint {
34
...
}
The constructor is marked with @Autowired, so that the OrderService business service is injected
into this endpoint.
The order method takes a Element as a parameter, annotated with @RequestPayload. This means
that the payload of the message is passed on this method as a DOM element. The method has a
void return type, indicating that no response message is sent.
For more information about endpoint methods, refer to Section 5.4.1, @Endpoint handling
methods.
The getOrder method takes a OrderRequest as a parameter, annotated with @RequestPayload
as well. This parameter is a JAXB2-supported object (it is annotated with @XmlRootElement).
This means that the payload of the message is passed on to this method as a unmarshalled object.
The SoapHeader type is also given as a parameter. On invocation, this parameter will contain
the SOAP header of the request message. The method is also annotated with @ResponsePayload,
indicating that the return value (the Order) is used as the payload of the response message.
For more information about endpoint methods, refer to Section 5.4.1, @Endpoint handling
methods.
The two handling methods of this endpoint are marked with @PayloadRoot, indicating what sort
of request messages can be handled by the method: the getOrder method will be invoked for
requests with a orderRequest local name and a http://samples namespace URI; the order
method for requests with a order local name.
For more information about @PayloadRoot, refer to Section 5.5, Endpoint mappings.
To enable the support for @Endpoint and related Spring-WS annotations, you will need to add the
following to your Spring application context:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
<sws:annotation-driven />
</beans>
In the next couple of sections, a more elaborate description of the @Endpoint programming model is
given.
Note
Endpoints, like any other Spring Bean, are scoped as a singleton by default, i.e. one
instance of the bean definition is created per container. Being a singleton implies that
35
The order method takes a Element as a parameter, annotated with @RequestPayload. This means that
the payload of the message is passed on this method as a DOM element. The method has a void return
type, indicating that no response message is sent.
5.4.1.1. Handling method parameters
The handling method typically has one or more parameters that refer to various parts of the incoming
XML message. Most commonly, the handling method will have a single parameter that will map to
the payload of the message, but it is also possible to map to other parts of the request message, such
as a SOAP header. This section will describe the parameters you can use in your handling method
signatures.
To map a parameter to the payload of the request message, you will need to annotate this parameter
with the @RequestPayload annotation. This annotation tells Spring-WS that the parameter needs to be
bound to the request payload.
The following table describes the supported parameter types. It shows the supported types, whether
the parameter should be annotated with @RequestPayload, and any additional notes.
Name
Supported
types
TrAX
parameter @RequestPayload
required?
javax.xml.transform.Source
Additional notes
Enabled by default.
and
sub-interfaces
(DOMSource, SAXSource,
StreamSource,
and
StAXSource)
36
Supported
types
parameter @RequestPayload
required?
Additional notes
org.w3c.dom.Element
Enabled by default
dom4j
org.dom4j.Element
JDOM
org.jdom.Element
XOM
nu.xom.Element
StAX
javax.xml.stream.XMLStreamReader
Enabled
by
default,
see Section 5.4.1.1.1,
@XPathParam.
W3C DOM
and
javax.xml.stream.XMLEventReader
XPath
Message context
SOAP
Any
boolean, double,
String,
org.w3c.Node,
org.w3c.dom.NodeList,
or
type
that
can
be converted from a
String by a Spring 3
conversion service [http://
static.springsource.org/
spring/docs/3.0.x/springframework-reference/
html/
validation.html#coreconvert],
and
that
is
annotated
with
@XPathParam.
org.springframework.ws.context.MessageContext
Enabled by default.
org.springframework.ws.soap.SoapMessage
,
Enabled by default.
org.springframework.ws.soap.SoapBody,
org.springframework.ws.soap.SoapEnvelope,
and
org.springframework.ws.soap.SoapHeader
JAXB2
Any
type
annotated
that
is
with
javax.xml.bind.annotation.XmlRootElement,
and
javax.xml.bind.JAXBElement.
OXM
Any
type
supported
by a Spring OXM
Unmarshaller
[http://
static.springsource.org/
spring/docs/3.0.x/spring-
Enabled
when
the
unmarshaller
attribute
of
<sws:annotationdriven/> is specified.
37
Supported
types
parameter @RequestPayload
required?
Additional notes
framework-reference/
html/
oxm.html#d0e26164].
Here are some examples of possible method signatures:
This method will be invoked with the payload of the request message as a DOM
org.w3c.dom.Element.
This
method
will
be
invoked
This method will be invoked with the payload of the request message unmarshalled into a
MyJaxb2Object (which is annotated with @XmlRootElement). The payload of the message is also
given as a DOM Element. The whole message context is passed on as the third parameter.
As you can see, there are a lot of possibilities when it comes to defining handling method signatures.
It is even possible to extend this mechanism, and to support your own parameter types. Refer to the
class-level Javadoc of DefaultMethodEndpointAdapter and MethodArgumentResolver to see how.
5.4.1.1.1. @XPathParam
One parameter type needs some extra explanation: @XPathParam. The idea here is that you simply
annotate one or more method parameter with an XPath expression, and that each such annotated
parameter will be bound to the evaluation of the expression. Here is an example:
package samples;
import javax.xml.transform.Source;
import
import
import
import
org.springframework.ws.server.endpoint.annotation.Endpoint;
org.springframework.ws.server.endpoint.annotation.Namespace;
org.springframework.ws.server.endpoint.annotation.PayloadRoot;
org.springframework.ws.server.endpoint.annotation.XPathParam;
@Endpoint
public class AnnotationOrderEndpoint {
private final OrderService orderService;
public AnnotationOrderEndpoint(OrderService orderService) {
this.orderService = orderService;
}
@PayloadRoot(localPart = "orderRequest", namespace = "http://samples")
@Namespace(prefix = "s", uri="http://samples")
public Order getOrder(@XPathParam("/s:orderRequest/@id") int orderId) {
Order order = orderService.getOrder(orderId);
// create Source from order and return it
38
Since we use the prefix 's' in our XPath expression, we must bind it to the http://samples namespace.
This is accomplished with the @Namespace annotation. Alternatively, we could have placed this
annotation on the type-level to use the same namespace mapping for all handler methods, or even the
package-level (in package-info.java) to use it for multiple endpoints.
Using the @XPathParam, you can bind to all the data types supported by XPath:
boolean or Boolean
double or Double
String
Node
NodeList
In addition to this list, you can use any type that can be converted from a String by a Spring 3
conversion service [http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/
validation.html#core-convert].
5.4.1.2. Handling method return types
To send a response message, the handling needs to specify a return type. If no response message is
required, the method can simply declare a void return type. Most commonly, the return type is used to
create the payload of the response message, but it is also possible to map to other parts of the response
message. This section will describe the return types you can use in your handling method signatures.
To map the return value to the payload of the response message, you will need to annotate the method
with the @ResponsePayload annotation. This annotation tells Spring-WS that the return value needs
to be bound to the response payload.
The following table describes the supported return types. It shows the supported types, whether the
parameter should be annotated with @ResponsePayload, and any additional notes.
Name
@ResponsePayload
Additional notes
required?
void
Enabled by default.
javax.xml.transform.Source
Enabled by default.
org.w3c.dom.Element
Enabled by default
dom4j
org.dom4j.Element
JDOM
org.jdom.Element
No response
TrAX
and
sub-interfaces
(DOMSource, SAXSource,
StreamSource,
and
StAXSource)
W3C DOM
39
@ResponsePayload
Additional notes
required?
XOM
JAXB2
nu.xom.Element
Any
type
annotated
that
is
with
javax.xml.bind.annotation.XmlRootElement,
and
javax.xml.bind.JAXBElement.
OXM
Enabled
when
the
marshaller
attribute
of
<sws:annotationdriven/> is specified.
As you can see, there are a lot of possibilities when it comes to defining handling method signatures.
It is even possible to extend this mechanism, and to support your own parameter types. Refer to the
class-level Javadoc of DefaultMethodEndpointAdapter and MethodReturnValueHandler to see how.
40
two
the
endpoint
mappings
that
can
direct
and
enabled by
PayloadRootAnnotationMethodEndpointMapping
SoapActionAnnotationMethodEndpointMapping,
both
<sws:annotation-driven/> in your application context.
of
which
are
requests
the
using
5.5.1. WS-Addressing
WS-Addressing specifies a transport-neutral routing mechanism. It is based on a To and Action SOAP
header, which indicate the destination and intent of the SOAP message, respectively. Additionally,
WS-Addressing allows you to define a return address (for normal messages and for faults), and a
unique message identifier which can be used for correlation 1. Here is an example of a WS-Addressing
message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://www.w3.org/2005/08/addressing">
<SOAP-ENV::Header>
<wsa:MessageID>urn:uuid:21363e0d-2645-4eb7-8afd-2f5ee1bb25cf</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://example.com/business/client1</wsa:Address>
</wsa:ReplyTo>
<wsa:To S:mustUnderstand="true">http://example/com/fabrikam</wsa:To>
<wsa:Action>http://example.com/fabrikam/mail/Delete</wsa:Action>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<f:Delete xmlns:f="http://example.com/fabrikam">
<f:maxCount>42</f:maxCount>
</f:Delete>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
In this example, the destination is set to http://example/com/fabrikam, while the action is set
to http://example.com/fabrikam/mail/Delete. Additionally, there is a message identifier, and an
reply-to address. By default, this address is the "anonymous" address, indicating that a response should
be sent using the same channel as the request (i.e. the HTTP response), but it can also be another
address, as indicated in this example.
In Spring Web Services, WS-Addressing is implemented as an endpoint mapping.
Using this mapping, you associate WS-Addressing actions with endpoints, similar to the
SoapActionAnnotationMethodEndpointMapping described above.
41
AnnotationActionEndpointMapping
SoapActionAnnotationMethodEndpointMapping,
is
similar
to
the
but uses WS-Addressing headers instead of the
The mapping above routes requests which have a WS-Addressing Action of http://samples/
RequestOrder to the getOrder method. Requests with http://samples/CreateOrder will be routed
to the order method..
By default, the AnnotationActionEndpointMapping supports both the 1.0 (May 2006), and the August
2004 editions of WS-Addressing. These two versions are most popular, and are interoperable with
Axis 1 and 2, JAX-WS, XFire, Windows Communication Foundation (WCF), and Windows Services
Enhancements (WSE) 3.0. If necessary, specific versions of the spec can be injected into the versions
property.
In addition to the @Action annotation, you can annotate the class with the @Address annotation. If set,
the value is compared to the To header property of the incoming message.
Finally, there is the messageSenders property, which is required for sending response messages to nonanonymous, out-of-bound addresses. You can set MessageSender implementations in this property,
the same as you would on the WebServiceTemplate. See Section 6.2.1.1, URIs and Transports.
42
Here, we define one 'global' interceptor (MyGlobalInterceptor) that intercepts all request and
responses. We also define an interceptor that only applies to XML messages that have the http://
www.example.com as a payload root namespace. Here, we could have defined a localPart attribute in
addition to the namespaceUri to further limit the messages the interceptor applies to. Finally, we define
two interceptors that apply when the message has a http://www.example.com/SoapAction SOAP
action. Notice how the second interceptor is actually a reference to a bean definition outside of the
<interceptors> element. You can use bean references anywhere inside the <interceptors> element.
Interceptors
must
implement
the
EndpointInterceptor
interface
from
the
org.springframework.ws.server package. This interface defines three methods, one that can be used
for handling the request message before the actual endpoint will be executed, one that can be used
for handling a normal response message, and one that can be used for handling fault messages, both
of which will be called after the endpoint is executed. These three methods should provide enough
flexibility to do all kinds of pre- and post-processing.
The handleRequest(..) method on the interceptor returns a boolean value. You can use this method
to interrupt or continue the processing of the invocation chain. When this method returns true, the
endpoint execution chain will continue, when it returns false, the MessageDispatcher interprets
this to mean that the interceptor itself has taken care of things and does not continue executing the
other interceptors and the actual endpoint in the invocation chain. The handleResponse(..) and
handleFault(..) methods also have a boolean return value. When these methods return false, the
response will not be sent back to the client.
There are a number of standard EndpointInterceptor implementations you can use in your Web
service. Additionally, there is the XwsSecurityInterceptor, which is described in Section 7.2,
XwsSecurityInterceptor .
5.5.2.1. PayloadLoggingInterceptor and SoapEnvelopeLoggingInterceptor
When developing a Web service, it can be useful to log the incoming and outgoing XML messages.
SWS facilitates this with the PayloadLoggingInterceptor and SoapEnvelopeLoggingInterceptor
classes. The former logs just the payload of the message to the Commons Logging Log; the latter logs
the entire SOAP envelope, including SOAP headers. The following example shows you how to define
them in an endpoint mapping:
43
Both of these interceptors have two properties: 'logRequest' and 'logResponse', which can be set to
false to disable logging for either request or response messages.
5.5.2.2. PayloadValidatingInterceptor
One of the benefits of using a contract-first development style is that we can use the
schema to validate incoming and outgoing XML messages. Spring-WS facilitates this with the
PayloadValidatingInterceptor. This interceptor requires a reference to one or more W3C XML or
RELAX NG schemas, and can be set to validate requests or responses, or both.
Note
Note that request validation may sound like a good idea, but makes the resulting Web
service very strict. Usually, it is not really important whether the request validates, only if
the endpoint can get sufficient information to fullfill a request. Validating the response is
a good idea, because the endpoint should adhere to its schema. Remember Postel's Law:
Be conservative in what you do; be liberal in what you accept from others.
Here is an example that uses the PayloadValidatingInterceptor; in this example, we use the
schema in /WEB-INF/orders.xsd to validate the response, but not the request. Note that the
PayloadValidatingInterceptor can also accept multiple schemas using the schemas property.
<bean id="validatingInterceptor"
class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
<property name="schema" value="/WEB-INF/orders.xsd"/>
<property name="validateRequest" value="false"/>
<property name="validateResponse" value="true"/>
</bean>
5.5.2.3. PayloadTransformingInterceptor
To transform the payload to another XML format, Spring Web Services offers the
PayloadTransformingInterceptor. This endpoint interceptor is based on XSLT style sheets,
and is especially useful when supporting multiple versions of a Web service: you can
transform the older message format to the newer format. Here is an example to use the
PayloadTransformingInterceptor:
<bean id="transformingInterceptor"
class="org.springframework.ws.server.endpoint.interceptor.PayloadTransformingInterceptor">
<property name="requestXslt" value="/WEB-INF/oldRequests.xslt"/>
<property name="responseXslt" value="/WEB-INF/oldResponses.xslt"/>
</bean>
44
5.6.1. SoapFaultMappingExceptionResolver
The SoapFaultMappingExceptionResolver is a more sophisticated implementation. This resolver
enables you to take the class name of any exception that might be thrown and map it to a SOAP Fault,
like so:
<beans>
<bean id="exceptionResolver"
class="org.springframework.ws.soap.server.endpoint.SoapFaultMappingExceptionResolver">
<property name="defaultFault" value="SERVER"/>
<property name="exceptionMappings">
<value>
org.springframework.oxm.ValidationFailureException=CLIENT,Invalid request
</value>
</property>
</bean>
</beans>
The key values and default endpoint use the format faultCode,faultString,locale, where only the
fault code is required. If the fault string is not set, it will default to the exception message. If the
language is not set, it will default to English. The above configuration will map exceptions of type
ValidationFailureException to a client-side SOAP Fault with a fault string "Invalid request", as
can be seen in the following response:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>Invalid request</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
45
5.6.2. SoapFaultAnnotationExceptionResolver
Finally, it is also possible to annotate exception classes with the @SoapFault annotation, to indicate the
SOAP Fault that should be returned whenever that exception is thrown. In order for these annotations
to be picked up, you need to add the SoapFaultAnnotationExceptionResolver to your application
context. The elements of the annotation include a fault code enumeration, fault string or reason, and
language. Here is an example exception:
package samples;
import org.springframework.ws.soap.server.endpoint.annotation.FaultCode;
import org.springframework.ws.soap.server.endpoint.annotation.SoapFault;
@SoapFault(faultCode = FaultCode.SERVER)
public class MyBusinessException extends Exception {
public MyClientException(String message) {
super(message);
}
}
Whenever the MyBusinessException is thrown with the constructor string "Oops!" during endpoint
invocation, it will result in the following response:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Oops!</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
46
MockWebServiceClient
instance
by
MockWebServiceClient.createClient(ApplicationContext)
calling
or
MockWebServiceClient.createClient(WebServiceMessageReceiver,
WebServiceMessageFactory).
Note
Note that the MockWebServiceClient (and related classes) offers a 'fluent' API, so you
can typically use the Code Completion features (i.e. ctrl-space) in your IDE to guide you
through the process of setting up the mock server.
Note
Also note that you rely on the standard logging features available in Spring Web Services
in your unit tests. Sometimes it might be useful to inspect the request or response message
to find out why a particular tests failed. See Section 4.4, Message Logging and Tracing
for more information.
Consider, for example, this simple Web service endpoint class:
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
@Endpoint
public class CustomerEndpoint {
@ResponsePayload
}
}
47
javax.xml.transform.Source;
org.springframework.beans.factory.annotation.Autowired;
org.springframework.context.ApplicationContext;
org.springframework.test.context.ContextConfiguration;
org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
org.springframework.xml.transform.StringSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.ws.test.server.MockWebServiceClient;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("spring-ws-servlet.xml")
public class CustomerEndpointIntegrationTest {
@Autowired
private ApplicationContext applicationContext;
}
@Test
public void customerEndpoint() throws Exception {
Source requestPayload = new StringSource(
"<customerCountRequest xmlns='http://springframework.org/spring-ws'>" +
"<customerName>John Doe</customerName>" +
"</customerCountRequest>");
Source responsePayload = new StringSource(
"<customerCountResponse xmlns='http://springframework.org/spring-ws'>" +
"<customerCount>10</customerCount>" +
"</customerCountResponse>");
mockClient.sendRequest(withPayload(requestPayload)).
andExpect(payload(responsePayload));
}
}
48
You can write your own implementations of this interface, creating a request message by using the
message factory, but you certainly do not have to. The RequestCreators class provides a way to
create a RequestCreator based on a given payload in the withPayload() method. You will typically
statically import RequestCreators.
Once again you can write your own implementations of this interface, throwing AssertionErrors
when the message does not meet your expectations, but you certainly do not have to, as the
ResponseMatchers class provides standard ResponseMatcher implementations for you to use in your
tests. You will typically statically import this class.
The ResponseMatchers class provides the following response matchers:
ResponseMatchers
payload()
method
Description
Expects a given response payload.
49
method
Description
validPayload()
xpath()
soapHeader()
noFault()
mustUnderstandFault(),
clientOrSenderFault(),
serverOrReceiverFault(),
versionMismatchFault()
You can set up multiple response expectations by chaining andExpect() calls, like so:
mockClient.sendRequest(...).
andExpect(payload(expectedResponsePayload)).
andExpect(validPayload(schemaResource));
For more information on the request matchers provided by ResponseMatchers, refer to the class level
Javadoc.
50
51
The following example shows how override the default configuration, and to use Commons Http to
authenticate using HTTP authentication:
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.CommonsHttpMessageSender">
<property name="credentials">
<bean class="org.apache.commons.httpclient.UsernamePasswordCredentials">
<constructor-arg value="john"/>
<constructor-arg value="secret"/>
</bean>
</property>
</bean>
</property>
<property name="defaultUri" value="http://example.com/WebService"/>
</bean>
52
53
import java.io.StringReader;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.transport.WebServiceMessageSender;
public class WebServiceClient {
private static final String MESSAGE =
"<message xmlns=\"http://tempuri.org\">Hello Web Service World</message>";
private final WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
public void setDefaultUri(String defaultUri) {
webServiceTemplate.setDefaultUri(defaultUri);
}
// send to the configured default URI
public void simpleSendAndReceive() {
StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult(source, result);
}
// send to an explicit URI
public void customSendAndReceive() {
54
<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="webServiceClient" class="WebServiceClient">
<property name="defaultUri" value="http://localhost:8080/WebService"/>
</bean>
</beans>
The above example uses the WebServiceTemplate to send a hello world message to the web
service located at http://localhost:8080/WebService (in the case of the simpleSendAndReceive()
method), and writes the result to the console. The WebServiceTemplate is injected with the default
URI, which is used because no URI was supplied explicitly in the Java code.
Please note that the WebServiceTemplate class is thread-safe once configured (assuming that all of it's
dependencies are thread-safe too, which is the case for all of the dependencies that ship with SpringWS), and so multiple objects can use the same shared WebServiceTemplate instance if so desired.
The WebServiceTemplate exposes a zero argument constructor and messageFactory/messageSender
bean properties which can be used for constructing the instance (using a Spring container or plain Java
code). Alternatively, consider deriving from Spring-WS's WebServiceGatewaySupport convenience
base class, which exposes convenient bean properties to enable easy configuration. (You do not have
to extend this base class... it is provided as a convenience class only.)
6.2.4.
WebServiceMessageCallback
To accommodate the setting of SOAP headers and other settings on the message, the
WebServiceMessageCallback interface gives you access to the message after it has been created, but
before it is sent. The example below demonstrates how to set the SOAP Action header on a message
that is created by marshalling an object.
55
Note
Note
that
you
can
also
use
the
org.springframework.ws.soap.client.core.SoapActionCallback to set the SOAP
Action header.
6.2.4.1. WS-Addressing
In addition to the server-side WS-Addressing support, Spring Web Services also has support for this
specification on the client-side.
For
setting
WS-Addressing
headers
on
the
client,
you
can
use
the
org.springframework.ws.soap.addressing.client.ActionCallback. This callback takes the
desired Action header as a parameter. It also has constructors for specifying the WS-Addressing
version, and a To header. If not specified, the To header will default to the URL of the connection
being made.
Here is an example of setting the Action header to http://samples/RequestOrder:
6.2.5.
WebServiceMessageExtractor
The WebServiceMessageExtractor interface is a low-level callback interface that allows
you to have full control over the process to extract an Object from a received
WebServiceMessage. The WebServiceTemplate will invoke the extractData(..) method on a
supplied WebServiceMessageExtractor while the underlying connection to the serving resource is
still open. The following example illustrates the WebServiceMessageExtractor in action:
56
instance
MockWebServiceServer.createServer(WebServiceTemplate),
MockWebServiceServer
by
MockWebServiceServer.createServer(WebServiceGatewaySupport),
calling
or
MockWebServiceServer.createServer(ApplicationContext).
Note
Note that the MockWebServiceServer (and related classes) offers a 'fluent' API, so you
can typically use the Code Completion features (i.e. ctrl-space) in your IDE to guide you
through the process of setting up the mock server.
Note
Also note that you rely on the standard logging features available in Spring Web Services
in your unit tests. Sometimes it might be useful to inspect the request or response message
57
CustomerCountResponse response =
(CustomerCountResponse) getWebServiceTemplate().marshalSendAndReceive(request);
return response.getCustomerCount();
}
}
javax.xml.transform.Source;
org.springframework.beans.factory.annotation.Autowired;
org.springframework.test.context.ContextConfiguration;
org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
org.springframework.xml.transform.StringSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import org.springframework.ws.test.client.MockWebServiceServer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("integration-test.xml")
public class CustomerClientIntegrationTest {
@Autowired
private CustomerClient client;
@Before
public void createServer() throws Exception {
mockServer = MockWebServiceServer.createServer(client);
}
@Test
58
assertEquals(10, result);
mockServer.verify();
}
}
This part of the test might look a bit confusing, but the Code Completion features of your IDE are
of great help. After typing expect(, simply type ctrl-space, and your IDE will provide you with a
list of possible request matching strategies, provided you statically imported RequestMatchers.
The same applies to andRespond(, provided you statically imported ResponseCreators.
We call getCustomerCount() on the CustomerClient, thus using the WebServiceTemplate. The
template has been set up for 'testing mode' by now, so no real (HTTP) connection is made by this
method call. We also make some JUnit assertions based on the result of the method call.
We call verify() on the MockWebServiceServer, thus verifying that the expected message was
actually received.
59
You can write your own implementations of this interface, throwing AssertionErrors when the
message does not meet your expectations, but you certainly do not have to. The RequestMatchers class
provides standard RequestMatcher implementations for you to use in your tests. You will typically
statically import this class.
The RequestMatchers class provides the following request matchers:
RequestMatchers
method
Description
anything()
payload()
validPayload()
xpath()
soapHeader()
connectionTo()
You can set up multiple request expectations by chaining andExpect() calls, like so:
mockServer.expect(connectionTo("http://example.com")).
andExpect(payload(expectedRequestPayload)).
andExpect(validPayload(schemaResource)).
andRespond(...);
For more information on the request matchers provided by RequestMatchers, refer to the class level
Javadoc.
Once again you can write your own implementations of this interface, creating a response message by
using the message factory, but you certainly do not have to, as the ResponseCreators class provides
standard ResponseCreator implementations for you to use in your tests. You will typically statically
import this class.
60
method
Description
withPayload()
withError()
withException()
withMustUnderstandFault(),
withClientOrSenderFault(),
withServerOrReceiverFault(),
withVersionMismatchFault()
For more information on the request matchers provided by RequestMatchers, refer to the class level
Javadoc.
61
of
these
three
Note
Note that WS-Security (especially encryption and signing) requires substantial amounts
of memory, and will also decrease performance. If performance is important to you, you
might want to consider not using WS-Security, or simply use HTTP-based security.
7.2.
XwsSecurityInterceptor
The XwsSecurityInterceptor is an EndpointInterceptor (see Section 5.5.2, Intercepting requests the EndpointInterceptor interface) that is based on SUN's XML and Web Services Security package
(XWSS). This WS-Security implementation is part of the Java Web Services Developer Pack (Java
WSDP [http://java.sun.com/webservices/]).
Like any other endpoint interceptor, it is defined in the endpoint mapping (see Section 5.5, Endpoint
mappings). This means that you can be selective about adding WS-Security support: some endpoint
mappings require it, while others do not.
Note
Note that XWSS requires both a SUN 1.5 JDK and the SUN SAAJ reference
implementation. The WSS4J interceptor does not have these requirements (see
Section 7.3, Wss4jSecurityInterceptor ).
The XwsSecurityInterceptor requires a security policy file to operate. This XML file tells the
interceptor what security aspects to require from incoming SOAP messages, and what aspects to add
62
<beans>
<bean id="wsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="classpath:securityPolicy.xml"/>
<property name="callbackHandlers">
<list>
<ref bean="certificateHandler"/>
<ref bean="authenticationHandler"/>
</list>
</property>
</bean>
...
</beans>
This interceptor is configured using the securityPolicy.xml file on the classpath. It uses two callback
handlers which are defined further on in the file.
7.2.1. Keystores
For most cryptographic operations, you will use the standard java.security.KeyStore objects. These
operations include certificate verification, message signing, signature verification, and encryption,
but excludes username and time-stamp verification. This section aims to give you some background
knowledge on keystores, and the Java tools that you can use to store keys and certificates in a keystore
file. This information is mostly not related to Spring-WS, but to the general cryptographic features
of Java.
The java.security.KeyStore class represents a storage facility for cryptographic keys and
certificates. It can contain three different sort of elements:
Private Keys.
These keys are used for self-authentication. The private key is accompanied by
certificate chain for the corresponding public key. Within the field of WS-Security, this accounts to
message signing and message decryption.
Symmetric Keys.
Symmetric (or secret) keys are used for message encryption and decryption as
well. The difference being that both sides (sender and recipient) share the same, secret key.
Trusted certificates.
These X509 certificates are called a trusted certificate because the keystore
owner trusts that the public key in the certificates indeed belong to the owner of the certificate.
63
Caution
If you don't specify the location property, a new, empty keystore will be created, which
is most likely not what you want.
7.2.1.3. KeyStoreCallbackHandler
To use the keystores within a XwsSecurityInterceptor, you will need to define
a KeyStoreCallbackHandler. This callback has three properties with type keystore:
(keyStore,trustStore, and symmetricStore). The exact stores used by the handler depend on the
cryptographic operations that are to be performed by this handler. For private key operation, the
keyStore is used, for symmetric key operations the symmetricStore, and for determining trust
relationships, the trustStore. The following table indicates this:
Cryptographic operation
Keystore used
Certificate validation
keyStore
symmetricStore
trustStore
symmetricStore
Signing
keyStore
Signature verification
trustStore
64
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallb
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
If you want to use it to decrypt incoming certificates or sign outgoing messages, you would use a key
store, like so:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallb
<property name="keyStore" ref="keyStore"/>
<property name="privateKeyPassword" value="changeit"/>
</bean>
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
The following sections will indicate where the KeyStoreCallbackHandler can be used, and which
properties to set for particular cryptographic operations.
7.2.2. Authentication
As stated in the introduction, authentication is the task of determining whether a principal is who they
claim to be. Within WS-Security, authentication can take two forms: using a username and password
token (using either a plain text password or a password digest), or using a X509 certificate.
7.2.2.1. Plain Text Username Authentication
The simplest form of username authentication usesplain text passwords. In this scenario, the SOAP
message will contain a UsernameToken element, which itself contains a Username element and a
Password element which contains the plain text password. Plain text authentication can be compared
to the Basic Authentication provided by HTTP servers.
Warning
Note that plain text passwords are not very secure. Therefore, you should always add
additional security measures to your transport layer if you are using them (using HTTPS
instead of plain HTTP, for instance).
To require that every incoming message contains a UsernameToken with a plain text
password, the security policy file should contain a RequireUsernameToken element, with the
65
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireUsernameToken passwordDigestRequired="false" nonceRequired="false"/>
...
</xwss:SecurityConfiguration>
If the username token is not present, the XwsSecurityInterceptor will return a SOAP Fault to the
sender. If it is present, it will fire a PasswordValidationCallback with a PlainTextPasswordRequest
to the registered handlers. Within Spring-WS, there are three classes which handle this particular
callback.
7.2.2.1.1. SimplePasswordValidationCallbackHandler
The simplest password validation handler is the SimplePasswordValidationCallbackHandler. This
handler validates passwords against an in-memory Properties object, which you can specify using
the users property, like so:
<bean id="passwordValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.SimplePasswordValidationCallbackHandler"
<property name="users">
<props>
<prop key="Bert">Ernie</prop>
</props>
</property>
</bean>
In this case, we are only allowing the user "Bert" to log in using the password "Ernie".
7.2.2.1.2. SpringPlainTextPasswordValidationCallbackHandler
The SpringPlainTextPasswordValidationCallbackHandler uses Spring Security [http://
www.springframework.org/security] to authenticate users. It is beyond the scope of this document to
describe Spring Security, but suffice it to say that it is a full-fledged security framework. You can
read more about it in the Spring Security reference documentation [http://www.springframework.org/
security].
The SpringPlainTextPasswordValidationCallbackHandler requires an AuthenticationManager to
operate. It uses this manager to authenticate against a UsernamePasswordAuthenticationToken that
it creates. If authentication is successful, the token is stored in the SecurityContextHolder. You can
set the authentication manager using the authenticationManagerproperty:
<beans>
<bean id="springSecurityHandler"
class="org.springframework.ws.soap.security.xwss.callback.SpringPlainTextPasswordValidationCallb
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<bean class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
66
7.2.2.1.3. JaasPlainTextPasswordValidationCallbackHandler
The JaasPlainTextPasswordValidationCallbackHandler is based on the standard
Java
Authentication and Authorization Service [http://java.sun.com/products/jaas/] . It is beyond the scope
of this document to provide a full introduction into JAAS, but there is a good tutorial [http://
www.javaworld.com/javaworld/jw-09-2002/jw-0913-jaas.html] available.
The JaasPlainTextPasswordValidationCallbackHandler requires only a loginContextName to
operate. It creates a new JAAS LoginContext using this name, and handles the standard JAAS
NameCallback and PasswordCallback using the username and password provided in the SOAP
message. This means that this callback handler integrates with any JAAS LoginModule that fires these
callbacks during the login() phase, which is standard behavior.
You can wire up a JaasPlainTextPasswordValidationCallbackHandler as follows:
<bean id="jaasValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.jaas.JaasPlainTextPasswordValidationCall
<property name="loginContextName" value="MyLoginModule" />
</bean>
In this case, the callback handler uses the LoginContext named "MyLoginModule". This module
should be defined in your jaas.config file, as explained in the abovementioned tutorial.
7.2.2.2. Digest Username Authentication
When using password digests, the SOAP message also contains a UsernameToken element, which itself
contains a Username element and a Password element. The difference is that the password is not sent
as plain text, but as a digest. The recipient compares this digest to the digest he calculated from the
known password of the user, and if they are the same, the user is authenticated. It can be compared to
the Digest Authentication provided by HTTP servers.
To require that every incoming message contains a UsernameToken element with a password
digest, the security policy file should contain a RequireUsernameToken element, with the
passwordDigestRequired attribute set totrue. Additionally, the nonceRequired should be set totrue:
You can find a reference of possible child elements here [http://java.sun.com/webservices/docs/1.6/
tutorial/doc/XWS-SecurityIntro4.html#wp567459] .
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireUsernameToken passwordDigestRequired="true" nonceRequired="true"/>
...
</xwss:SecurityConfiguration>
If the username token is not present, the XwsSecurityInterceptor will return a SOAP Fault to the
sender. If it is present, it will fire a PasswordValidationCallback with a DigestPasswordRequest to
the registered handlers. Within Spring-WS, there are two classes which handle this particular callback.
67
7.2.2.2.1. SimplePasswordValidationCallbackHandler
The SimplePasswordValidationCallbackHandler can handle both plain text passwords as well as
password digests. It is described inSection 7.2.2.1.1, SimplePasswordValidationCallbackHandler.
7.2.2.2.2. SpringDigestPasswordValidationCallbackHandler
The
<beans>
<bean class="org.springframework.ws.soap.security.xwss.callback.SpringDigestPasswordValidationCall
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireSignature requireTimestamp="false">
...
</xwss:SecurityConfiguration>
When a message arrives that carries no certificate, the XwsSecurityInterceptor will return a SOAP
Fault to the sender. If it is present, it will fire a CertificateValidationCallback. There are three
handlers within Spring-WS which handle this callback for authentication purposes.
Note
In most cases, certificate authentication should be preceded by certificate validation,
since you only want to authenticate against valid certificates. Invalid certificates such as
certificates for which the expiration date has passed, or which are not in your store of
trusted certificates, should be ignored.
68
Spring-WS
terms,
this
means
that
the
SpringCertificateValidationCallbackHandler
or
JaasCertificateValidationCallbackHandler
should
be
preceded
by
KeyStoreCallbackHandler. This can be accomplished by setting the order of the
callbackHandlers property in the configuration of the XwsSecurityInterceptor:
<bean id="wsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="classpath:securityPolicy.xml"/>
<property name="callbackHandlers">
<list>
<ref bean="keyStoreHandler"/>
<ref bean="springSecurityHandler"/>
</list>
</property>
</bean>
Using this setup, the interceptor will first determine if the certificate in the message is
valid using the keystore, and then authenticate against it.
7.2.2.3.1. KeyStoreCallbackHandler
The KeyStoreCallbackHandler uses a standard Java keystore to validate certificates. This certificate
validation process consists of the following steps:
1. First, the handler will check whether the certificate is in the private keyStore. If it is, it is valid.
2. If the certificate is not in the private keystore, the handler will check whether the current date and
time are within the validity period given in the certificate. If they are not, the certificate is invalid;
if it is, it will continue with the final step.
3. Finally, a certification path for the certificate is created. This basically means that the handler
will determine whether the certificate has been issued by any of the certificate authorities in
thetrustStore. If a certification path can be built successfully, the certificate is valid. Otherwise,
the certificate is not.
To use the KeyStoreCallbackHandler for certificate validation purposes, you will most likely set only
the trustStore property:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallb
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
Using this setup, the certificate that is to be validated must either be in the trust store itself, or the trust
store must contain a certificate authority that issued the certificate.
69
7.2.2.3.2. SpringCertificateValidationCallbackHandler
The
requires
an
Spring
Security
AuthenticationManager to operate. It uses this manager to authenticate against a
X509AuthenticationToken that it creates. The configured authentication manager is expected to
supply a provider which can handle this token (usually an instance of X509AuthenticationProvider).
If authentication is succesful, the token is stored in the SecurityContextHolder. You can set the
authentication manager using the authenticationManager property:
SpringCertificateValidationCallbackHandler
<beans>
<bean id="springSecurityCertificateHandler"
class="org.springframework.ws.soap.security.xwss.callback.SpringCertificateValidationCallbackH
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="authenticationManager"
class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<bean class="org.springframework.ws.soap.security.x509.X509AuthenticationProvider">
<property name="x509AuthoritiesPopulator">
<bean class="org.springframework.ws.soap.security.x509.populator.DaoX509Authoritie
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
In this case, we are using a custom user details service to obtain authentication details based on the
certificate. Refer to the Spring Security reference documentation [http://www.springframework.org/
security] for more information about authentication against X509 certificates.
7.2.2.3.3. JaasCertificateValidationCallbackHandler
The JaasCertificateValidationCallbackHandler requires a loginContextName to operate. It
creates a new JAAS LoginContext using this name and with the X500Principal of the certificate. This
means that this callback handler integrates with any JAAS LoginModule that handles X500 principals.
You can wire up a JaasCertificateValidationCallbackHandler as follows:
<bean id="jaasValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.jaas.JaasCertificateValidationCallbackHa
<property name="loginContextName">MyLoginModule</property>
</bean>
In this case, the callback handler uses the LoginContext named "MyLoginModule". This module
should be defined in your jaas.config file, and should be able to authenticate against X500 principals.
70
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:RequireSignature requireTimestamp="false"/>
</xwss:SecurityConfiguration>
If the signature is not present, the XwsSecurityInterceptor will return a SOAP Fault to the sender. If it
is present, it will fire a SignatureVerificationKeyCallback to the registered handlers. Within SpringWS, there are is one class which handles this particular callback: the KeyStoreCallbackHandler.
7.2.3.1.1. KeyStoreCallbackHandler
As described inSection 7.2.1.3, KeyStoreCallbackHandler, the KeyStoreCallbackHandler uses
a java.security.KeyStore for handling various cryptographic callbacks, including signature
verification. For signature verification, the handler uses the trustStore property:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallb
<property name="trustStore" ref="trustStore"/>
</bean>
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Sign includeTimestamp="false" />
</xwss:SecurityConfiguration>
71
7.2.3.2.1. KeyStoreCallbackHandler
As described inSection 7.2.1.3, KeyStoreCallbackHandler, the KeyStoreCallbackHandler uses a
java.security.KeyStore for handling various cryptographic callbacks, including signing messages.
For adding signatures, the handler uses the keyStore property. Additionally, you must set the
privateKeyPassword property to unlock the private key used for signing.
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallb
<property name="keyStore" ref="keyStore"/>
<property name="privateKeyPassword" value="changeit"/>
</bean>
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:RequireEncryption />
</xwss:SecurityConfiguration>
If an incoming message is not encrypted, the XwsSecurityInterceptor will return a SOAP Fault to
the sender. If it is present, it will fire a DecryptionKeyCallback to the registered handlers. Within
Spring-WS, there is one class which handled this particular callback: theKeyStoreCallbackHandler.
7.2.4.1.1. KeyStoreCallbackHandler
As described inSection 7.2.1.3, KeyStoreCallbackHandler, the KeyStoreCallbackHandler uses
a java.security.KeyStore for handling various cryptographic callbacks, including decryption.
For decryption, the handler uses the keyStore property. Additionally, you must set the
privateKeyPassword property to unlock the private key used for decryption. For decryption based on
symmetric keys, it will use the symmetricStore.
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallb
72
7.2.4.2. Encryption
To encrypt outgoing SOAP messages, the security policy file should contain a Encrypt element. This
element can further carry a EncryptionTarget element which indicates which part of the message
should be encrypted, and a SymmetricKey to indicate that a shared secret instead of the regular public
key should be used to encrypt the message. You can read a description of the other elements here
[http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565951] .
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Encrypt />
</xwss:SecurityConfiguration>
7.2.4.2.1. KeyStoreCallbackHandler
As described inSection 7.2.1.3, KeyStoreCallbackHandler, the KeyStoreCallbackHandler uses a
java.security.KeyStore for handling various cryptographic callbacks, including encryption. For
encryption based on public keys, the handler uses the trustStore property. For encryption based on
symmetric keys, it will use thesymmetricStore.
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallb
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
Similarly,
are
handled
in
the
handleValidationException method of the XwsSecurityInterceptor. By default, this method will
create a SOAP 1.1 Client or SOAP 1.2 Sender Fault, and send that back as a response.
WsSecurityValidationException
exceptions
73
Note
Both handleSecurementException and handleValidationException are protected
methods, which you can override to change their default behavior.
7.3.
Wss4jSecurityInterceptor
The Wss4jSecurityInterceptor is an EndpointInterceptor (seeSection 5.5.2, Intercepting
requests - the EndpointInterceptor interface) that is based on Apache's WSS4J [http://
ws.apache.org/wss4j/].
WSS4J implements the following standards:
OASIS Web Serives Security: SOAP Message Security 1.0 Standard 200401, March 2004
Username Token profile V1.0
X.509 Token Profile V1.0
This inteceptor supports messages created by the AxiomSoapMessageFactory and the
SaajSoapMessageFactory.
Description
UsernameToken
Timestamp
Encrypt
Signature
NoSecurity
No action performed
Description
UsernameToken
74
Description
UsernameTokenSignature
Timestamp
Adds a timestamp
Encrypt
Signature
NoSecurity
No action performed
The order of the actions is significant and is enforced by the interceptor. The interceptor will reject
an incoming SOAP message if its security actions were performed in a different order than the one
specified byvalidationActions.
WSCryptoFactoryBean.
7.3.2.1. CryptoFactoryBean
Spring-WS provides a convenient factory bean, CryptoFactoryBean that constructs and configures
Crypto instances via strong-typed properties (prefered) or through a Properties object.
By
default,
returns
instances
of
org.apache.ws.security.components.crypto.Merlin. This can be changed by setting the
cryptoProvider property (or its equivalent org.apache.ws.security.crypto.provider string
property).
CryptoFactoryBean
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="mypassword"/>
<property name="keyStoreLocation" value="file:/path_to_keystore/keystore.jks"/>
</bean>
7.3.3. Authentication
7.3.3.1. Validating Username Token
Spring-WS provides a set of callback handlers to integrate with Spring Security. Additionally, a simple
callback handler SimplePasswordValidationCallbackHandler is provided to configure users and
passwords with an in-memory Properties object.
Callback handlers are configured via Wss4jSecurityInterceptor's validationCallbackHandler
property.
75
7.3.3.1.1. SimplePasswordValidationCallbackHandler
SimplePasswordValidationCallbackHandler validates plain text and digest username tokens against
<bean id="callbackHandler"
class="org.springframework.ws.soap.security.wss4j.callback.SimplePasswordValidationCallbackHandler
<property name="users">
<props>
<prop key="Bert">Ernie</prop>
</props>
</property>
</bean>
7.3.3.1.2. SpringPlainTextPasswordValidationCallbackHandler
The
AuthenticationManager
to
operate.
<beans>
<bean id="springSecurityHandler"
class="org.springframework.ws.soap.security.wss4j.callback.SpringPlainTextPasswordValidationCall
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<bean class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</property>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
7.3.3.1.3. SpringDigestPasswordValidationCallbackHandler
The
<beans>
<bean class="org.springframework.ws.soap.security.wss4j.callback.SpringDigestPasswordValidationCal
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
76
If plain text password type is chosen, it is possible to instruct the interceptor to add Nonce and/or
Created elements using the securementUsernameTokenElements property. The value must be a list
containing the desired elements' names separated by spaces (case sensitive).
The next example generates a username token with a plain text password, a Nonce and a Created
element:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="UsernameToken"/>
<property name="securementUsername" value="Ernie"/>
<property name="securementPassword" value="Bert"/>
<property name="securementPasswordType" value="PasswordText"/>
<property name="securementUsernameTokenElements" value="Nonce Created"/>
</bean>
77
At the end of the validation, the interceptor will automatically verify the validity of the certificate by
delegating to the default WSS4J implementation. If needed, this behavior can be changed by redefining
the verifyCertificateTrust method.
For more details, please refer toSection 7.3.5, Digital Signatures.
The interceptor will always reject already expired timestamps whatever the value of timeToLive is.
78
The WS Security specifications define several formats to transfer the signature tokens (certificates)
or references to these tokens. Thus, the plain element name Token signs the token and takes
care of the different formats. To sign the SOAP body and the signature token the value of
securementSignatureParts must contain:
<property name="securementSignatureParts">
<value>
{}{http://schemas.xmlsoap.org/soap/envelope/}Body;
Token
</value>
</property>
The first empty brackets are used for encryption parts only.
79
To support decryption of messages with an embedded key name ( ds:KeyName element), configure a
KeyStoreCallbackHandler that points to the keystore with the symmetric secret key. The property
3
This is because WSS4J needs only a Crypto for encypted keys, whereas embedded key name validation is delegated to a callback handler.
80
7.3.6.2. Encryption
Adding Encrypt to the securementActions enables encryption of outgoing messages. The certifacte's
alias to use for the encryption is set via the securementEncryptionUser property. The keystore where
the certificate reside is accessed using the securementEncryptionCrypto property. As encryption relies
on public certificates, no password needs to be passed.
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Encrypt"/>
<property name="securementEncryptionUser" value="mycert"/>
<property name="securementEncryptionCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="file:/keystore.jks"/>
</bean>
</property>
</bean>
Encryption can be customized in several ways: The key identifier type to use is defined
bysecurementEncryptionKeyIdentifier. Possible values areIssuerSerial,X509KeyIdentifier,
DirectReference,Thumbprint, SKIKeyIdentifier orEmbeddedKeyName.
If the EmbeddedKeyName type is chosen, you need to specify the secret key to use for the encryption.
The alias of the key is set via the securementEncryptionUser property just as for the other
key identifier types. However, WSS4J requires a callback handler to fetch the secret key. Thus,
securementCallbackHandler must be provided with a KeyStoreCallbackHandler pointing to the
appropriate keystore. By default, the ds:KeyName element in the resulting WS-Security header
takes the value of the securementEncryptionUser property. To indicate a different name, set the
securementEncryptionEmbeddedKeyName with the desired value. In the next example, the outgoing
message will be encrypted with a key aliased secretKey whereas myKey will appear in ds:KeyName
element:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Encrypt"/>
<property name="securementEncryptionKeyIdentifier" value="EmbeddedKeyName"/>
<property name="securementEncryptionUser" value="secretKey"/>
<property name="securementEncryptionEmbeddedKeyName" value="myKey"/>
<property name="securementCallbackHandler">
<bean class="org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler">
<property name="symmetricKeyPassword" value="keypass"/>
<property name="keyStore">
81
Be aware that the element name, the namespace identifier, and the encryption modifier are case
sensitive. The encryption modifier and the namespace identifier can be omitted. In this case the
encryption mode defaults to Content and the namespace is set to the SOAP namespace.
To specify an element without a namespace use the value Null as the namespace name (case sensitive).
If no list is specified, the handler encrypts the SOAP Body in Content mode by default.
Please refer to the W3C XML Encryption specification about the differences between Element and Content encryption.
82
83
Bibliography
[waldo-94] Jim Waldo, Ann Wollrath, and Sam Kendall. A Note on Distributed Computing. Springer Verlag.
1994.
[alpine] Steve Loughran and Edmund Smith. Rethinking the Java SOAP Stack. May 17, 2005. Copyright
2005 IEEE Telephone Laboratories, Inc..
[effective-enterprise-java] Ted Neward. Scott Meyers. Effective Enterprise Java. Addison-Wesley. 2004.
[effective-xml] Elliotte Rusty Harold. Scott Meyers. Effective XML. Addison-Wesley. 2004.
84