diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc index 12dc5395..49d04a8d 100644 --- a/CONTRIBUTING.adoc +++ b/CONTRIBUTING.adoc @@ -1,49 +1,43 @@ = Contributing to Spring Web Services -Spring Web Services is released under the Apache 2.0 license. If you would like to contribute -something, or simply want to hack on the code this document should help you get started. +Spring Web Services is released under the Apache 2.0 license. +If you would like to contribute something, or simply want to hack on the code this document should help you get started. == Code of Conduct -This project adheres to the Contributor Covenant link:CODE_OF_CONDUCT.adoc[code of -conduct]. By participating, you are expected to uphold this code. Please report -unacceptable behavior to spring-code-of-conduct@pivotal.io. -== Using Github issues -We use Github issues to track bugs and enhancements. If you have a general usage question -please ask on https://stackoverflow.com[Stack Overflow]. The Spring Web Services team and the -broader community monitor the https://stackoverflow.com/tags/spring-ws[`spring-ws`] -tag. +This project adheres to the Contributor Covenant https://github.com/spring-projects/spring-ws?tab=coc-ov-file#contributor-code-of-conduct[code of conduct]. +By participating, you are expected to uphold this code. Please report unacceptable behavior to code-of-conduct@spring.io. -If you are reporting a bug, please help to speed up problem diagnosis by providing as much -information as possible. Submitting a github-hosted sample project replicating the problem helps. +== Using GitHub issues + +We use GitHub issues to track bugs and enhancements. +If you have a general usage question please ask on https://stackoverflow.com[Stack Overflow]. +The Spring Web Services team and the broader community monitor the https://stackoverflow.com/tags/spring-ws[`spring-ws`] tag. + +If you are reporting a bug, please help to speed up problem diagnosis by providing as much information as possible. +Submitting a github-hosted sample project replicating the problem helps. == Include a Signed Off By Trailer -All commits must include a __Signed-off-by__ trailer at the end of each commit message to -indicate that the contributor agrees to the Developer Certificate of Origin. -For additional details, please refer to the blog post -https://spring.io/blog/2025/01/06/hello-dco-goodbye-cla-simplifying-contributions-to-spring[Hello -DCO, Goodbye CLA: Simplifying Contributions to Spring]. +All commits must include a __Signed-off-by__ trailer at the end of each commit message to indicate that the contributor agrees to the Developer Certificate of Origin. +For additional details, please refer to the blog post https://spring.io/blog/2025/01/06/hello-dco-goodbye-cla-simplifying-contributions-to-spring[Hello DCO, Goodbye CLA: Simplifying Contributions to Spring]. == Code Conventions and Housekeeping -None of these are essential for a pull request, but they help. They can also be -added after the original pull request but before a merge. + +None of these are essential for a pull request, but they help. +They can also be added after the original pull request but before a merge. * Use the Spring Framework code format conventions. -* Make sure all new `.java` files to have a simple Javadoc class comment with at least an - `@author` tag identifying you, and preferably at least a paragraph on what the class is - for. -* Add the ASF license header comment to all new `.java` files (copy from existing files - in the project) -* Add yourself as an `@author` to the `.java` files that you modify substantially (more - than cosmetic changes). +* Make sure all new `.java` files to have a simple Javadoc class comment with at least an `@author` tag identifying you, and preferably at least a paragraph on what the class is for. +* Add the ASF license header comment to all new `.java` files (copy from existing files in the project) +* Add yourself as an `@author` to the `.java` files that you modify substantially (more than cosmetic changes). * Add some Javadocs. * A few unit tests would help a lot as well -- someone has to do it. -* If no-one else is using your branch, please rebase it against the current main (or - other target branch in the main project). +* If no-one else is using your branch, please rebase it against the current main (or other target branch in the main project). * When writing a commit message please follow http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions]. === Building from source + This project includes the Gradle wrapper, meaning you don't have to install any CLI tools to compile. Once you've cloned the project, it can be built from the root directory using the following command: diff --git a/spring-ws-docs/src/docs/asciidoc/client.adoc b/spring-ws-docs/src/docs/asciidoc/client.adoc index c652eb8a..f69cd943 100644 --- a/spring-ws-docs/src/docs/asciidoc/client.adoc +++ b/spring-ws-docs/src/docs/asciidoc/client.adoc @@ -1,9 +1,14 @@ [[client]] = Using Spring-WS on the Client -Spring-WS provides a client-side Web service API that allows for consistent, XML-driven access to web services. It also caters to the use of marshallers and unmarshallers so that your service-tier code can deal exclusively with Java objects. +Spring-WS provides a client-side Web service API that allows for consistent, XML-driven access to web services. +It also caters to the use of marshallers and unmarshallers so that your service-tier code can deal exclusively with Java objects. -The `org.springframework.ws.client.core` package provides the core functionality for using the client-side access API. It contains template classes that simplify the use of Web services, much like the core Spring `JdbcTemplate` does for JDBC. The design principle common to Spring template classes is to provide helper methods to perform common operations and, for more sophisticated usage, delegate to user implemented callback interfaces. The web service template follows the same design. The classes offer various convenience methods for +The `org.springframework.ws.client.core` package provides the core functionality for using the client-side access API. +It contains template classes that simplify the use of Web services, much like the core Spring `JdbcTemplate` does for JDBC. +The design principle common to Spring template classes is to provide helper methods to perform common operations and, for more sophisticated usage, delegate to user implemented callback interfaces. +The web service template follows the same design. +The classes offer various convenience methods for * Sending and receiving of XML messages. * Marshalling objects to XML before sending. @@ -11,21 +16,30 @@ The `org.springframework.ws.client.core` package provides the core functionality == Using the Client-side API -This section describs how to use the client-side API. For how to use the server-side API, see <>. +This section describes how to use the client-side API. +For how to use the server-side API, see <>. [[client-web-service-template]] === `WebServiceTemplate` -The {spring-ws-api}/client/core/WebServiceTemplate.html[`WebServiceTemplate`] is the core class for client-side web service access in Spring-WS. It contains methods for sending `Source` objects and receiving response messages as either `Source` or `Result`. Additionally, it can marshal objects to XML before sending them across a transport and unmarshal any response XML into an object again. +The {spring-ws-api}/client/core/WebServiceTemplate.html[`WebServiceTemplate`] is the core class for client-side web service access in Spring-WS. +It contains methods for sending `Source` objects and receiving response messages as either `Source` or `Result`. +Additionally, it can marshal objects to XML before sending them across a transport and unmarshal any response XML into an object again. [[client-transports]] ==== URIs and Transports -The `WebServiceTemplate` class uses a URI as the message destination. You can either set a `defaultUri` property on the template itself or explicitly supply a URI when calling a method on the template. The URI is resolved into a `WebServiceMessageSender`, which is responsible for sending the XML message across a transport layer. You can set one or more message senders by using the `messageSender` or `messageSenders` properties of the `WebServiceTemplate` class. +The `WebServiceTemplate` class uses a URI as the message destination. +You can either set a `defaultUri` property on the template itself or explicitly supply a URI when calling a method on the template. +The URI is resolved into a `WebServiceMessageSender`, which is responsible for sending the XML message across a transport layer. +You can set one or more message senders by using the `messageSender` or `messageSenders` properties of the `WebServiceTemplate` class. ===== HTTP transports -There are three implementations of the `WebServiceMessageSender` interface for sending messages over HTTP. The default implementation is the `HttpUrlConnectionMessageSender`, which uses the facilities provided by Java itself. The alternatives are either `JdkHttpClientMessageSender` that uses the JDK's `HttpClient`, or `HttpComponents5MessageSender`, which uses the https://hc.apache.org/httpcomponents-client-ga[Apache HttpClient]. Use the latter if you need more advanced and easy-to-use functionality (such as authentication, HTTP connection pooling, and so forth). +There are three implementations of the `WebServiceMessageSender` interface for sending messages over HTTP. +The default implementation is the `HttpUrlConnectionMessageSender`, which uses the facilities provided by Java itself. +The alternatives are either `JdkHttpClientMessageSender` that uses the JDK's `HttpClient`, or `HttpComponents5MessageSender`, which uses the https://hc.apache.org/httpcomponents-client-ga[Apache HttpClient]. +Use the latter if you need more advanced and easy-to-use functionality (such as authentication, HTTP connection pooling, and so forth). To use the HTTP transport, either set the `defaultUri` to something like `http://example.com/services` or supply the `uri` parameter for one of the methods. @@ -71,11 +85,15 @@ The following example shows how to override the default configuration and how to ===== JMS transport -For sending messages over JMS, Spring-WS provides `JmsMessageSender`. This class uses the facilities of the Spring framework to transform the `WebServiceMessage` into a JMS `Message`, send it on its way on a `Queue` or `Topic`, and receive a response (if any). +For sending messages over JMS, Spring-WS provides `JmsMessageSender`. +This class uses the facilities of the Spring framework to transform the `WebServiceMessage` into a JMS `Message`, send it on its way on a `Queue` or `Topic`, and receive a response (if any). -To use `JmsMessageSender`, you need to set the `defaultUri` or `uri` parameter to a JMS URI, which -- at a minimum -- consists of the `jms:` prefix and a destination name. Some examples of JMS URIs are: `jms:SomeQueue`, `jms:SomeTopic?priority=3&deliveryMode=NON_PERSISTENT`, and `jms:RequestQueue?replyToName=ResponseName`. For more information on this URI syntax, see the {spring-ws-api}/transport/jms/JmsMessageSender.html[Javadoc for `JmsMessageSender`]. +To use `JmsMessageSender`, you need to set the `defaultUri` or `uri` parameter to a JMS URI, which -- at a minimum -- consists of the `jms:` prefix and a destination name. +Some examples of JMS URIs are: `jms:SomeQueue`, `jms:SomeTopic?priority=3&deliveryMode=NON_PERSISTENT`, and `jms:RequestQueue?replyToName=ResponseName`. +For more information on this URI syntax, see the {spring-ws-api}/transport/jms/JmsMessageSender.html[Javadoc for `JmsMessageSender`]. -By default, the `JmsMessageSender` sends JMS `BytesMessage`, but you can override this to use `TextMessages` by using the `messageType` parameter on the JMS URI -- for example, `jms:Queue?messageType=TEXT_MESSAGE`. Note that `BytesMessages` are the preferred type, because `TextMessages` do not support attachments and character encodings reliably. +By default, the `JmsMessageSender` sends JMS `BytesMessage`, but you can override this to use `TextMessages` by using the `messageType` parameter on the JMS URI -- for example, `jms:Queue?messageType=TEXT_MESSAGE`. +Note that `BytesMessages` are the preferred type, because `TextMessages` do not support attachments and character encodings reliably. The following example shows how to use the JMS transport in combination with an Artemis connection factory: @@ -106,9 +124,13 @@ The following example shows how to use the JMS transport in combination with an ===== Email Transport -Spring-WS also provides an email transport, which you can use to send web service messages over SMTP and retrieve them over either POP3 or IMAP. The client-side email functionality is contained in {spring-ws-api}/transport/mail/MailMessageSender.html[`MailMessageSender`]. This class creates an email message from the request `WebServiceMessage` and sends it over SMTP. It then waits for a response message to arrive at the incoming POP3 or IMAP server. +Spring-WS also provides an email transport, which you can use to send web service messages over SMTP and retrieve them over either POP3 or IMAP. +The client-side email functionality is contained in {spring-ws-api}/transport/mail/MailMessageSender.html[`MailMessageSender`]. +This class creates an email message from the request `WebServiceMessage` and sends it over SMTP. +It then waits for a response message to arrive at the incoming POP3 or IMAP server. -To use the `MailMessageSender`, set the `defaultUri` or `uri` parameter to a `mailto` URI -- for example, `mailto:john@example.com` or `mailto:server@localhost?subject=SOAP%20Test`. Make sure that the message sender is properly configured with a `transportUri`, which indicates the server to use for sending requests (typically a SMTP server), and a `storeUri`, which indicates the server to poll for responses (typically a POP3 or IMAP server). +To use the `MailMessageSender`, set the `defaultUri` or `uri` parameter to a `mailto` URI -- for example, `mailto:john@example.com` or `mailto:server@localhost?subject=SOAP%20Test`. +Make sure that the message sender is properly configured with a `transportUri`, which indicates the server to use for sending requests (typically a SMTP server), and a `storeUri`, which indicates the server to poll for responses (typically a POP3 or IMAP server). The following example shows how to use the email transport: @@ -137,9 +159,13 @@ The following example shows how to use the email transport: ===== XMPP Transport -Spring-WS also provides a XMPP (Jabber) transport, which you can use to send and receive web service messages over XMPP. The client-side XMPP functionality is contained in {spring-ws-api}/transport/xmpp/XmppMessageSender.html[`XmppMessageSender`]. This class creates an XMPP message from the request `WebServiceMessage` and sends it over XMPP. It then listens for a response message to arrive. +Spring-WS also provides a XMPP (Jabber) transport, which you can use to send and receive web service messages over XMPP. +The client-side XMPP functionality is contained in {spring-ws-api}/transport/xmpp/XmppMessageSender.html[`XmppMessageSender`]. +This class creates an XMPP message from the request `WebServiceMessage` and sends it over XMPP. +It then listens for a response message to arrive. -To use the `XmppMessageSender`, set the `defaultUri` or `uri` parameter to a `xmpp` URI -- for example, `xmpp:johndoe@jabber.org`. The sender also requires an `XMPPConnection` to work, which can be conveniently created by using the `org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean`. +To use the `XmppMessageSender`, set the `defaultUri` or `uri` parameter to a `xmpp` URI -- for example, `xmpp:johndoe@jabber.org`. +The sender also requires an `XMPPConnection` to work, which can be conveniently created by using the `org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean`. The following example shows how to use the XMPP transport: @@ -172,11 +198,15 @@ The following example shows how to use the XMPP transport: ==== Message factories -In addition to a message sender, the `WebServiceTemplate` requires a web service message factory. By default, `SaajSoapMessageFactory` is used. +In addition to a message sender, the `WebServiceTemplate` requires a web service message factory. +By default, `SaajSoapMessageFactory` is used. === Sending and Receiving a `WebServiceMessage` -The `WebServiceTemplate` contains many convenience methods to send and receive web service messages. There are methods that accept and return a `Source` and those that return a `Result`. Additionally, there are methods that marshal and unmarshal objects to XML. The following example sends a simple XML message to a web service: +The `WebServiceTemplate` contains many convenience methods to send and receive web service messages. +There are methods that accept and return a `Source` and those that return a `Result`. +Additionally, there are methods that marshal and unmarshal objects to XML. +The following example sends a simple XML message to a web service: ==== [source,java,subs="verbatim,quotes"] @@ -233,17 +263,27 @@ public class WebServiceClient { ---- ==== -The preceding 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. +The preceding 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. -Note that the `WebServiceTemplate` class is thread-safe once configured (assuming that all of its dependencies are also thread-safe, which is the case for all of the dependencies that ship with Spring-WS), so multiple objects can use the same shared `WebServiceTemplate` instance. The `WebServiceTemplate` exposes a zero-argument constructor and `messageFactory` and `messageSender` bean properties that you can use to construct the instance (by using a Spring container or plain Java code). Alternatively, consider deriving from Spring-WS's `WebServiceGatewaySupport` convenience base class, which exposes bean properties to enable easy configuration. (You do not have to extend this base class. It is provided as a convenience class only.) +Note that the `WebServiceTemplate` class is thread-safe once configured (assuming that all of its dependencies are also thread-safe, which is the case for all of the dependencies that ship with Spring-WS), so multiple objects can use the same shared `WebServiceTemplate` instance. +The `WebServiceTemplate` exposes a zero-argument constructor and `messageFactory` and `messageSender` bean properties that you can use to construct the instance (by using a Spring container or plain Java code). +Alternatively, consider deriving from Spring-WS `WebServiceGatewaySupport` convenience base class, which exposes bean properties to enable easy configuration. +(You do not have to extend this base class, it is provided as a convenience class only). === Sending and Receiving POJOs -- Marshalling and Unmarshalling -To facilitate the sending of plain Java objects, the `WebServiceTemplate` has a number of `send(..)` methods that take an `Object` as an argument for a message's data content. The method `marshalSendAndReceive(..)` in the `WebServiceTemplate` class delegates the conversion of the request object to XML to a `Marshaller` and the conversion of the response XML to an object to an `Unmarshaller`. (For more information about marshalling and unmarshaller, see https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#oxm-marshaller-unmarshaller[the Spring Framework reference documentation].) By using the marshallers, your application code can focus on the business object that is being sent or received and not be concerned with the details of how it is represented as XML. To use the marshalling functionality, you have to set a marshaller and an unmarshaller with the `marshaller` and `unmarshaller` properties of the `WebServiceTemplate` class. +To facilitate the sending of plain Java objects, the `WebServiceTemplate` has a number of `send(..)` methods that take an `Object` as an argument for a message's data content. +The method `marshalSendAndReceive(..)` in the `WebServiceTemplate` class delegates the conversion of the request object to XML to a `Marshaller` and the conversion of the response XML to an object to an `Unmarshaller`. +(For more information about marshalling and unmarshaller, see https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#oxm-marshaller-unmarshaller[the Spring Framework reference documentation]). + +By using the marshallers, your application code can focus on the business object that is being sent or received and not be concerned with the details of how it is represented as XML. +To use the marshalling functionality, you have to set a marshaller and an unmarshaller with the `marshaller` and `unmarshaller` properties of the `WebServiceTemplate` class. === Using `WebServiceMessageCallback` -To accommodate setting 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 following example demonstrates how to set the SOAP action header on a message that is created by marshalling an object: +To accommodate setting 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 following example demonstrates how to set the SOAP action header on a message that is created by marshalling an object: ==== [source,java] @@ -267,7 +307,10 @@ NOTE: Note that you can also use the `org.springframework.ws.soap.client.core.So In addition to the <> support, Spring-WS also has support for this specification on the client-side. -For setting WS-Addressing headers on the client, you can use {spring-ws-api}/soap/addressing/client/ActionCallback.html[`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 defaults to the URL of the connection being made. +For setting WS-Addressing headers on the client, you can use {spring-ws-api}/soap/addressing/client/ActionCallback.html[`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 defaults to the URL of the connection being made. The following example sets the `Action` header to `http://samples/RequestOrder`: @@ -280,7 +323,9 @@ webServiceTemplate.marshalSendAndReceive(o, new ActionCallback("http://samples/R === Using `WebServiceMessageExtractor` -The `WebServiceMessageExtractor` interface is a low-level callback interface that gives you full control over the process to extract an `Object` from a received `WebServiceMessage`. The `WebServiceTemplate` invokes the `extractData(..)` method on a supplied `WebServiceMessageExtractor` while the underlying connection to the serving resource is still open. The following example shows the `WebServiceMessageExtractor` in action: +The `WebServiceMessageExtractor` interface is a low-level callback interface that gives you full control over the process to extract an `Object` from a received `WebServiceMessage`. +The `WebServiceTemplate` invokes the `extractData(..)` method on a supplied `WebServiceMessageExtractor` while the underlying connection to the serving resource is still open. +The following example shows the `WebServiceMessageExtractor` in action: ==== [source,java,subs="verbatim,quotes"] @@ -306,21 +351,29 @@ public void marshalWithSoapActionHeader(final Source s) { When it comes to testing your Web service clients (that is, classes that use the `WebServiceTemplate` to access a Web service), you have two possible approaches: -* Write unit tests, which mock away the `WebServiceTemplate` class, `WebServiceOperations` interface, or the complete client class. The advantage of this approach is that it s easy to accomplish. The disadvantage is that you are not really testing the exact content of the XML messages that are sent over the wire, especially when mocking out the entire client class. +* Write unit tests, which mock away the `WebServiceTemplate` class, `WebServiceOperations` interface, or the complete client class. +The advantage of this approach is that it s easy to accomplish. +The disadvantage is that you are not really testing the exact content of the XML messages that are sent over the wire, especially when mocking out the entire client class. * Write integrations tests, which do test the contents of the message. -The first approach can easily be accomplished with mocking frameworks, such as Mockito, EasyMock, and others. The next section focuses on writing integration tests. +The first approach can easily be accomplished with mocking frameworks, such as Mockito, EasyMock, and others. +The next section focuses on writing integration tests. === Writing Client-side Integration Tests -Spring-WS has support for creating for creating Web service client integration tests. In this context, a client is a class that uses the `WebServiceTemplate` to access a web service. +Spring-WS has support for creating for creating Web service client integration tests. +In this context, a client is a class that uses the `WebServiceTemplate` to access a web service. -The integration test support lives in the `org.springframework.ws.test.client` package. The core class in that package is the `MockWebServiceServer`. The underlying idea is that the web service template connects to this mock server and sends it a request message, which the mock server then verifies against the registered expectations. If the expectations are met, the mock server then prepares a response message, which is sent back to the template. +The integration test support lives in the `org.springframework.ws.test.client` package. +The core class in that package is the `MockWebServiceServer`. +The underlying idea is that the web service template connects to this mock server and sends it a request message, which the mock server then verifies against the registered expectations. +If the expectations are met, the mock server then prepares a response message, which is sent back to the template. The typical usage of the `MockWebServiceServer` is: . . Create a `MockWebServiceServer` instance by calling `MockWebServiceServer.createServer(WebServiceTemplate)`, `MockWebServiceServer.createServer(WebServiceGatewaySupport)`, or `MockWebServiceServer.createServer(ApplicationContext)`. -. Set up request expectations by calling `expect(RequestMatcher)`, possibly by using the default `RequestMatcher` implementations provided in `RequestMatchers` (which can be statically imported). Multiple expectations can be set up by chaining `andExpect(RequestMatcher)` calls. +. Set up request expectations by calling `expect(RequestMatcher)`, possibly by using the default `RequestMatcher` implementations provided in `RequestMatchers` (which can be statically imported). +Multiple expectations can be set up by chaining `andExpect(RequestMatcher)` calls. . Create an appropriate response message by calling `andRespond(ResponseCreator)`, possibly by using the default `ResponseCreator` implementations provided in `ResponseCreators` (which can be statically imported). . Use the `WebServiceTemplate` as normal, either directly of through client code. . Call `MockWebServiceServer.verify()` to make sure that all expectations have been met. @@ -332,7 +385,9 @@ The typical usage of the `MockWebServiceServer` is: . [NOTE] ==== -You can rely on the standard logging features available in Spring-WS 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 <> for more information. +You can rely on the standard logging features available in Spring-WS 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 <> for more information. ==== Consider, for example, the following Web service client class: @@ -356,8 +411,10 @@ public class CustomerClient extends WebServiceGatewaySupport { ---- <1> The `CustomerClient` extends `WebServiceGatewaySupport`, which provides it with a `webServiceTemplate` property. -<2> `CustomerCountRequest` is an object supported by a marshaller. For instance, it can have an `@XmlRootElement` annotation to be supported by JAXB2. -<3> The `CustomerClient` uses the `WebServiceTemplate` offered by `WebServiceGatewaySupport` to marshal the request object into a SOAP message and sends that to the web service. The response object is unmarshalled into a `CustomerCountResponse`. +<2> `CustomerCountRequest` is an object supported by a marshaller. +For instance, it can have an `@XmlRootElement` annotation to be supported by JAXB2. +<3> The `CustomerClient` uses the `WebServiceTemplate` offered by `WebServiceGatewaySupport` to marshal the request object into a SOAP message and sends that to the web service. +The response object is unmarshalled into a `CustomerCountResponse`. ==== The following example shows a typical test for `CustomerClient`: @@ -419,20 +476,26 @@ public class CustomerClientIntegrationTest { } ---- -<1> This test uses the standard testing facilities provided in the Spring Framework. This is not required but is generally the easiest way to set up the test. +<1> This test uses the standard testing facilities provided in the Spring Framework. +This is not required but is generally the easiest way to set up the test. <2> The `CustomerClient` is configured in `integration-test.xml` and wired into this test using `@Autowired`. <3> In a `@Before` method, we create a `MockWebServiceServer` by using the `createServer` factory method. <4> We define expectations by calling `expect()` with a `payload()` `RequestMatcher` provided by the statically imported `RequestMatchers` (see <>). We also set up a response by calling `andRespond()` with a `withPayload()` `ResponseCreator` provided by the statically imported `ResponseCreators` (see <>). -This part of the test might look a bit confusing, but the code-completion features of your IDE are of great help. After you type `expect(`, your IDE can 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`. -<5> 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. +This part of the test might look a bit confusing, but the code-completion features of your IDE are of great help. +After you type `expect(`, your IDE can 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`. +<5> 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. <6> We call `verify()` on the `MockWebServiceServer`, verifying that the expected message was actually received. ==== [[client-test-request-matcher]] === Using `RequestMatcher` and `RequestMatchers` -To verify whether the request message meets certain expectations, the `MockWebServiceServer` uses the `RequestMatcher` strategy interface. The contract defined by this interface is as follows: +To verify whether the request message meets certain expectations, the `MockWebServiceServer` uses the `RequestMatcher` strategy interface. +The contract defined by this interface is as follows: ==== [source,java] @@ -446,7 +509,9 @@ public interface RequestMatcher { ---- ==== -You can write your own implementations of this interface, throwing `AssertionError` exceptions 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 typically statically import this class. +You can write your own implementations of this interface, throwing `AssertionError` exceptions 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 typically statically import this class. The `RequestMatchers` class provides the following request matchers: @@ -459,7 +524,8 @@ The `RequestMatchers` class provides the following request matchers: | Expects any sort of request. | `payload()` -| Expects a given request payload. May include https://github.com/xmlunit/user-guide/wiki/Placeholders[XMLUnit Placeholders] +| Expects a given request payload. +May include https://github.com/xmlunit/user-guide/wiki/Placeholders[XMLUnit Placeholders] | `validPayload()` | Expects the request payload to validate against given XSD schemas. @@ -471,7 +537,8 @@ The `RequestMatchers` class provides the following request matchers: | Expects a given SOAP header to exist in the request message. | `soapEnvelope()` -| Expects a given SOAP payload. May include https://github.com/xmlunit/user-guide/wiki/Placeholders[XMLUnit Placeholders] +| Expects a given SOAP payload. +May include https://github.com/xmlunit/user-guide/wiki/Placeholders[XMLUnit Placeholders] | `connectionTo()` | Expects a connection to the given URL. @@ -494,7 +561,8 @@ For more information on the request matchers provided by `RequestMatchers`, see [[client-test-response-creator]] === Using `ResponseCreator` and `ResponseCreators` -When the request message has been verified and meets the defined expectations, the `MockWebServiceServer` creates a response message for the `WebServiceTemplate` to consume. The server uses the `ResponseCreator` strategy interface for this purpose: +When the request message has been verified and meets the defined expectations, the `MockWebServiceServer` creates a response message for the `WebServiceTemplate` to consume. +The server uses the `ResponseCreator` strategy interface for this purpose: ==== [source,java] @@ -509,7 +577,8 @@ public interface ResponseCreator { ---- ==== -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 typically statically import this class. +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 typically statically import this class. The `ResponseCreators` class provides the following responses: @@ -522,13 +591,16 @@ The `ResponseCreators` class provides the following responses: | Creates a response message with a given payload. | `withError()` -| Creates an error in the response connection. This method gives you the opportunity to test your error handling. +| Creates an error in the response connection. +This method gives you the opportunity to test your error handling. | `withException()` -| Throws an exception when reading from the response connection. This method gives you the opportunity to test your exception handling. +| Throws an exception when reading from the response connection. +This method gives you the opportunity to test your exception handling. | `withMustUnderstandFault()`, `withClientOrSenderFault()`, `withServerOrReceiverFault()`, or `withVersionMismatchFault()` -| Creates a response message with a given SOAP fault. This method gives you the opportunity to test your Fault handling. +| Creates a response message with a given SOAP fault. +This method gives you the opportunity to test your Fault handling. |=== For more information on the request matchers provided by `RequestMatchers`, see the {spring-ws-api}/test/client/RequestMatchers.html[Javadoc]. diff --git a/spring-ws-docs/src/docs/asciidoc/common.adoc b/spring-ws-docs/src/docs/asciidoc/common.adoc index c185b597..df6b211f 100644 --- a/spring-ws-docs/src/docs/asciidoc/common.adoc +++ b/spring-ws-docs/src/docs/asciidoc/common.adoc @@ -3,7 +3,8 @@ [[common]] = Shared components -This chapter explores the components that are shared between client- and server-side Spring-WS development. These interfaces and classes represent the building blocks of Spring-WS, so you need to understand what they do, even if you do not use them directly. +This chapter explores the components that are shared between client- and server-side Spring-WS development. +These interfaces and classes represent the building blocks of Spring-WS, so you need to understand what they do, even if you do not use them directly. [[web-service-messages]] == Web Service Messages @@ -13,7 +14,11 @@ This section describes the messages and message factories that Spring-WS uses. [[web-service-message]] === `WebServiceMessage` -One of the core interfaces of Spring-WS is the `WebServiceMessage`. This interface represents a protocol-agnostic XML message. The interface contains methods that provide access to the payload of the message, in the form of a `javax.xml.transform.Source` or a `javax.xml.transform.Result`. `Source` and `Result` are tagging interfaces that represent an abstraction over XML input and output. Concrete implementations wrap various XML representations, as indicated in the following table: +One of the core interfaces of Spring-WS is the `WebServiceMessage`. +This interface represents a protocol-agnostic XML message. +The interface contains methods that provide access to the payload of the message, in the form of a `javax.xml.transform.Source` or a `javax.xml.transform.Result`. +`Source` and `Result` are tagging interfaces that represent an abstraction over XML input and output. +Concrete implementations wrap various XML representations, as indicated in the following table: [cols="2", options="header"] |=== @@ -44,16 +49,23 @@ In addition to reading from and writing to the payload, a web service message ca [[soap-message]] === `SoapMessage` -`SoapMessage` is a subclass of `WebServiceMessage`. It contains SOAP-specific methods, such as getting SOAP Headers, SOAP Faults, and so on. Generally, your code should not be dependent on `SoapMessage`, because the content of the SOAP Body (the payload of the message) can be obtained by using `getPayloadSource()` and `getPayloadResult()` in the `WebServiceMessage`. Only when it is necessary to perform SOAP-specific actions (such as adding a header, getting an attachment, and so on) should you need to cast `WebServiceMessage` to `SoapMessage`. +`SoapMessage` is a subclass of `WebServiceMessage`. +It contains SOAP-specific methods, such as getting SOAP Headers, SOAP Faults, and so on. +Generally, your code should not be dependent on `SoapMessage`, because the content of the SOAP Body (the payload of the message) can be obtained by using `getPayloadSource()` and `getPayloadResult()` in the `WebServiceMessage`. +Only when it is necessary to perform SOAP-specific actions (such as adding a header, getting an attachment, and so on) should you need to cast `WebServiceMessage` to `SoapMessage`. [[message-factories]] === Message Factories -Concrete message implementations are created by a `WebServiceMessageFactory`. This factory can create an empty message or read a message from an input stream. One concrete implementations of `WebServiceMessageFactory` is provided based on SAAJ, the SOAP with Attachments API for Java. +Concrete message implementations are created by a `WebServiceMessageFactory`. +This factory can create an empty message or read a message from an input stream. +One concrete implementations of `WebServiceMessageFactory` is provided based on SAAJ, the SOAP with Attachments API for Java. ==== `SaajSoapMessageFactory` -The `SaajSoapMessageFactory` uses the SOAP with Attachments API for Java (SAAJ) 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: +The `SaajSoapMessageFactory` uses the SOAP with Attachments API for Java (SAAJ) 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: [cols="2", options="header"] |=== @@ -72,10 +84,12 @@ The `SaajSoapMessageFactory` uses the SOAP with Attachments API for Java (SAAJ) | SUN Glassfish 1 | 1.3 -2+|^1^Weblogic 9 has a known bug in the SAAJ 1.2 implementation: it implements all the 1.2 interfaces but throws an `UnsupportedOperationException` when called. Spring-WS has a workaround: It uses SAAJ 1.1 when operating on WebLogic 9. +2+|^1^Weblogic 9 has a known bug in the SAAJ 1.2 implementation: it implements all the 1.2 interfaces but throws an `UnsupportedOperationException` when called. +Spring-WS has a workaround: It uses SAAJ 1.1 when operating on WebLogic 9. |=== -Additionally, Java SE 6 includes SAAJ 1.3. You can wire up a `SaajSoapMessageFactory` as follows: +Additionally, Java SE 6 includes SAAJ 1.3. +You can wire up a `SaajSoapMessageFactory` as follows: ==== [source,xml] @@ -84,12 +98,15 @@ Additionally, Java SE 6 includes SAAJ 1.3. You can wire up a `SaajSoapMessageFac ---- ==== -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 performant. +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 performant. [[soap_11_or_12]] ==== SOAP 1.1 or 1.2 -`SaajSoapMessageFactory` has 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: +`SaajSoapMessageFactory` has 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: ==== [source,xml] @@ -116,24 +133,36 @@ In the preceding example, we define a `SaajSoapMessageFactory` that accepts only [WARNING] ==== -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, though they still work. +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, though 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 1.1 is currently the safest bet. +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 1.1 is currently the safest bet. ==== [[message-context]] === `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. +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-WS, 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 <>. 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`. +In Spring-WS, 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 <>. +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`. [[transport-context]] == `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 message content. +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 message content. -However, it is sometimes necessary to get access to the underlying transport, either on the client or the server side. For this, Spring-WS 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: +However, it is sometimes necessary to get access to the underlying transport, either on the client or the server side. +For this, Spring-WS 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: ==== [source,java] @@ -148,17 +177,23 @@ String ipAddress = request.getRemoteAddr(); [[xpath]] == Handling XML With XPath -One of the best ways to handle XML is to use XPath. Quoting <>, item 35: +One of the best ways to handle XML is to use XPath. +Quoting <>, item 35: [quote, Elliotte Rusty Harold] -XPath is a fourth generation declarative language that allows you to specify which nodes you want to process without specifying exactly how the processor is supposed to navigate to those nodes. XPath's data model is very well designed to support exactly what almost all developers want from XML. For instance, it merges all adjacent text including that in CDATA sections, allows values to be calculated that skip over comments and processing instructions` and include text from child and descendant elements, and requires all external entity references to be resolved. In practice, XPath expressions tend to be much more robust against unexpected but perhaps insignificant changes in the input document. +XPath is a fourth generation declarative language that allows you to specify which nodes you want to process without specifying exactly how the processor is supposed to navigate to those nodes. +XPath's data model is very well designed to support exactly what almost all developers want from XML. +For instance, it merges all adjacent text including that in CDATA sections, allows values to be calculated that skip over comments and processing instructions` and include text from child and descendant elements, and requires all external entity references to be resolved. +In practice, XPath expressions tend to be much more robust against unexpected but perhaps insignificant changes in the input document. Spring-WS has two ways to use XPath within your application: the faster `XPathExpression` or the more flexible `XPathOperations`. [[xpath-expression]] === `XPathExpression` -The `XPathExpression` is an abstraction over a compiled XPath expression, such as the Java 5 `javax.xml.xpath.XPathExpression` interface or the Jaxen `XPath` class. To construct an expression in an application context, you can use `XPathExpressionFactoryBean`. The following example uses this factory bean: +The `XPathExpression` is an abstraction over a compiled XPath expression, such as the Java 5 `javax.xml.xpath.XPathExpression` interface or the Jaxen `XPath` class. +To construct an expression in an application context, you can use `XPathExpressionFactoryBean`. +The following example uses this factory bean: ==== [source,xml] @@ -180,7 +215,8 @@ The `XPathExpression` is an abstraction over a compiled XPath expression, such a ---- ==== -The preceding expression does not use namespaces, but we could set those by using the `namespaces` property of the factory bean. The expression can be used in the code as follows: +The preceding expression does not use namespaces, but we could set those by using the `namespaces` property of the factory bean. +The expression can be used in the code as follows: ==== [source,java] @@ -204,7 +240,8 @@ public class MyXPathClass { ---- ==== -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 to use it: +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 to use it: ==== [source,java] @@ -235,12 +272,16 @@ public class MyXPathClass { ---- ==== -Similar to mapping rows in Spring JDBC's `RowMapper`, each result node is mapped by using an anonymous inner class. In this case, we create a `Contact` object, which we use later on. +Similar to mapping rows in Spring JDBC's `RowMapper`, each result node is mapped by using an anonymous inner class. +In this case, we create a `Contact` object, which we use later on. [[xpath-template]] === `XPathOperations` -The `XPathExpression` lets you evaluate only a single, pre-compiled expression. A more flexible, though slower, alternative is the `XPathOperations`. This class follows the common template pattern used throughout Spring (`JdbcTemplate`, `JmsTemplate`, and others). The following listing shows an example: +The `XPathExpression` lets you evaluate only a single, pre-compiled expression. +A more flexible, though slower, alternative is the `XPathOperations`. +This class follows the common template pattern used throughout Spring (`JdbcTemplate`, `JmsTemplate`, and others). +The following listing shows an example: ==== [source,java,subs="verbatim,quotes"] @@ -263,13 +304,19 @@ public class MyXPathClass { [[logging]] == Message Logging and Tracing -When developing or debugging a web service, it can be quite useful to look at the content of a (SOAP) message when it arrives or before it is sent. Spring-WS offer this functionality, through the standard Commons Logging interface. +When developing or debugging a web service, it can be quite useful to look at the content of a (SOAP) message when it arrives, or before it is sent. +Spring-WS offer this functionality, through the standard Commons Logging interface. -To log all server-side messages, set the `org.springframework.ws.server.MessageTracing` logger level to `DEBUG` or `TRACE`. On the `DEBUG` level, only the payload root element is logged. On the `TRACE` level, the entire message content is logged. If you want to log only sent messages, use the `org.springframework.ws.server.MessageTracing.sent` logger. Similarly, you can use `org.springframework.ws.server.MessageTracing.received` to log only received messages. +To log all server-side messages, set the `org.springframework.ws.server.MessageTracing` logger level to `DEBUG` or `TRACE`. +On the `DEBUG` level, only the payload root element is logged. +On the `TRACE` level, the entire message content is logged. +If you want to log only sent messages, use the `org.springframework.ws.server.MessageTracing.sent` logger. +Similarly, you can use `org.springframework.ws.server.MessageTracing.received` to log only received messages. On the client-side, similar loggers exist: `org.springframework.ws.client.MessageTracing.sent` and `org.springframework.ws.client.MessageTracing.received`. -The following example of a `log4j2.properties` configuration file logs 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: +The following example of a `log4j2.properties` configuration file logs 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: ==== [source] diff --git a/spring-ws-docs/src/docs/asciidoc/index.adoc b/spring-ws-docs/src/docs/asciidoc/index.adoc index 75500fa1..b95b4b61 100644 --- a/spring-ws-docs/src/docs/asciidoc/index.adoc +++ b/spring-ws-docs/src/docs/asciidoc/index.adoc @@ -25,7 +25,9 @@ include::preface.adoc[leveloffset=+1] = I. Introduction :sectnums: -This first part of the reference documentation <> of Spring Web Services and the underlying concepts. Then, <> behind contract-first web service development are explained. Finally, the third section provides <>. +This first part of the reference documentation <> of Spring Web Services and the underlying concepts. +Then, <> behind contract-first web service development are explained. +Finally, the third section provides <>. include::what-is-spring-ws.adoc[leveloffset=+1] @@ -37,7 +39,8 @@ include::tutorial.adoc[leveloffset=+1] = II. Reference :sectnums: -This part of the reference documentation details the various components that comprise Spring Web Services. This includes <> that discusses the parts common to both client- and server-side WS, a chapter devoted to the specifics of <>, a chapter about using web services on <>, and a chapter on using <>. +This part of the reference documentation details the various components that comprise Spring Web Services. +This includes <> that discusses the parts common to both client- and server-side WS, a chapter devoted to the specifics of <>, a chapter about using web services on <>, and a chapter on using <>. include::common.adoc[leveloffset=+1] @@ -52,7 +55,8 @@ include::security.adoc[leveloffset=+1] = III. Other Resources :sectnums: -In addition to this reference documentation, a number of other resources may help you learn how to use Spring Web Services. These additional, third-party resources are enumerated in this section. +In addition to this reference documentation, a number of other resources may help you learn how to use Spring Web Services. +These additional, third-party resources are enumerated in this section. :sectnums!: diff --git a/spring-ws-docs/src/docs/asciidoc/preface.adoc b/spring-ws-docs/src/docs/asciidoc/preface.adoc index 781f0412..c9d10405 100644 --- a/spring-ws-docs/src/docs/asciidoc/preface.adoc +++ b/spring-ws-docs/src/docs/asciidoc/preface.adoc @@ -2,6 +2,14 @@ [[overview]] = Preface -In the current age of Service Oriented Architectures, more and more people use 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 that contain all the data necessary to process the request. Conceptually, XML-based web services are better compared to message queues than to remoting solutions. Overall, XML should be considered the platform-neutral representation of data, the _common language_ of SOA. When developing or using web services, the focus should be on this XML and not on Java. +In the current age of Service Oriented Architectures, more and more people use 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 that contain all the data necessary to process the request. +Conceptually, XML-based web services are better compared to message queues than to remoting solutions. +Overall, XML should be considered the platform-neutral representation of data, the _common language_ of SOA. +When developing or using web services, the focus should be on this XML and not on Java. -Spring-WS focuses on creating these document-driven web services. Spring-WS facilitates contract-first SOAP service development, allowing for the creation of flexible web services by using one of the many ways to manipulate XML payloads. Spring-WS provides a powerful <>, a <> solution that integrates with your existing application security solution, and a <> that follows the familiar Spring template pattern. +Spring-WS focuses on creating these document-driven web services. +Spring-WS facilitates contract-first SOAP service development, allowing for the creation of flexible web services by using one of the many ways to manipulate XML payloads. +Spring-WS provides a powerful <>, a <> solution that integrates with your existing application security solution, and a <> that follows the familiar Spring template pattern. diff --git a/spring-ws-docs/src/docs/asciidoc/security.adoc b/spring-ws-docs/src/docs/asciidoc/security.adoc index c9548bc9..1c5fdaad 100644 --- a/spring-ws-docs/src/docs/asciidoc/security.adoc +++ b/spring-ws-docs/src/docs/asciidoc/security.adoc @@ -1,34 +1,54 @@ [[security]] = Securing Your Web services with Spring-WS -This chapter explains how to add WS-Security aspects to your Web services. We focus on the three different areas of WS-Security: +This chapter explains how to add WS-Security aspects to your Web services. +We focus on the three different areas of WS-Security: -* *Authentication*: This is the process of determining whether a principal is who they claim to be. In this context, a "principal" generally means a user, device or some other system that can perform an action in your application. -* *Digital signatures*: The digital signature of a message is a piece of information based on both the document and the signer's private key. It is created through the use of a hash function and a private signing function (encrypting with the signer's private key). -* *Encryption and Decryption*: Encryption is the process of transforming data into a form that is impossible to read without the appropriate key. It is mainly used to keep information hidden from anyone for whom it is not intended. Decryption is the reverse of encryption. It is the process of transforming encrypted data back into an readable form. +* *Authentication*: This is the process of determining whether a principal is who they claim to be. +In this context, a "principal" generally means a user, device or some other system that can perform an action in your application. +* *Digital signatures*: The digital signature of a message is a piece of information based on both the document and the signer's private key. +It is created through the use of a hash function and a private signing function (encrypting with the signer's private key). +* *Encryption and Decryption*: Encryption is the process of transforming data into a form that is impossible to read without the appropriate key. +It is mainly used to keep information hidden from anyone for whom it is not intended. +Decryption is the reverse of encryption. +It is the process of transforming encrypted data back into an readable form. -These three areas are implemented by using the `XwsSecurityInterceptor` or `Wss4jSecurityInterceptor`, which we describe in <> and <>, respectively +These three areas are implemented by using the `XwsSecurityInterceptor` or `Wss4jSecurityInterceptor`, which we describe in <> and <>, respectively. [NOTE] ==== -WS-Security (especially encryption and signing) requires substantial amounts of memory and can decrease performance. If performance is important to you, you might want to consider not using WS-Security or using HTTP-based security. +WS-Security (especially encryption and signing) requires substantial amounts of memory and can decrease performance. +If performance is important to you, you might want to consider not using WS-Security or using HTTP-based security. ==== [[security-xws-security-interceptor]] == `XwsSecurityInterceptor` -The `XwsSecurityInterceptor` is an `EndpointInterceptor` (see <>) 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 (https://www.oracle.com/java/technologies/java-archive-jwsdp-downloads.html[Java WSDP]). +The `XwsSecurityInterceptor` is an `EndpointInterceptor` (see <>) 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 (https://www.oracle.com/java/technologies/java-archive-jwsdp-downloads.html[Java WSDP]). -Like any other endpoint interceptor, it is defined in the endpoint mapping (see <>). This means that you can be selective about adding WS-Security support. Some endpoint mappings require it, while others do not. +Like any other endpoint interceptor, it is defined in the endpoint mapping (see <>). +This means that you can be selective about adding WS-Security support. +Some endpoint mappings require it, while others do not. [NOTE] ==== -XWSS requires a SUN SAAJ reference implementation. The WSS4J interceptor does not have these requirements (see <>). +XWSS requires a SUN SAAJ reference implementation. +The WSS4J interceptor does not have these requirements (see <>). ==== -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 to outgoing messages. The basic format of the policy file is explained in the following sections, but a more in-depth tutorial https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp564887[is available]. You can set the policy with the `policyConfiguration` property, which requires a Spring resource. The policy file can contain multiple elements -- for example, require a username token on incoming messages and sign all outgoing messages. It contains a `SecurityConfiguration` element (not a `JAXRPCSecurity` element) as its root. +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 to outgoing messages. +The basic format of the policy file is explained in the following sections, but a more in-depth tutorial https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp564887[is available]. +You can set the policy with the `policyConfiguration` property, which requires a Spring resource. +The policy file can contain multiple elements -- for example, require a username token on incoming messages and sign all outgoing messages. +It contains a `SecurityConfiguration` element (not a `JAXRPCSecurity` element) as its root. -Additionally, the security interceptor requires one or more `CallbackHandler` instances to operate. These handlers are used to retrieve certificates, private keys, validate user credentials, and so on. Spring-WS offers handlers for most common security concerns -- for example, authenticating against a Spring Security authentication manager and signing outgoing messages based on a X509 certificate. The following sections indicate what callback handler to use for which security concern. You can set the callback handlers by using the `callbackHandler` or `callbackHandlers` property. +Additionally, the security interceptor requires one or more `CallbackHandler` instances to operate. +These handlers are used to retrieve certificates, private keys, validate user credentials, and so on. +Spring-WS offers handlers for most common security concerns -- for example, authenticating against a Spring Security authentication manager and signing outgoing messages based on a X509 certificate. +The following sections indicate what callback handler to use for which security concern. +You can set the callback handlers by using the `callbackHandler` or `callbackHandlers` property. The following example that shows how to wire up the `XwsSecurityInterceptor`: @@ -51,26 +71,41 @@ The following example that shows how to wire up the `XwsSecurityInterceptor`: ---- ==== -This interceptor is configured by using the `securityPolicy.xml` file on the classpath. It uses two callback handlers that are defined later in the file. +This interceptor is configured by using the `securityPolicy.xml` file on the classpath. +It uses two callback handlers that are defined later in the file. [[keystore]] === Keystores -For most cryptographic operations, you an use the standard `java.security.KeyStore` objects. These operations include certificate verification, message signing, signature verification, and encryption. They exclude 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. +For most cryptographic operations, you an use the standard `java.security.KeyStore` objects. +These operations include certificate verification, message signing, signature verification, and encryption. +They exclude 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: +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 a certificate chain for the corresponding public key. Within the field of WS-Security, this accounts for message signing and message decryption. +* *Private Keys*: These keys are used for self-authentication. +The private key is accompanied by a certificate chain for the corresponding public key. +Within the field of WS-Security, this accounts for message signing and message decryption. * *Symmetric Keys*: Symmetric (or secret) keys are also used for message encryption and decryption -- 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 does indeed belong to the owner of the certificate. Within WS-Security, these certificates are used for certificate validation, signature verification, and encryption. +* *Trusted certificates*: These X509 certificates are called a "trusted certificate" because the keystore owner trusts that the public key in the certificates does indeed belong to the owner of the certificate. +Within WS-Security, these certificates are used for certificate validation, signature verification, and encryption. ==== Using `keytool` -The `keytool` program, a key and certificate management utility, is supplied with your Java Virtual Machine. You can use this tool to create new keystores, add new private keys and certificates to them, and so on. It is beyond the scope of this document to provide a full reference of the `keytool` command, check the https://docs.oracle.com/en/java/javase/17/docs/specs/man/keytool.html[standard reference] or invoke `keytool -help` on the command line. +The `keytool` program, a key and certificate management utility, is supplied with your Java Virtual Machine. +You can use this tool to create new keystores, add new private keys and certificates to them, and so on. +It is beyond the scope of this document to provide a full reference of the `keytool` command, check the https://docs.oracle.com/en/java/javase/17/docs/specs/man/keytool.html[standard reference] or invoke `keytool -help` on the command line. ==== Using `KeyStoreFactoryBean` -To easily load a keystore by using Spring configuration, you can use the `KeyStoreFactoryBean`. It has a resource location property, which you can set to point to the path of the keystore to load. A password may be given to check the integrity of the keystore data. If a password is not given, integrity checking is not performed. The following listing configures a `KeyStoreFactoryBean`: +To easily load a keystore by using Spring configuration, you can use the `KeyStoreFactoryBean`. +It has a resource location property, which you can set to point to the path of the keystore to load. +A password may be given to check the integrity of the keystore data. +If a password is not given, integrity checking is not performed. +The following listing configures a `KeyStoreFactoryBean`: ==== [source,xml] @@ -87,7 +122,13 @@ WARNING: If you do not specify the location property, a new, empty keystore is c [[security-key-store-callback-handler]] ==== KeyStoreCallbackHandler -To use the keystores within a `XwsSecurityInterceptor`, you 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` is used. For determining trust relationships, the `trustStore` is used. The following table indicates this: +To use the keystores within a `XwsSecurityInterceptor`, you 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` is used. +For determining trust relationships, the `trustStore` is used. +The following table indicates this: [cols="2", options="header"] |=== @@ -118,7 +159,9 @@ To use the keystores within a `XwsSecurityInterceptor`, you need to define a `Ke Additionally, the `KeyStoreCallbackHandler` has a `privateKeyPassword` property, which should be set to unlock the private keys contained in the`keyStore`. -If the `symmetricStore` is not set, it defaults to the `keyStore`. If the key or trust store is not set, the callback handler uses the standard Java mechanism to load or create it. See {spring-ws-api}/soap/security/wss4j2/callback/KeyStoreCallbackHandler.html[`KeyStoreCallbackHandler`] for more details. +If the `symmetricStore` is not set, it defaults to the `keyStore`. +If the key or trust store is not set, the callback handler uses the standard Java mechanism to load or create it. +See {spring-ws-api}/soap/security/wss4j2/callback/KeyStoreCallbackHandler.html[`KeyStoreCallbackHandler`] for more details. For instance, if you want to use the `KeyStoreCallbackHandler` to validate incoming certificates or signatures, you can use a trust store: @@ -161,18 +204,24 @@ The following sections indicate where the `KeyStoreCallbackHandler` can be used === Authentication -As stated in the <>, 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. +As stated in the <>, 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. ==== Plain Text Username Authentication -The simplest form of username authentication uses plain text passwords. In this scenario, the SOAP message contains 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. +The simplest form of username authentication uses plain text passwords. +In this scenario, the SOAP message contains 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] ==== -Plain text passwords are not very secure. Therefore, you should always add additional security measures to your transport layer if you use them (using HTTPS instead of plain HTTP, for instance). +Plain text passwords are not very secure. +Therefore, you should always add additional security measures to your transport layer if you use 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 `passwordDigestRequired` attribute set to `false`. Fore more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp567459[official reference] of possible child elements. The following listing shows how to include a `RequireUsernameToken` element: +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 `passwordDigestRequired` attribute set to `false`. +Fore more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp567459[official reference] of possible child elements. +The following listing shows how to include a `RequireUsernameToken` element: ==== [source,xml] @@ -185,7 +234,9 @@ To require that every incoming message contains a `UsernameToken` with a plain t ---- ==== -If the username token is not present, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. If it is present, it fires a `PasswordValidationCallback` with a `PlainTextPasswordRequest` to the registered handlers. Within Spring-WS, there are three classes that handle this particular callback. +If the username token is not present, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. +If it is present, it fires a `PasswordValidationCallback` with a `PlainTextPasswordRequest` to the registered handlers. +Within Spring-WS, there are three classes that handle this particular callback: * <> * <> @@ -194,7 +245,8 @@ If the username token is not present, the `XwsSecurityInterceptor` returns a SOA [[security-simple-password-validation-callback-handler]] ===== Using `SimplePasswordValidationCallbackHandler` -The simplest password validation handler is the `SimplePasswordValidationCallbackHandler`. This handler validates passwords against an in-memory `Properties` object, which you can specify by using the `users` property: +The simplest password validation handler is the `SimplePasswordValidationCallbackHandler`. +This handler validates passwords against an in-memory `Properties` object, which you can specify by using the `users` property: ==== [source,xml] @@ -215,9 +267,14 @@ In this case, we are allowing only the user, "Bert", to log in by using the pass [[using-springplaintextpasswordvalidationcallbackhandler]] ===== Using `SpringPlainTextPasswordValidationCallbackHandler` -The `SpringPlainTextPasswordValidationCallbackHandler` uses https://spring.io/projects/spring-security[Spring Security] to authenticate users. It is beyond the scope of this document to describe Spring Security, but it is a full-fledged security framework. You can read more about it in the https://docs.spring.io/spring-security/reference[Spring Security reference documentation]. +The `SpringPlainTextPasswordValidationCallbackHandler` uses https://spring.io/projects/spring-security[Spring Security] to authenticate users. +It is beyond the scope of this document to describe Spring Security, but it is a full-fledged security framework. +You can read more about it in the https://docs.spring.io/spring-security/reference[Spring Security reference documentation]. -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 by using the `authenticationManager` property: +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 by using the `authenticationManager` property: ==== [source,xml] @@ -245,9 +302,12 @@ The `SpringPlainTextPasswordValidationCallbackHandler` requires an `Authenticati [[using-jaasplaintextpasswordvalidationcallbackhandler]] ===== Using `JaasPlainTextPasswordValidationCallbackHandler` -The `JaasPlainTextPasswordValidationCallbackHandler` is based on the standard https://www.oracle.com/java/technologies/javase/javase-tech-security.html[Java Authentication and Authorization Service]. It is beyond the scope of this document to provide a full introduction into JAAS, but https://docs.oracle.com/javase/8/docs/technotes/guides/security/jaas/tutorials/index.html[tutorials] are available. +The `JaasPlainTextPasswordValidationCallbackHandler` is based on the standard https://www.oracle.com/java/technologies/javase/javase-tech-security.html[Java Authentication and Authorization Service]. +It is beyond the scope of this document to provide a full introduction into JAAS, but https://docs.oracle.com/javase/8/docs/technotes/guides/security/jaas/tutorials/index.html[tutorials] are available. -The `JaasPlainTextPasswordValidationCallbackHandler` requires only a `loginContextName` to operate. It creates a new JAAS `LoginContext` by using this name and handles the standard JAAS `NameCallback` and `PasswordCallback` by 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. +The `JaasPlainTextPasswordValidationCallbackHandler` requires only a `loginContextName` to operate. +It creates a new JAAS `LoginContext` by using this name and handles the standard JAAS `NameCallback` and `PasswordCallback` by 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: @@ -261,13 +321,20 @@ You can wire up a `JaasPlainTextPasswordValidationCallbackHandler` as follows: ---- ==== -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 http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-jaas.html[tutorial mentioned earlier]. +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 http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-jaas.html[tutorial mentioned earlier]. ==== 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. This method is comparable to the digest authentication provided by HTTP servers. +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. +This method is comparable 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 to `true`. Additionally, the `nonceRequired` attribute should be set to `true`. For more details, check the http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp567459[official reference] of possible child elements. The following listing shows how to define a `RequireUsernameToken` element: +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 to `true`. +Additionally, the `nonceRequired` attribute should be set to `true`. +For more details, check the http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp567459[official reference] of possible child elements. +The following listing shows how to define a `RequireUsernameToken` element: ==== [source,xml] @@ -280,15 +347,24 @@ To require that every incoming message contains a `UsernameToken` element with a ---- ==== -If the username token is not present, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. If it is present, it fires a `PasswordValidationCallback` with a `DigestPasswordRequest` to the registered handlers. Within Spring-WS, two classes handle this particular callback: `SimplePasswordValidationCallbackHandler` and `SpringDigestPasswordValidationCallbackHandler`. +If the username token is not present, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. +If it is present, it fires a `PasswordValidationCallback` with a `DigestPasswordRequest` to the registered handlers. +Within Spring-WS, two classes handle this particular callback: `SimplePasswordValidationCallbackHandler` and `SpringDigestPasswordValidationCallbackHandler`. ===== Using `SimplePasswordValidationCallbackHandler` -The `SimplePasswordValidationCallbackHandler` can handle both plain text passwords as well as password digests. It is described in <>. +The `SimplePasswordValidationCallbackHandler` can handle both plain text passwords as well as password digests. +It is described in <>. ===== Using `SpringDigestPasswordValidationCallbackHandler` -The `SpringDigestPasswordValidationCallbackHandler` requires a Spring Security `UserDetailService` to operate. It uses this service to retrieve the password of the user specified in the token. The digest of the password contained in this details object is then compared with the digest in the message. If they are equal, the user has successfully authenticated, and a `UsernamePasswordAuthenticationToken` is stored in the `SecurityContextHolder`. You can set the service by using the `userDetailsService` property. Additionally, you can set a `userCache` property, to cache loaded user details. The following example shows how to do so: +The `SpringDigestPasswordValidationCallbackHandler` requires a Spring Security `UserDetailService` to operate. +It uses this service to retrieve the password of the user specified in the token. +The digest of the password contained in this details object is then compared with the digest in the message. +If they are equal, the user has successfully authenticated, and a `UsernamePasswordAuthenticationToken` is stored in the `SecurityContextHolder`. +You can set the service by using the `userDetailsService` property. +Additionally, you can set a `userCache` property, to cache loaded user details. +The following example shows how to do so: ==== [source,xml] @@ -307,9 +383,15 @@ The `SpringDigestPasswordValidationCallbackHandler` requires a Spring Security ` [[security-certificate-authentication]] ==== Certificate Authentication -A more secure way of authentication uses X509 certificates. In this scenario, the SOAP message contains a`BinarySecurityToken`, which contains a Base 64-encoded version of a X509 certificate. The certificate is used by the recipient to authenticate. The certificate stored in the message is also used to sign the message (see <>). +A more secure way of authentication uses X509 certificates. +In this scenario, the SOAP message contains a`BinarySecurityToken`, which contains a Base 64-encoded version of a X509 certificate. +The certificate is used by the recipient to authenticate. +The certificate stored in the message is also used to sign the message (see <>). -To make sure that all incoming SOAP messages carry a`BinarySecurityToken`, the security policy file should contain a `RequireSignature` element. This element can further carry other elements, which are covered in <>. For more details, check the http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565769[official reference] of possible child elements. The following listing shows how to define a `RequireSignature` element: +To make sure that all incoming SOAP messages carry a`BinarySecurityToken`, the security policy file should contain a `RequireSignature` element. +This element can further carry other elements, which are covered in <>. +For more details, check the http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565769[official reference] of possible child elements. +The following listing shows how to define a `RequireSignature` element: ==== [source,xml] @@ -322,16 +404,20 @@ To make sure that all incoming SOAP messages carry a`BinarySecurityToken`, the s ---- ==== -When a message arrives that carries no certificate, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. If it is present, it fires a `CertificateValidationCallback`. Two handlers within Spring-WS handle this callback for authentication purposes: +When a message arrives that carries no certificate, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. +If it is present, it fires a `CertificateValidationCallback`. +Two handlers within Spring-WS handle this callback for authentication purposes: * <> * <> [NOTE] ===== -In most cases, certificate authentication should be preceded by certificate validation, since you want to authenticate against only 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. +In most cases, certificate authentication should be preceded by certificate validation, since you want to authenticate against only 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. -In 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`: +In 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`: ==== [source,xml] @@ -349,17 +435,24 @@ In Spring-WS terms, this means that the `SpringCertificateValidationCallbackHand ---- ==== -Using this setup, the interceptor first determines if the certificate in the message is valid buusing the keystore and then authenticating against it. +Using this setup, the interceptor first determines if the certificate in the message is valid by using the keystore and then authenticating against it. ===== [[using-keystorecallbackhandler]] ===== Using `KeyStoreCallbackHandler` -The `KeyStoreCallbackHandler` uses a standard Java keystore to validate certificates. This certificate validation process consists of the following steps: . +The `KeyStoreCallbackHandler` uses a standard Java keystore to validate certificates. +This certificate validation process consists of the following steps: -. The handler checks whether the certificate is in the private `keyStore`. If it is, it is valid. -. If the certificate is not in the private keystore, the handler checks 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 continues with the final step. -. A certification path for the certificate is created. This basically means that the handler determines whether the certificate has been issued by any of the certificate authorities in the `trustStore`. If a certification path can be built successfully, the certificate is valid. Otherwise, the certificate is not valid. +. The handler checks whether the certificate is in the private `keyStore`. +If it is, it is valid. +. If the certificate is not in the private keystore, the handler checks 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 continues with the final step. +. A certification path for the certificate is created. +This basically means that the handler determines whether the certificate has been issued by any of the certificate authorities in the `trustStore`. +If a certification path can be built successfully, the certificate is valid. +Otherwise, the certificate is not valid. To use the `KeyStoreCallbackHandler` for certificate validation purposes, you most likely need to set only the `trustStore` property: @@ -384,7 +477,11 @@ Using the setup shown in the preceding example, the certificate that is to be va [[using-springcertificatevalidationcallbackhandler]] ===== Using `SpringCertificateValidationCallbackHandler` -The `SpringCertificateValidationCallbackHandler` 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 that can handle this token (usually an instance of `X509AuthenticationProvider`). If authentication is successful, the token is stored in the `SecurityContextHolder`. You can set the authentication manager by using the `authenticationManager` property: +The `SpringCertificateValidationCallbackHandler` 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 that can handle this token (usually an instance of `X509AuthenticationProvider`). +If authentication is successful, the token is stored in the `SecurityContextHolder`. +You can set the authentication manager by using the `authenticationManager` property: ==== [source,xml] @@ -414,18 +511,25 @@ The `SpringCertificateValidationCallbackHandler` requires an Spring Security `Au ---- ==== -In this case, we use a custom user details service to obtain authentication details based on the certificate. See the http://www.springframework.org/security[Spring Security reference documentation] for more information about authentication against X509 certificates. +In this case, we use a custom user details service to obtain authentication details based on the certificate. +See the http://www.springframework.org/security[Spring Security reference documentation] for more information about authentication against X509 certificates. === Digital Signatures -The digital signature of a message is a piece of information based on both the document and the signer's private key. Two main tasks are related to signatures in WS-Security: verifying signatures and signing messages. +The digital signature of a message is a piece of information based on both the document and the signer's private key. +Two main tasks are related to signatures in WS-Security: verifying signatures and signing messages. [[security-verifying-signatures]] ==== Verifying Signatures -As with <>, a signed message contains a `BinarySecurityToken`, which contains the certificate used to sign the message. Additionally, it contains a `SignedInfo` block, which indicates what part of the message was signed. +As with <>, a signed message contains a `BinarySecurityToken`, which contains the certificate used to sign the message. +Additionally, it contains a `SignedInfo` block, which indicates what part of the message was signed. -To make sure that all incoming SOAP messages carry a `BinarySecurityToken`, the security policy file should contain a `RequireSignature` element. It can also contain a `SignatureTarget` element, which specifies the target message part that was expected to be signed and various other sub-elements. You can also define the private key alias to use, whether to use a symmetric instead of a private key, and many other properties. For more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565769[official reference] of possible child elements. The following listing configures a `RequireSignature` element: +To make sure that all incoming SOAP messages carry a `BinarySecurityToken`, the security policy file should contain a `RequireSignature` element. +It can also contain a `SignatureTarget` element, which specifies the target message part that was expected to be signed and various other sub-elements. +You can also define the private key alias to use, whether to use a symmetric instead of a private key, and many other properties. +For more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565769[official reference] of possible child elements. +The following listing configures a `RequireSignature` element: ==== [source,xml] @@ -436,11 +540,14 @@ To make sure that all incoming SOAP messages carry a `BinarySecurityToken`, the ---- ==== -If the signature is not present, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. If it is present, it fires a `SignatureVerificationKeyCallback` to the registered handlers. Within Spring-WS, one class handles this particular callback: `KeyStoreCallbackHandler`. +If the signature is not present, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. +If it is present, it fires a `SignatureVerificationKeyCallback` to the registered handlers. +Within Spring-WS, one class handles this particular callback: `KeyStoreCallbackHandler`. ===== Using `KeyStoreCallbackHandler` -As described in <>, `KeyStoreCallbackHandler` uses a `java.security.KeyStore` for handling various cryptographic callbacks, including signature verification. For signature verification, the handler uses the `trustStore` property: +As described in <>, `KeyStoreCallbackHandler` uses a `java.security.KeyStore` for handling various cryptographic callbacks, including signature verification. +For signature verification, the handler uses the `trustStore` property: ==== [source,xml] @@ -460,9 +567,14 @@ As described in <>, `KeyStoreCallbackHandle ==== Signing Messages -When signing a message, the `XwsSecurityInterceptor` adds the `BinarySecurityToken` to the message. It also adds a `SignedInfo` block, which indicates what part of the message was signed. +When signing a message, the `XwsSecurityInterceptor` adds the `BinarySecurityToken` to the message. +It also adds a `SignedInfo` block, which indicates what part of the message was signed. -To sign all outgoing SOAP messages, the security policy file should contain a `Sign` element. It can also contain a `SignatureTarget` element, which specifies the target message part that was expected to be signed and various other sub-elements. You can also define the private key alias to use, whether to use a symmetric instead of a private key, and many other properties. For more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565497[official reference] of possible child elements. The following example includes a `Sign` element: +To sign all outgoing SOAP messages, the security policy file should contain a `Sign` element. +It can also contain a `SignatureTarget` element, which specifies the target message part that was expected to be signed and various other sub-elements. +You can also define the private key alias to use, whether to use a symmetric instead of a private key, and many other properties. +For more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565497[official reference] of possible child elements. +The following example includes a `Sign` element: ==== [source,xml] @@ -473,11 +585,15 @@ To sign all outgoing SOAP messages, the security policy file should contain a `S ---- ==== -The `XwsSecurityInterceptor` fires a `SignatureKeyCallback` to the registered handlers. Within Spring-WS, the `KeyStoreCallbackHandler` class handles this particular callback. +The `XwsSecurityInterceptor` fires a `SignatureKeyCallback` to the registered handlers. +Within Spring-WS, the `KeyStoreCallbackHandler` class handles this particular callback. ===== Using `KeyStoreCallbackHandler` -As described in <>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` to handle 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. The following example uses a `KeyStoreCallbackHandler`: +As described in <>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` to handle 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. +The following example uses a `KeyStoreCallbackHandler`: ==== [source,xml] @@ -498,11 +614,15 @@ As described in <>, the `KeyStoreCallbackHa === Decryption and Encryption -When encrypting, the message is transformed into a form that can be read only with the appropriate key. The message can be decrypted to reveal the original, readable message. +When encrypting, the message is transformed into a form that can be read only with the appropriate key. +The message can be decrypted to reveal the original, readable message. ==== Decryption -To decrypt incoming SOAP messages, the security policy file should contain a `RequireEncryption` element. This element can further carry a `EncryptionTarget` element that indicates which part of the message should be encrypted and a `SymmetricKey` to indicate that a shared secret instead of the regular private key should be used to decrypt the message. For more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565951[official reference ] of the other elements. The following example uses a `RequireEncryption` element: +To decrypt incoming SOAP messages, the security policy file should contain a `RequireEncryption` element. +This element can further carry a `EncryptionTarget` element that indicates which part of the message should be encrypted and a `SymmetricKey` to indicate that a shared secret instead of the regular private key should be used to decrypt the message. +For more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565951[official reference ] of the other elements. +The following example uses a `RequireEncryption` element: ==== [source,xml] @@ -513,11 +633,17 @@ To decrypt incoming SOAP messages, the security policy file should contain a `Re ---- ==== -If an incoming message is not encrypted, the `XwsSecurityInterceptor` returns a SOAP ault to the sender. If it is present, it fires a `DecryptionKeyCallback` to the registered handlers. Within Spring-WS, the `KeyStoreCallbackHandler` class handles this particular callback. +If an incoming message is not encrypted, the `XwsSecurityInterceptor` returns a SOAP fault to the sender. +If it is present, it fires a `DecryptionKeyCallback` to the registered handlers. +Within Spring-WS, the `KeyStoreCallbackHandler` class handles this particular callback. ===== Using `KeyStoreCallbackHandler` -As described in <>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` to handle 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 uses the `symmetricStore`. The following example uses `KeyStoreCallbackHandler`: +As described in <>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` to handle 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 uses the `symmetricStore`. +The following example uses `KeyStoreCallbackHandler`: ==== [source,xml] @@ -538,7 +664,10 @@ As described in <>, the `KeyStoreCallbackHa ==== Encryption -To encrypt outgoing SOAP messages, the security policy file should contain an `Encrypt` element. This element can further carry a `EncryptionTarget` element that 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. For more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565951[official reference] of the other elements. The following example uses an `Encrypt` element: +To encrypt outgoing SOAP messages, the security policy file should contain an `Encrypt` element. +This element can further carry a `EncryptionTarget` element that 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. +For more details, check the https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565951[official reference] of the other elements. +The following example uses an `Encrypt` element: ==== [source,xml] @@ -549,11 +678,15 @@ To encrypt outgoing SOAP messages, the security policy file should contain an `E ---- ==== -The `XwsSecurityInterceptor` fires an `EncryptionKeyCallback` to the registered handlers to retrieve the encryption information. Within Spring-WS, the `KeyStoreCallbackHandler` class handles this particular callback. +The `XwsSecurityInterceptor` fires an `EncryptionKeyCallback` to the registered handlers to retrieve the encryption information. +Within Spring-WS, the `KeyStoreCallbackHandler` class handles this particular callback. ===== Using `KeyStoreCallbackHandler` -As described in <>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` to handle various cryptographic callbacks, including encryption. For encryption based on public keys, the handler uses the `trustStore` property. For encryption based on symmetric keys, it uses `symmetricStore`. The following example uses `KeyStoreCallbackHandler`: +As described in <>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` to handle various cryptographic callbacks, including encryption. +For encryption based on public keys, the handler uses the `trustStore` property. +For encryption based on symmetric keys, it uses `symmetricStore`. +The following example uses `KeyStoreCallbackHandler`: ==== [source,xml] @@ -574,11 +707,14 @@ As described in <>, the `KeyStoreCallbackHa [[security-xws-exception-handling]] === Security Exception Handling -When a securement or validation action fails, the `XwsSecurityInterceptor` throws a `WsSecuritySecurementException` or `WsSecurityValidationException` respectively. These exceptions bypass the <> but are handled by the interceptor itself. +When a securement or validation action fails, the `XwsSecurityInterceptor` throws a `WsSecuritySecurementException` or `WsSecurityValidationException` respectively. +These exceptions bypass the <> but are handled by the interceptor itself. -`WsSecuritySecurementException` exceptions are handled by the `handleSecurementException` method of the `XwsSecurityInterceptor`. By default, this method logs an error and stops further processing of the message. +`WsSecuritySecurementException` exceptions are handled by the `handleSecurementException` method of the `XwsSecurityInterceptor`. +By default, this method logs an error and stops further processing of the message. -Similarly, `WsSecurityValidationException` exceptions are handled by the `handleValidationException` method of the `XwsSecurityInterceptor`. By default, this method creates a SOAP 1.1 Client or SOAP 1.2 sender fault and sends that back as a response. +Similarly, `WsSecurityValidationException` exceptions are handled by the `handleValidationException` method of the `XwsSecurityInterceptor`. +By default, this method creates a SOAP 1.1 Client or SOAP 1.2 sender fault and sends that back as a response. NOTE: Both `handleSecurementException` and `handleValidationException` are protected methods, which you can override to change their default behavior. @@ -589,15 +725,19 @@ The `Wss4jSecurityInterceptor` is an `EndpointInterceptor` (see <>. @@ -817,7 +971,9 @@ This section describes the various timestamp options available in the `Wss4jSecu ==== Validating Timestamps -To validate timestamps, add `Timestamp` to the `validationActions` property. You can override timestamp semantics specified by the initiator of the SOAP message by setting `timestampStrict` to `true` and specifying a server-side time-to-live in seconds (default: 300) by setting the `timeToLive` property. The interceptor always rejects already expired timestamps, whatever the value of `timeToLive` is. +To validate timestamps, add `Timestamp` to the `validationActions` property. +You can override timestamp semantics specified by the initiator of the SOAP message by setting `timestampStrict` to `true` and specifying a server-side time-to-live in seconds (default: 300) by setting the `timeToLive` property. +The interceptor always rejects already expired timestamps, whatever the value of `timeToLive` is. In the following example, the interceptor limits the timestamp validity window to 10 seconds, rejecting any valid timestamp token outside that window: @@ -835,7 +991,10 @@ In the following example, the interceptor limits the timestamp validity window t ==== Adding Timestamps -Adding `Timestamp` to the `securementActions` property generates a timestamp header in outgoing messages. The `timestampPrecisionInMilliseconds` property specifies whether the precision of the generated timestamp is in milliseconds. The default value is `true`. The following listing adds a timestamp: +Adding `Timestamp` to the `securementActions` property generates a timestamp header in outgoing messages. +The `timestampPrecisionInMilliseconds` property specifies whether the precision of the generated timestamp is in milliseconds. +The default value is `true`. +The following listing adds a timestamp: ==== [source,xml] @@ -854,7 +1013,8 @@ This section describes the various signature options available in the `Wss4jSecu ==== Verifying Signatures -To instruct the `Wss4jSecurityInterceptor`, `validationActions` must contain the `Signature` action. Additionally, the `validationSignatureCrypto` property must point to the keystore containing the public certificates of the initiator: +To instruct the `Wss4jSecurityInterceptor`, `validationActions` must contain the `Signature` action. +Additionally, the `validationSignatureCrypto` property must point to the keystore containing the public certificates of the initiator: ==== [source,xml] @@ -873,7 +1033,8 @@ To instruct the `Wss4jSecurityInterceptor`, `validationActions` must contain the ==== Signing Messages -Signing outgoing messages is enabled by adding the `Signature` action to the `securementActions`. The alias and the password of the private key to use are specified by the `securementUsername` and `securementPassword` properties, respectively. `securementSignatureCrypto` must point to the keystore that contains the private key: +Signing outgoing messages is enabled by adding the `Signature` action to the `securementActions`. +The alias and the password of the private key to use are specified by the `securementUsername` and `securementPassword` properties, respectively. `securementSignatureCrypto` must point to the keystore that contains the private key: ==== [source,xml] @@ -894,9 +1055,14 @@ Signing outgoing messages is enabled by adding the `Signature` action to the `se Furthermore, you can define the signature algorithm by setting the `securementSignatureAlgorithm` property. -You can customize the key identifier type to use by setting the `securementSignatureKeyIdentifier` property. Only `IssuerSerial` and `DirectReference` are valid for the signature. +You can customize the key identifier type to use by setting the `securementSignatureKeyIdentifier` property. +Only `IssuerSerial` and `DirectReference` are valid for the signature. -The `securementSignatureParts` property controls which part of the message is signed. The value of this property is a list of semicolon-separated element names that identify the elements to sign. The general form of a signature part is `{}{namespace}Element`. Note that the first empty brackets are used for encryption parts only. The default behavior is to sign the SOAP body. +The `securementSignatureParts` property controls which part of the message is signed. +The value of this property is a list of semicolon-separated element names that identify the elements to sign. +The general form of a signature part is `{}{namespace}Element`. +Note that the first empty brackets are used for encryption parts only. +The default behavior is to sign the SOAP body. The following example shows how to sign the `echoResponse` element in the Spring-WS echo sample: @@ -914,7 +1080,10 @@ If no other element in the request has a local name of `Body`, the SOAP namespac ==== Signature Confirmation -Signature confirmation is enabled by setting `enableSignatureConfirmation` to `true`. Note that the signature confirmation action spans over the request and the response. This implies that `secureResponse` and `validateRequest` must be set to `true` (which is the default value) even if there are no corresponding security actions. The following example sets the `enableSignatureConfirmation` property to `true`: +Signature confirmation is enabled by setting `enableSignatureConfirmation` to `true`. +Note that the signature confirmation action spans over the request and the response. +This implies that `secureResponse` and `validateRequest` must be set to `true` (which is the default value) even if there are no corresponding security actions. +The following example sets the `enableSignatureConfirmation` property to `true`: ==== [source,xml] @@ -938,9 +1107,12 @@ This section describes the various decryption and encryption options available i ==== Decryption -Decryption of incoming SOAP messages requires that the `Encrypt` action be added to the `validationActions` property. The rest of the configuration depends on the key information that appears in the message. (This is because WSS4J needs only a Crypto for encypted keys, whereas embedded key name validation is delegated to a callback handler.) +Decryption of incoming SOAP messages requires that the `Encrypt` action be added to the `validationActions` property. +The rest of the configuration depends on the key information that appears in the message. +(This is because WSS4J needs only a Crypto for encrypted keys, whereas embedded key name validation is delegated to a callback handler). -To decrypt messages with an embedded encrypted symmetric key (the `xenc:EncryptedKey` element), `validationDecryptionCrypto` needs to point to a keystore that contains the decryption private key. Additionally, `validationCallbackHandler` has to be injected with a {spring-ws-api}/soap/security/wss4j2/callback/KeyStoreCallbackHandler.html[`KeyStoreCallbackHandler`] that specifies the key's password: +To decrypt messages with an embedded encrypted symmetric key (the `xenc:EncryptedKey` element), `validationDecryptionCrypto` needs to point to a keystore that contains the decryption private key. +Additionally, `validationCallbackHandler` has to be injected with a {spring-ws-api}/soap/security/wss4j2/callback/KeyStoreCallbackHandler.html[`KeyStoreCallbackHandler`] that specifies the key's password: ==== [source,xml] @@ -962,7 +1134,8 @@ To decrypt messages with an embedded encrypted symmetric key (the `xenc:Encrypte ---- ==== -To support decryption of messages with an embedded key name ( `ds:KeyName` element), you can configure a `KeyStoreCallbackHandler` that points to the keystore with the symmetric secret key. The `symmetricKeyPassword` property indicates the key's password, the key name being the one specified by `ds:KeyName` element: +To support decryption of messages with an embedded key name ( `ds:KeyName` element), you can configure a `KeyStoreCallbackHandler` that points to the keystore with the symmetric secret key. +The `symmetricKeyPassword` property indicates the key's password, the key name being the one specified by `ds:KeyName` element: ==== [source,xml] @@ -987,7 +1160,11 @@ To support decryption of messages with an embedded key name ( `ds:KeyName` eleme ==== Encryption -Adding `Encrypt` to the `securementActions` enables encryption of outgoing messages. You can set the certificate's alias to use for the encryption by setting the `securementEncryptionUser` property. The keystore where the certificate resides is accessed through the `securementEncryptionCrypto` property. As encryption relies on public certificates, no password needs to be passed. The following example uses the `securementEncryptionCrypto` property: +Adding `Encrypt` to the `securementActions` enables encryption of outgoing messages. +You can set the certificate's alias to use for the encryption by setting the `securementEncryptionUser` property. +The keystore where the certificate resides is accessed through the `securementEncryptionCrypto` property. +As encryption relies on public certificates, no password needs to be passed. +The following example uses the `securementEncryptionCrypto` property: ==== [source,xml] @@ -1005,9 +1182,16 @@ Adding `Encrypt` to the `securementActions` enables encryption of outgoing messa ---- ==== -You can customize encryption in several ways: The key identifier type to use is defined by the `securementEncryptionKeyIdentifier` property. Possible values are `IssuerSerial`,`X509KeyIdentifier`, `DirectReference`,`Thumbprint`, `SKIKeyIdentifier`, and `EmbeddedKeyName`. +You can customize encryption in several ways: The key identifier type to use is defined by the `securementEncryptionKeyIdentifier` property. +Possible values are `IssuerSerial`,`X509KeyIdentifier`, `DirectReference`,`Thumbprint`, `SKIKeyIdentifier`, and `EmbeddedKeyName`. -If you choose the `EmbeddedKeyName` type, you need to specify the secret key to use for the encryption. The alias of the key is set in the `securementEncryptionUser` property, as for the other key identifier types. However, WSS4J requires a callback handler to fetch the secret key. Thus, you must provide `securementCallbackHandler` with a `KeyStoreCallbackHandler` that points 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, you can set the `securementEncryptionEmbeddedKeyName` with the desired value. In the next example, the outgoing message is encrypted with a key aliased `secretKey`, whereas `myKey` appears in `ds:KeyName` element: +If you choose the `EmbeddedKeyName` type, you need to specify the secret key to use for the encryption. +The alias of the key is set in the `securementEncryptionUser` property, as for the other key identifier types. +However, WSS4J requires a callback handler to fetch the secret key. +Thus, you must provide `securementCallbackHandler` with a `KeyStoreCallbackHandler` that points 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, you can set the `securementEncryptionEmbeddedKeyName` with the desired value. +In the next example, the outgoing message is encrypted with a key aliased `secretKey`, whereas `myKey` appears in `ds:KeyName` element: ==== [source,xml] @@ -1033,11 +1217,17 @@ If you choose the `EmbeddedKeyName` type, you need to specify the secret key to ---- ==== -The `securementEncryptionKeyTransportAlgorithm` property defines which algorithm to use to encrypt the generated symmetric key. Supported values are `http://www.w3.org/2001/04/xmlenc#rsa-1_5`, which is the default, and `http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p`. +The `securementEncryptionKeyTransportAlgorithm` property defines which algorithm to use to encrypt the generated symmetric key. +Supported values are `http://www.w3.org/2001/04/xmlenc#rsa-1_5`, which is the default, and `http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p`. -You can set the symmetric encryption algorithm to use by setting the `securementEncryptionSymAlgorithm` property. Supported values are `http://www.w3.org/2001/04/xmlenc#aes128-cbc` (default), `http://www.w3.org/2001/04/xmlenc#tripledes-cbc`, `http://www.w3.org/2001/04/xmlenc#aes256-cbc`, and `http://www.w3.org/2001/04/xmlenc#aes192-cbc`. +You can set the symmetric encryption algorithm to use by setting the `securementEncryptionSymAlgorithm` property. +Supported values are `http://www.w3.org/2001/04/xmlenc#aes128-cbc` (default), `http://www.w3.org/2001/04/xmlenc#tripledes-cbc`, `http://www.w3.org/2001/04/xmlenc#aes256-cbc`, and `http://www.w3.org/2001/04/xmlenc#aes192-cbc`. -Finally, the `securementEncryptionParts` property defines which parts of the message are encrypted. The value of this property is a list of semicolon-separated element names that identify the elements to encrypt. An encryption mode specifier and a namespace identification, each inside a pair of curly brackets, may precede each element name. The encryption mode specifier is either `{Content}` or `{Element}` See the W3C XML Encryption specification about the differences between Element and Content encryption. The following example identifies the `echoResponse` from the echo sample: +Finally, the `securementEncryptionParts` property defines which parts of the message are encrypted. +The value of this property is a list of semicolon-separated element names that identify the elements to encrypt. +An encryption mode specifier and a namespace identification, each inside a pair of curly brackets, may precede each element name. +The encryption mode specifier is either `{Content}` or `{Element}` See the W3C XML Encryption specification about the differences between Element and Content encryption. +The following example identifies the `echoResponse` from the echo sample: ==== [source,xml] @@ -1047,10 +1237,14 @@ Finally, the `securementEncryptionParts` property defines which parts of the mes ---- ==== -Be aware that the element name, the namespace identifier, and the encryption modifier are case-sensitive. You can omit the encryption modifier and the namespace identifier. If you do, the encryption mode defaults to `Content`, and the namespace is set to the SOAP namespace. +Be aware that the element name, the namespace identifier, and the encryption modifier are case-sensitive. +You can omit the encryption modifier and the namespace identifier. +If you do, 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` (case sensitive), as the namespace name. If no list is specified, the handler encrypts the SOAP Body in `Content` mode by default. +To specify an element without a namespace, use the value, `Null` (case sensitive), as the namespace name. +If no list is specified, the handler encrypts the SOAP Body in `Content` mode by default. === Security Exception Handling -The exception handling of the `Wss4jSecurityInterceptor` is identical to that of the `XwsSecurityInterceptor`. See <> for more information. +The exception handling of the `Wss4jSecurityInterceptor` is identical to that of the `XwsSecurityInterceptor`. +See <> for more information. diff --git a/spring-ws-docs/src/docs/asciidoc/server.adoc b/spring-ws-docs/src/docs/asciidoc/server.adoc index f3453353..48a60784 100644 --- a/spring-ws-docs/src/docs/asciidoc/server.adoc +++ b/spring-ws-docs/src/docs/asciidoc/server.adoc @@ -1,44 +1,66 @@ [[server]] = Creating a Web service with Spring-WS -Spring-WS's server-side support is designed around a `MessageDispatcher` that dispatches incoming messages to endpoints, with configurable endpoint mappings, response generation, and endpoint interception. Endpoints are typically annotated with the `@Endpoint` annotation and have one or more handling methods. These methods handle incoming XML request messages by inspecting parts of the message (typically the payload) and create some sort of response. You can annotate the method with another annotation, typically `@PayloadRoot`, to indicate what sort of messages it can handle. +Spring-WS server-side support is designed around a `MessageDispatcher` that dispatches incoming messages to endpoints, with configurable endpoint mappings, response generation, and endpoint interception. +Endpoints are typically annotated with the `@Endpoint` annotation and have one or more handling methods. +These methods handle incoming XML request messages by inspecting parts of the message (typically the payload) and create some sort of response. +You can annotate the method with another annotation, typically `@PayloadRoot`, to indicate what sort of messages it can handle. -Spring-WS's XML handling is extremely flexible. An endpoint can choose from a large number of XML handling libraries supported by Spring-WS, including: +Spring-WS XML handling is extremely flexible. +An endpoint can choose from a large number of XML handling libraries supported by Spring-WS, including: -* The DOM family: W3C DOM, JDOM, dom4j, and XOM -* SAX or StAX: For faster performance -* XPath: To extract information from the message -* Marshalling techniques (JAXB, Castor, XMLBeans, JiBX, or XStream): To convert the XML to objects and vice-versa +* The DOM family: W3C DOM, JDOM, dom4j, and XOM. +* SAX or StAX: For faster performance. +* XPath: To extract information from the message. +* Marshalling techniques (JAXB, Castor, XMLBeans, JiBX, or XStream): To convert the XML to objects and vice-versa. == The `MessageDispatcher` -The server-side of Spring-WS is designed around a central class that dispatches incoming XML messages to endpoints. Spring-WS's `MessageDispatcher` is extremely flexible, letting you use any sort of class as an endpoint, as long as it can be configured in the Spring IoC container. In a way, the message dispatcher resembles Spring's `DispatcherServlet`, the -"`Front Controller`" used in Spring Web MVC. +The server-side of Spring-WS is designed around a central class that dispatches incoming XML messages to endpoints. +Spring-WS `MessageDispatcher` is extremely flexible, letting you use any sort of class as an endpoint, as long as it can be configured in the Spring IoC container. +In a way, the message dispatcher resembles Spring's `DispatcherServlet`, the "Front Controller" used in Spring Web MVC. The following sequence diagram shows the processing and dispatching flow of the `MessageDispatcher`: image::images/sequence.png[align="center"] -When a `MessageDispatcher` is set up for use and a request comes in for that specific dispatcher, the `MessageDispatcher` starts processing the request. The following process describes how `MessageDispatcher` handles a request: +When a `MessageDispatcher` is set up for use and a request comes in for that specific dispatcher, the `MessageDispatcher` starts processing the request. +The following process describes how `MessageDispatcher` handles a request: -. The configured `EndpointMapping(s)` is searched for an appropriate endpoint. If an endpoint is found, the invocation chain associated with the endpoint (pre-processors, post-processors, and endpoints) is invoked to create a response. -. An appropriate adapter is found for the endpoint. The `MessageDispatcher` delegates to this adapter to invoke the endpoint. -. If a response is returned, it is sent on its way. If no response is returned (which could be due to a pre- or post-processor intercepting the request, for example, for security reasons), no response is sent. +. The configured `EndpointMapping(s)` is searched for an appropriate endpoint. +If an endpoint is found, the invocation chain associated with the endpoint (pre-processors, post-processors, and endpoints) is invoked to create a response. +. An appropriate adapter is found for the endpoint. +The `MessageDispatcher` delegates to this adapter to invoke the endpoint. +. If a response is returned, it is sent on its way. +If no response is returned (which could be due to a pre- or post-processor intercepting the request, for example, for security reasons), no response is sent. -Exceptions that are thrown during the handling of the request get picked up by any of the endpoint exception resolvers that are declared in the application context. Using these exception resolvers lets you define custom behaviors (such as returning a SOAP fault), in case such exceptions get thrown. +Exceptions that are thrown during the handling of the request get picked up by any of the endpoint exception resolvers that are declared in the application context. +Using these exception resolvers lets you define custom behaviors (such as returning a SOAP fault), in case such exceptions get thrown. -The `MessageDispatcher` has several properties for setting endpoint adapters, <>, <>. However, setting these properties is not required, since the dispatcher automatically detects all of the types that are registered in the application context. You should set these properties only when you need to override detection. +The `MessageDispatcher` has several properties for setting endpoint adapters, <>, <>. +However, setting these properties is not required, since the dispatcher automatically detects all the types that are registered in the application context. +You should set these properties only when you need to override detection. -The message dispatcher operates on a <> and not on a transport-specific input stream and output stream. As a result, transport-specific requests need to read into a `MessageContext`. For HTTP, this is done with a `WebServiceMessageReceiverHandlerAdapter` (which is a Spring Web `HandlerInterceptor`) so that the `MessageDispatcher` can be wired in a standard `DispatcherServlet`. There is a more convenient way to do this, however, which is shown in <>. +The message dispatcher operates on a <> and not on a transport-specific input stream and output stream. +As a result, transport-specific requests need to read into a `MessageContext`. +For HTTP, this is done with a `WebServiceMessageReceiverHandlerAdapter` (which is a Spring Web `HandlerInterceptor`) so that the `MessageDispatcher` can be wired in a standard `DispatcherServlet`. +There is a more convenient way to do this, however, which is shown in <>. == Transports -Spring-WS supports multiple transport protocols. The most common is the HTTP transport, for which a custom servlet is supplied, but you can also send messages over JMS and even email. +Spring-WS supports multiple transport protocols. +The most common is the HTTP transport, for which a custom servlet is supplied, but you can also send messages over JMS and even email. [[message-dispatcher-servlet]] === `MessageDispatcherServlet` -The `MessageDispatcherServlet` is a standard `Servlet` that conveniently extends from the standard Spring Web `DispatcherServlet` and wraps a `MessageDispatcher`. As a result, 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 must be mapped by a URL mapping in the same `web.xml` file. This is standard JavaEE servlet configuration. The following example shows such a `MessageDispatcherServlet` declaration and mapping: +The `MessageDispatcherServlet` is a standard `Servlet` that conveniently extends from the standard Spring Web `DispatcherServlet` and wraps a `MessageDispatcher`. +As a result, 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 must be mapped by a URL mapping in the same `web.xml` file. +This is standard JavaEE servlet configuration. +The following example shows such a `MessageDispatcherServlet` declaration and mapping: ==== [source,xml] @@ -60,10 +82,16 @@ The `MessageDispatcherServlet` is a standard `Servlet` that conveniently extends ---- ==== -In the preceding example, all requests are handled by the `spring-ws` `MessageDispatcherServlet`. This is only the first step in setting up Spring-WS, because the various component beans used by the Spring-WS framework also need to be configured. This configuration consists of standard Spring XML `` definitions. Because the `MessageDispatcherServlet` is a standard Spring `DispatcherServlet`, it -looks for a file named `[servlet-name]-servlet.xml` in the `WEB-INF` directory of your web application and creates the beans defined there in a Spring container. In the preceding example, it looks for `/WEB-INF/spring-ws-servlet.xml`. This file contains all the Spring-WS beans, such as endpoints, marshallers, and so on. +In the preceding example, all requests are handled by the `spring-ws` `MessageDispatcherServlet`. +This is only the first step in setting up Spring-WS, because the various component beans used by the Spring-WS framework also need to be configured. +This configuration consists of standard Spring XML `` definitions. +Because the `MessageDispatcherServlet` is a standard Spring `DispatcherServlet`, it looks for a file named `[servlet-name]-servlet.xml` in the `WEB-INF` directory of your web application and creates the beans defined there in a Spring container. +In the preceding example, it looks for `/WEB-INF/spring-ws-servlet.xml`. +This file contains all the Spring-WS beans, such as endpoints, marshallers, and so on. -As an alternative for `web.xml`, you can configure Spring-WS programmatically. For this purpose, Spring-WS provides a number of abstract base classes that extend the `WebApplicationInitializer` interface found in the Spring Framework. If you also use `@Configuration` classes for your bean definitions, you should extend the `AbstractAnnotationConfigMessageDispatcherServletInitializer`: +As an alternative for `web.xml`, you can configure Spring-WS programmatically. +For this purpose, Spring-WS provides a number of abstract base classes that extend the `WebApplicationInitializer` interface found in the Spring Framework. +If you also use `@Configuration` classes for your bean definitions, you should extend the `AbstractAnnotationConfigMessageDispatcherServletInitializer`: ==== [source,java] @@ -85,14 +113,20 @@ public class MyServletInitializer ---- ==== -In the preceding example, we tell Spring that endpoint bean definitions can be found in the `MyEndpointConfig` class (which is a `@Configuration` class). Other bean definitions (typically services, repositories, and so on) can be found in the `MyRootConfig` class. By default, the `AbstractAnnotationConfigMessageDispatcherServletInitializer` maps the servlet to two patterns: `/services` and `*.wsdl`, though you can change this by overriding the `getServletMappings()` method. For more details on the programmatic configuration of the `MessageDispatcherServlet`, refer to the Javadoc of {spring-ws-api}/transport/http/support/AbstractMessageDispatcherServletInitializer.html[`AbstractMessageDispatcherServletInitializer`] and {spring-ws-api}/transport/http/support/AbstractAnnotationConfigMessageDispatcherServletInitializer.html[`AbstractAnnotationConfigMessageDispatcherServletInitializer`]. +In the preceding example, we tell Spring that endpoint bean definitions can be found in the `MyEndpointConfig` class (which is a `@Configuration` class). +Other bean definitions (typically services, repositories, and so on) can be found in the `MyRootConfig` class. +By default, the `AbstractAnnotationConfigMessageDispatcherServletInitializer` maps the servlet to two patterns: `/services` and `*.wsdl`, though you can change this by overriding the `getServletMappings()` method. +For more details on the programmatic configuration of the `MessageDispatcherServlet`, refer to the Javadoc of {spring-ws-api}/transport/http/support/AbstractMessageDispatcherServletInitializer.html[`AbstractMessageDispatcherServletInitializer`] and {spring-ws-api}/transport/http/support/AbstractAnnotationConfigMessageDispatcherServletInitializer.html[`AbstractAnnotationConfigMessageDispatcherServletInitializer`]. [[server-automatic-wsdl-exposure]] ==== Automatic WSDL exposure -The `MessageDispatcherServlet` automatically detects any `WsdlDefinition` beans defined in its Spring container. All the `WsdlDefinition` detected beans are also exposed through a `WsdlDefinitionHandlerAdapter`. This is a convenient way to expose your WSDL to clients by defining some beans. +The `MessageDispatcherServlet` automatically detects any `WsdlDefinition` beans defined in its Spring container. +All the `WsdlDefinition` detected beans are also exposed through a `WsdlDefinitionHandlerAdapter`. +This is a convenient way to expose your WSDL to clients by defining some beans. -By way of an example, consider the following `` definition, defined in the Spring-WS configuration file (`/WEB-INF/[servlet-name]-servlet.xml`). Take notice of the value of the `id` attribute, because it is used when exposing the WSDL. +By way of an example, consider the following `` definition, defined in the Spring-WS configuration file (`/WEB-INF/[servlet-name]-servlet.xml`). +Take notice of the value of the `id` attribute, because it is used when exposing the WSDL. ==== [source,xml] @@ -122,11 +156,16 @@ http://localhost:8080/spring-ws/orders.wsdl ---- ==== -NOTE: All `WsdlDefinition` bean definitions are exposed by the `MessageDispatcherServlet` under their bean name with a suffix of`.wsdl`. So, if the bean name is `echo`, the host name is `server`, and the Servlet context (war name) is `spring-ws`, the WSDL can be found at `http://server/spring-ws/echo.wsdl`. +[NOTE] +==== +All `WsdlDefinition` bean definitions are exposed by the `MessageDispatcherServlet` under their bean name with a suffix of`.wsdl`. +So, if the bean name is `echo`, the host name is `server`, and the Servlet context (war name) is `spring-ws`, the WSDL can be found at `http://server/spring-ws/echo.wsdl`. +==== Another nice feature of the `MessageDispatcherServlet` (or more correctly the `WsdlDefinitionHandlerAdapter`) is that it can transform the value of the `location` of all the WSDL that it exposes to reflect the URL of the incoming request. -Note that this `location` transformation feature is off by default. To switch this feature on, you need to specify an initialization parameter to the `MessageDispatcherServlet`: +Note that this `location` transformation feature is off by default. +To switch this feature on, you need to specify an initialization parameter to the `MessageDispatcherServlet`: ==== [source,xml] @@ -155,7 +194,9 @@ If you use `AbstractAnnotationConfigMessageDispatcherServletInitializer`, enabli Consult the class-level Javadoc on the {spring-ws-api}/transport/http/WsdlDefinitionHandlerAdapter.html[`WsdlDefinitionHandlerAdapter`] class to learn more about the whole transformation process. -As an alternative to writing the WSDL by hand and exposing it with ``, Spring-WS can also generate a WSDL from an XSD schema. This is the approach shown in <>. The next application context snippet shows how to create such a dynamic WSDL file: +As an alternative to writing the WSDL by hand and exposing it with ``, Spring-WS can also generate a WSDL from an XSD schema. +This is the approach shown in <>. +The next application context snippet shows how to create such a dynamic WSDL file: ==== [source,xml] @@ -184,21 +225,38 @@ public DefaultWsdl11Definition orders() { ---- ==== -The `` element depends on the `DefaultWsdl11Definition` class. This definition class uses WSDL providers in the https://docs.spring.io/spring-ws/sites/1.5/apidocs/org/springframework/ws/wsdl/wsdl11/provider/package-summary.html[`org.springframework.ws.wsdl.wsdl11.provider`] package and the {spring-ws-api}/wsdl/wsdl11/ProviderBasedWsdl4jDefinition.html[`ProviderBasedWsdl4jDefinition`] class to generate a WSDL the first time it is requested. See the class-level Javadoc of these classes to see how you can extend this mechanism, if necessary. +The `` element depends on the `DefaultWsdl11Definition` class. +This definition class uses WSDL providers in the {spring-ws-api}/wsdl/wsdl11/provider/package-summary.html[`org.springframework.ws.wsdl.wsdl11.provider`] package and the {spring-ws-api}/wsdl/wsdl11/ProviderBasedWsdl4jDefinition.html[`ProviderBasedWsdl4jDefinition`] class to generate a WSDL the first time it is requested. +See the class-level Javadoc of these classes to see how you can extend this mechanism, if necessary. -The `DefaultWsdl11Definition` (and therefore, the `` tag) builds a WSDL from an 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 a 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 ``, respectively. It also builds a `portType`, `binding`, and `service` based on the operations. +The `DefaultWsdl11Definition` (and therefore, the `` tag) builds a WSDL from an 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 a 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 ``, 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, `` creates a `GetOrdersRequest` and `GetOrdersResponse` message and a `GetOrders` operation, which is put in a `Orders` port type. -To use multiple schemas, either by includes or imports, you can put Commons XMLSchema on the class path. If Commons XMLSchema is on the class path, the `` element follows all XSD imports and includes and inlines them in the WSDL as a single XSD. This greatly simplifies the deployment of the schemas, while still making it possible to edit them separately. +To use multiple schemas, either by includes or imports, you can put Commons XMLSchema on the class path. +If Commons XMLSchema is on the class path, the `` element follows all XSD imports and includes and inlines them in the WSDL as a single XSD. +This greatly simplifies the deployment of the schemas, while still making it possible to edit them separately. -WARNING: Even though it can be handy to create the WSDL at runtime from your XSDs, there are a couple of drawbacks to this approach. First, though we try to keep the WSDL generation process consistent between releases, there is still the possibility that it changes (slightly). Second, the generation is a bit slow, though, once generated, the WSDL is cached for later reference. +[WARNING] +==== +Even though it can be handy to create the WSDL at runtime from your XSDs, there are a couple of drawbacks to this approach. +First, though we try to keep the WSDL generation process consistent between releases, there is still the possibility that it changes (slightly). +Second, the generation is a bit slow, though, once generated, the WSDL is cached for later reference. +==== -Therefore, you should use `` only during the development stages of your project. We recommend using your browser to download the generated WSDL, store it in the project, and expose it with ``. This is the only way to be really sure that the WSDL does not change over time. +Therefore, you should use `` only during the development stages of your project. +We recommend using your browser to download the generated WSDL, store it in the project, and expose it with ``. +This is the only way to be really sure that the WSDL does not change over time. === Wiring up Spring-WS in a `DispatcherServlet` -As an alternative to the `MessageDispatcherServlet`, you can wire up a `MessageDispatcher` in a standard, Spring-Web MVC `DispatcherServlet`. By default, the `DispatcherServlet` can delegate only to `Controllers`, but we can instruct it to delegate to a `MessageDispatcher` by adding a `WebServiceMessageReceiverHandlerAdapter` to the servlet's web application context: +As an alternative to the `MessageDispatcherServlet`, you can wire up a `MessageDispatcher` in a standard, Spring-Web MVC `DispatcherServlet`. +By default, the `DispatcherServlet` can delegate only to `Controllers`, but we can instruct it to delegate to a `MessageDispatcher` by adding a `WebServiceMessageReceiverHandlerAdapter` to the servlet's web application context: ==== [source,xml] @@ -221,7 +279,8 @@ As an alternative to the `MessageDispatcherServlet`, you can wire up a `MessageD ---- ==== -Note that, by explicitly adding the `WebServiceMessageReceiverHandlerAdapter`, the dispatcher servlet does not load the default adapters and is unable to handle standard Spring-MVC `@Controllers`. Therefore, we add the `RequestMappingHandlerAdapter` at the end. +Note that, by explicitly adding the `WebServiceMessageReceiverHandlerAdapter`, the dispatcher servlet does not load the default adapters and is unable to handle standard Spring-MVC `@Controllers`. +Therefore, we add the `RequestMappingHandlerAdapter` at the end. In a similar fashion, you can wire a `WsdlDefinitionHandlerAdapter` to make sure the `DispatcherServlet` can handle implementations of the `WsdlDefinition` interface: @@ -257,7 +316,10 @@ In a similar fashion, you can wire a `WsdlDefinitionHandlerAdapter` to make sure === JMS transport -Spring-WS supports server-side JMS handling through the JMS functionality provided in the Spring framework. Spring-WS provides the `WebServiceMessageListener` to plug in to a `MessageListenerContainer`. This message listener requires a `WebServiceMessageFactory` and `MessageDispatcher` to operate. The following configuration example shows this: +Spring-WS supports server-side JMS handling through the JMS functionality provided in the Spring framework. +Spring-WS provides the `WebServiceMessageListener` to plug in to a `MessageListenerContainer`. +This message listener requires a `WebServiceMessageFactory` and `MessageDispatcher` to operate. +The following configuration example shows this: ==== [source,xml] @@ -297,11 +359,20 @@ Spring-WS supports server-side JMS handling through the JMS functionality provid === Email Transport -In addition to HTTP and JMS, Spring-WS also provides server-side email handling. This functionality is provided through the `MailMessageReceiver` class. This class monitors a POP3 or IMAP folder, converts the email to a `WebServiceMessage`, and sends any response by using SMTP. You can configure the host names through the `storeUri`, which indicates the mail folder to monitor for requests (typically a POP3 or IMAP folder), and a `transportUri`, which indicates the server to use for sending responses (typically an SMTP server). +In addition to HTTP and JMS, Spring-WS also provides server-side email handling. +This functionality is provided through the `MailMessageReceiver` class. +This class monitors a POP3 or IMAP folder, converts the email to a `WebServiceMessage`, and sends any response by using SMTP. +You can configure the host names through the `storeUri`, which indicates the mail folder to monitor for requests (typically a POP3 or IMAP folder), and a `transportUri`, which indicates the server to use for sending responses (typically an SMTP server). -You can configure how the `MailMessageReceiver` monitors incoming messages with a pluggable strategy: the `MonitoringStrategy`. By default, a polling strategy is used, where the incoming folder is polled for new messages every five minutes. You can change this interval by setting the `pollingInterval` property on the strategy. By default, all `MonitoringStrategy` implementations delete the handled messages. You can change this setting by setting the `deleteMessages` property. +You can configure how the `MailMessageReceiver` monitors incoming messages with a pluggable strategy: the `MonitoringStrategy`. +By default, a polling strategy is used, where the incoming folder is polled for new messages every five minutes. +You can change this interval by setting the `pollingInterval` property on the strategy. +By default, all `MonitoringStrategy` implementations delete the handled messages. +You can change this setting by setting the `deleteMessages` property. -As an alternative to the polling approaches, which are quite inefficient, there is a monitoring strategy that uses IMAP IDLE. The IDLE command is an optional expansion of the IMAP email protocol that lets the mail server send new message updates to the `MailMessageReceiver` asynchronously. If you use an IMAP server that supports the IDLE command, you can plug the `ImapIdleMonitoringStrategy` into the `monitoringStrategy` property. +As an alternative to the polling approaches, which are quite inefficient, there is a monitoring strategy that uses IMAP IDLE. +The IDLE command is an optional expansion of the IMAP email protocol that lets the mail server send new message updates to the `MailMessageReceiver` asynchronously. +If you use an IMAP server that supports the IDLE command, you can plug the `ImapIdleMonitoringStrategy` into the `monitoringStrategy` property. The following piece of configuration shows how to use the server-side email support, overriding the default polling interval to check every 30 seconds (30.000 milliseconds): @@ -343,11 +414,17 @@ The following piece of configuration shows how to use the server-side email supp NOTE: This should only be used for testing purposes. -Spring-WS provides a transport based on Sun's JRE 1.6 http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/index.html[HTTP server]. The embedded HTTP Server is a standalone server that is simple to configure. It offers a lighter alternative to conventional servlet containers. +Spring-WS provides a transport based on Sun's JRE http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/index.html[HTTP server]. +The embedded HTTP Server is a standalone server that is simple to configure. +It offers a lighter alternative to conventional servlet containers. -When using the embedded HTTP server, you need no external deployment descriptor (`web.xml`). You need only define an instance of the server and configure it to handle incoming requests. `SimpleHttpServerFactoryBean` wires things up, and the most important property is `contexts`, which maps context paths to corresponding `HttpHandler` instances. +When using the embedded HTTP server, you need no external deployment descriptor (`web.xml`). +You need only define an instance of the server and configure it to handle incoming requests. +`SimpleHttpServerFactoryBean` wires things up, and the most important property is `contexts`, which maps context paths to corresponding `HttpHandler` instances. -Spring-WS provides two implementations of the `HttpHandler` interface: {spring-ws-api}/transport/http/WsdlDefinitionHttpHandler.html[`WsdlDefinitionHttpHandler`] and {spring-ws-api}/transport/http/WebServiceMessageReceiverHttpHandler.html[`WebServiceMessageReceiverHttpHandler`]. The former maps an incoming GET request to a `WsdlDefinition`. The latter is responsible for handling POST requests for web services messages and, thus, needs a `WebServiceMessageFactory` (typically a `SaajSoapMessageFactory`) and a `WebServiceMessageReceiver` (typically the `SoapMessageDispatcher`) to accomplish its task. +Spring-WS provides two implementations of the `HttpHandler` interface: {spring-ws-api}/transport/http/WsdlDefinitionHttpHandler.html[`WsdlDefinitionHttpHandler`] and {spring-ws-api}/transport/http/WebServiceMessageReceiverHttpHandler.html[`WebServiceMessageReceiverHttpHandler`]. +The former maps an incoming GET request to a `WsdlDefinition`. +The latter is responsible for handling POST requests for web services messages and, thus, needs a `WebServiceMessageFactory` (typically a `SaajSoapMessageFactory`) and a `WebServiceMessageReceiver` (typically the `SoapMessageDispatcher`) to accomplish its task. To draw parallels with the servlet world, the `contexts` property plays the role of servlet mappings in `web.xml` and the `WebServiceMessageReceiverHttpHandler` is the equivalent of a `MessageDispatcherServlet`. @@ -391,7 +468,8 @@ The following snippet shows a configuration example of the HTTP server transport === XMPP transport -Spring-WS has support for XMPP, otherwise known as Jabber. The support is based on the https://www.igniterealtime.org/projects/smack/index.jsp[Smack] library. +Spring-WS has support for XMPP, otherwise known as Jabber. +The support is based on the https://www.igniterealtime.org/projects/smack/index.jsp[Smack] library. Spring-WS support for XMPP is very similar to the other transports: There is a a `XmppMessageSender` for the `WebServiceTemplate` and a `XmppMessageReceiver` to use with the `MessageDispatcher`. @@ -433,14 +511,21 @@ The following example shows how to set up the server-side XMPP components: === MTOM -https://en.wikipedia.org/wiki/Message_Transmission_Optimization_Mechanism[MTOM] is the mechanism for sending binary data to and from Web Services. You can look at how to implement this with Spring WS through the https://github.com/spring-projects/spring-ws-samples/tree/main/mtom[MTOM sample]. +https://en.wikipedia.org/wiki/Message_Transmission_Optimization_Mechanism[MTOM] is the mechanism for sending binary data to and from Web Services. +You can look at how to implement this with Spring WS through the https://github.com/spring-projects/spring-ws-samples/tree/main/mtom[MTOM sample]. [[server-endpoints]] == 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 (typically) invoke a method on the business service. The result of that service invocation is represented as a response message. Spring-WS has a wide variety of endpoints and uses various ways to handle the XML message and to create a response. +Endpoints are the central concept in Spring-WS 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 (typically) invoke a method on the business service. +The result of that service invocation is represented as a response message. +Spring-WS has a wide variety of endpoints and uses various ways to handle the XML message and to create a response. -You can 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, and others). You can indicate the sort of messages a method can handle by using another annotation (typically `@PayloadRoot`). +You can 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, and others). +You can indicate the sort of messages a method can handle by using another annotation (typically `@PayloadRoot`). Consider the following sample endpoint: @@ -482,11 +567,19 @@ public class AnnotationOrderEndpoint { ---- <1> The class is annotated with `@Endpoint`, marking it as a Spring-WS endpoint. -<2> The `order` method takes an `Element` (annotated with `@RequestPayload`) as a parameter. 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. +<2> The `order` method takes an `Element` (annotated with `@RequestPayload`) as a parameter. +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, see <>. -<3> The `getOrder` method takes an `OrderRequest` (also annotated with `@RequestPayload`) as a parameter. This parameter is a JAXB2-supported object (it is annotated with `@XmlRootElement`). This means that the payload of the message is passed to this method as a unmarshalled object. The `SoapHeader` type is also given as a parameter. On invocation, this parameter contains 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. +<3> The `getOrder` method takes an `OrderRequest` (also annotated with `@RequestPayload`) as a parameter. +This parameter is a JAXB2-supported object (it is annotated with `@XmlRootElement`). +This means that the payload of the message is passed to this method as a unmarshalled object. +The `SoapHeader` type is also given as a parameter. +On invocation, this parameter contains 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, see <>. -<4> 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 is invoked for requests with a `orderRequest` local name and a `http://samples` namespace URI. The order method is invoked for requests with a `order` local name. +<4> 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 is invoked for requests with a `orderRequest` local name and a `http://samples` namespace URI. +The order method is invoked for requests with a `order` local name. For more information about `@PayloadRoot`, see <>. ==== @@ -497,13 +590,13 @@ To enable the support for `@Endpoint` and related Spring-WS annotations, you nee ---- - ** + ---- @@ -514,7 +607,7 @@ Alternatively, if you use `@Configuration` classes instead of Spring XML, you ca ==== [source,java,subs="verbatim,quotes"] ---- -*@EnableWs* +@EnableWs @Configuration public class EchoConfig { @@ -550,16 +643,26 @@ public class MyConfiguration extends WsConfigurerAdapter { 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. That is, one instance of the bean definition is created per container. Being a singleton implies that more than one thread can use it at the same time, so the endpoint has to be thread safe. If you want to use a different scope, such as prototype, see the {spring-framework-docs}/core/beans/factory-scopes.html#beans-factory-scopes-other-injection[Spring Reference documentation]. +[NOTE] +==== +Endpoints, like any other Spring Bean, are scoped as a singleton by default. +That is, one instance of the bean definition is created per container. +Being a singleton implies that more than one thread can use it at the same time, so the endpoint has to be thread safe. +If you want to use a different scope, such as prototype, see the {spring-framework-docs}/core/beans/factory-scopes.html#beans-factory-scopes-other-injection[Spring Reference documentation]. +==== - Note that all abstract base classes provided in Spring-WS are thread safe, unless otherwise indicated in the class-level Javadoc. +Note that all abstract base classes provided in Spring-WS are thread safe, unless otherwise indicated in the class-level Javadoc. [[server-atEndpoint-methods]] === `@Endpoint` handling methods -For an endpoint to actually handle incoming XML messages, it needs to have one or more handling methods. Handling methods can take wide range of parameters and return types. However, they typically have one parameter that contains the message payload, and they return the payload of the response message (if any). This section covers which parameter and return types are supported. +For an endpoint to actually handle incoming XML messages, it needs to have one or more handling methods. +Handling methods can take wide range of parameters and return types. +However, they typically have one parameter that contains the message payload, and they return the payload of the response message (if any). +This section covers which parameter and return types are supported. -To indicate what sort of messages a method can handle, the method is typically annotated with either the `@PayloadRoot` or the `@SoapAction` annotation. You can learn more about these annotations in <>. +To indicate what sort of messages a method can handle, the method is typically annotated with either the `@PayloadRoot` or the `@SoapAction` annotation. +You can learn more about these annotations in <>. The following example shows a handling method: @@ -574,15 +677,21 @@ public void order(@RequestPayload Element orderElement) { ---- ==== -The `order` method takes an `Element` (annotated with `@RequestPayload`) as a parameter. 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. +The `order` method takes an `Element` (annotated with `@RequestPayload`) as a parameter. +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. ==== 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 has a single parameter that maps to the payload of the message, but it can also map to other parts of the request message, such as a SOAP header. This section describes the parameters you can use in your handling method signatures. +The handling method typically has one or more parameters that refer to various parts of the incoming XML message. +Most commonly, the handling method has a single parameter that maps to the payload of the message, but it can also map to other parts of the request message, such as a SOAP header. +This section describes the parameters you can use in your handling method signatures. -To map a parameter to the payload of the request message, you 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. +To map a parameter to the payload of the request message, you 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. +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. [cols="4", options="header"] |=== @@ -647,7 +756,8 @@ The following table describes the supported parameter types. It shows the suppor | Enabled when the `unmarshaller` attribute of `` is specified. |=== -The next few examples show possible method signatures. The following method is invoked with the payload of the request message as a DOM `org.w3c.dom.Element`: +The next few examples show possible method signatures. +The following method is invoked with the payload of the request message as a DOM `org.w3c.dom.Element`: ==== [source,java] @@ -656,7 +766,8 @@ public void handle(@RequestPayload Element element) ---- ==== -The following method is invoked with the payload of the request message as a `javax.xml.transform.dom.DOMSource`. The `header` parameter is bound to the SOAP header of the request message. +The following method is invoked with the payload of the request message as a `javax.xml.transform.dom.DOMSource`. +The `header` parameter is bound to the SOAP header of the request message. ==== [source,java] @@ -665,7 +776,9 @@ public void handle(@RequestPayload DOMSource domSource, SoapHeader header) ---- ==== -The following method is 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 <> is passed on as the third parameter. +The following method is 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 <> is passed on as the third parameter. ==== [source,java] @@ -674,12 +787,16 @@ public void handle(@RequestPayload MyJaxb2Object requestObject, @RequestPayload ---- ==== -As you can see, there are a lot of possibilities when it comes to defining how to handle method signatures. You can even extend this mechanism to support your own parameter types. See the Javadoc of {spring-ws-api}/server/endpoint/adapter/DefaultMethodEndpointAdapter.html[`DefaultMethodEndpointAdapter`] and {spring-ws-api}/server/endpoint/adapter/method/MethodArgumentResolver.html[`MethodArgumentResolver`] to see how. +As you can see, there are a lot of possibilities when it comes to defining how to handle method signatures. +You can even extend this mechanism to support your own parameter types. +See the Javadoc of {spring-ws-api}/server/endpoint/adapter/DefaultMethodEndpointAdapter.html[`DefaultMethodEndpointAdapter`] and {spring-ws-api}/server/endpoint/adapter/method/MethodArgumentResolver.html[`MethodArgumentResolver`] to see how. [[server-xpath-param]] ===== `@XPathParam` -One parameter type needs some extra explanation: `@XPathParam`. The idea here is that you annotate one or more method parameters with an XPath expression and that each such annotated parameter is bound to the evaluation of the expression. The following example shows how to do so: +One parameter type needs some extra explanation: `@XPathParam`. +The idea here is that you annotate one or more method parameters with an XPath expression and that each such annotated parameter is bound to the evaluation of the expression. +The following example shows how to do so: ==== [source,java,subs="verbatim,quotes"] @@ -713,25 +830,33 @@ public class AnnotationOrderEndpoint { ---- ==== -Since we use the `s` prefix 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. +Since we use the `s` prefix 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. By using the `@XPathParam`, you can bind to all the data types supported by XPath: -* `boolean` or `Boolean` -* `double` or `Double` -* `String` -* `Node` -* `NodeList` +* `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 {spring-framework-docs}/core/validation/convert.html#core-convert-ConversionService-API[conversion service]. ==== 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 declare a `void` return type. Most commonly, the return type is used to create the payload of the response message. However, you can also map to other parts of the response message. This section describes the return types you can use in your handling method signatures. +To send a response message, the handling needs to specify a return type. +If no response message is required, the method can declare a `void` return type. +Most commonly, the return type is used to create the payload of the response message. +However, you can also map to other parts of the response message. +This section describes the return types you can use in your handling method signatures. -To map the return value to the payload of the response message, you 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. +To map the return value to the payload of the response message, you 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. +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. [cols="4", options="header"] @@ -782,31 +907,48 @@ The following table describes the supported return types. It shows the supported | Enabled when the `marshaller` attribute of `` is specified. |=== -There are a lot of possibilities when it comes to defining handling method signatures. It is even possible to extend this mechanism to support your own parameter types. See the class-level Javadoc of {spring-ws-api}/server/endpoint/adapter/DefaultMethodEndpointAdapter.html[`DefaultMethodEndpointAdapter`] and {spring-ws-api}/server/endpoint/adapter/method/MethodReturnValueHandler.html[`MethodReturnValueHandler`] to see how. +There are a lot of possibilities when it comes to defining handling method signatures. +It is even possible to extend this mechanism to support your own parameter types. +See the class-level Javadoc of {spring-ws-api}/server/endpoint/adapter/DefaultMethodEndpointAdapter.html[`DefaultMethodEndpointAdapter`] and {spring-ws-api}/server/endpoint/adapter/method/MethodReturnValueHandler.html[`MethodReturnValueHandler`] to see how. [[server-endpoint-mapping]] == Endpoint mappings -The endpoint mapping is responsible for mapping incoming messages to appropriate endpoints. Some endpoint mappings are enabled by default -- for example, the `PayloadRootAnnotationMethodEndpointMapping` or the `SoapActionAnnotationMethodEndpointMapping`. However, we first need to examine the general concept of an `EndpointMapping`. +The endpoint mapping is responsible for mapping incoming messages to appropriate endpoints. +Some endpoint mappings are enabled by default -- for example, the `PayloadRootAnnotationMethodEndpointMapping` or the `SoapActionAnnotationMethodEndpointMapping`. +However, we first need to examine the general concept of an `EndpointMapping`. -An `EndpointMapping` delivers a `EndpointInvocationChain`, which contains the endpoint that matches the incoming request and may also contain a list of endpoint interceptors that are applied to the request and response. When a request comes in, the `MessageDispatcher` hands it over to the endpoint mapping to let it inspect the request and come up with an appropriate `EndpointInvocationChain`. Then the `MessageDispatcher` invokes the endpoint and any interceptors in the chain. +An `EndpointMapping` delivers a `EndpointInvocationChain`, which contains the endpoint that matches the incoming request and may also contain a list of endpoint interceptors that are applied to the request and response. +When a request comes in, the `MessageDispatcher` hands it over to the endpoint mapping to let it inspect the request and come up with an appropriate `EndpointInvocationChain`. +Then the `MessageDispatcher` invokes the endpoint and any interceptors in the chain. -The concept of configurable endpoint mappings that can optionally contain interceptors (which can, in turn, manipulate the request, the response, or both) is extremely powerful. A lot of supporting functionality can be built into custom `EndpointMapping` implementations. For example, a custom endpoint mapping could choose an endpoint based not only on the contents of a message but also on a specific SOAP header (or, indeed, multiple SOAP headers). +The concept of configurable endpoint mappings that can optionally contain interceptors (which can, in turn, manipulate the request, the response, or both) is extremely powerful. +A lot of supporting functionality can be built into custom `EndpointMapping` implementations. +For example, a custom endpoint mapping could choose an endpoint based not only on the contents of a message but also on a specific SOAP header (or, indeed, multiple SOAP headers). -Most endpoint mappings inherit from the `AbstractEndpointMapping`, which offers an '`interceptors`' property, which is the list of interceptors to use. `EndpointInterceptors` are discussed in <>. Additionally, there is the `defaultEndpoint`, which is the default endpoint to use when this endpoint mapping does not result in a matching endpoint. +Most endpoint mappings inherit from the `AbstractEndpointMapping`, which offers an '`interceptors`' property, which is the list of interceptors to use. `EndpointInterceptors` are discussed in <>. +Additionally, there is the `defaultEndpoint`, which is the default endpoint to use when this endpoint mapping does not result in a matching endpoint. -As explained in <>, the `@Endpoint` style lets you handle multiple requests in one endpoint class. This is the responsibility of the `MethodEndpointMapping`. This mapping determines which method is to be invoked for an incoming request message. +As explained in <>, the `@Endpoint` style lets you handle multiple requests in one endpoint class. +This is the responsibility of the `MethodEndpointMapping`. +This mapping determines which method is to be invoked for an incoming request message. There are two endpoint mappings that can direct requests to methods: the `PayloadRootAnnotationMethodEndpointMapping` and the `SoapActionAnnotationMethodEndpointMapping` You can enable both methods by using `` in your application context. -The `PayloadRootAnnotationMethodEndpointMapping` uses the `@PayloadRoot` annotation, with the `localPart` and `namespace` elements, to mark methods with a particular qualified name. Whenever a message comes in with this qualified name for the payload root element, the method is invoked. +The `PayloadRootAnnotationMethodEndpointMapping` uses the `@PayloadRoot` annotation, with the `localPart` and `namespace` elements, to mark methods with a particular qualified name. +Whenever a message comes in with this qualified name for the payload root element, the method is invoked. -Alternatively, the `SoapActionAnnotationMethodEndpointMapping` uses the `@SoapAction` annotation to mark methods with a particular SOAP Action. Whenever a message comes in with this `SOAPAction` header, the method is invoked. +Alternatively, the `SoapActionAnnotationMethodEndpointMapping` uses the `@SoapAction` annotation to mark methods with a particular SOAP Action. +Whenever a message comes in with this `SOAPAction` header, the method is invoked. [[server-ws-addressing]] === WS-Addressing -WS-Addressing specifies a transport-neutral routing mechanism. It is based on the `To` and `Action` SOAP headers, which indicate the destination and intent of the SOAP message, respectively. Additionally, WS-Addressing lets you define a return address (for normal messages and for faults) and a unique message identifier, which can be used for correlation. For more information on WS-Addressing, see https://en.wikipedia.org/wiki/WS-Addressing. The following example shows a WS-Addressing message: +WS-Addressing specifies a transport-neutral routing mechanism. +It is based on the `To` and `Action` SOAP headers, which indicate the destination and intent of the SOAP message, respectively. +Additionally, WS-Addressing lets you define a return address (for normal messages and for faults) and a unique message identifier, which can be used for correlation. +For more information on WS-Addressing, see https://en.wikipedia.org/wiki/WS-Addressing. +The following example shows a WS-Addressing message: ==== [source,xml] @@ -830,15 +972,19 @@ WS-Addressing specifies a transport-neutral routing mechanism. It is based on th ---- ==== -In the preceding 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 a reply-to address. By default, this address is the "`anonymous`" address, indicating that a response should be sent by using the same channel as the request (that is, the HTTP response), but it can also be another address, as indicated in this example. +In the preceding 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 a reply-to address. +By default, this address is the "anonymous" address, indicating that a response should be sent by using the same channel as the request (that is, 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. By using this mapping, you associate WS-Addressing actions with endpoints, similar to the `SoapActionAnnotationMethodEndpointMapping` described earlier. +In Spring-WS, WS-Addressing is implemented as an endpoint mapping. +By using this mapping, you associate WS-Addressing actions with endpoints, similar to the `SoapActionAnnotationMethodEndpointMapping` described earlier. ==== Using `AnnotationActionEndpointMapping` The `AnnotationActionEndpointMapping` is similar to the `SoapActionAnnotationMethodEndpointMapping` but uses WS-Addressing headers instead of the SOAP Action transport header. -To use the `AnnotationActionEndpointMapping`, annotate the handling methods with the `@Action` annotation, similar to the `@PayloadRoot` and `@SoapAction` annotations described in <> and <>. The following example shows how to do so: +To use the `AnnotationActionEndpointMapping`, annotate the handling methods with the `@Action` annotation, similar to the `@PayloadRoot` and `@SoapAction` annotations described in <> and <>. +The following example shows how to do so: ==== [source,java] @@ -871,20 +1017,30 @@ public class AnnotationOrderEndpoint { ---- ==== -The preceding mapping routes requests that have a WS-Addressing `Action` of `http://samples/RequestOrder` to the `getOrder` method. Requests with `http://samples/CreateOrder` are routed to the `order` method.. +The preceding mapping routes requests that have a WS-Addressing `Action` of `http://samples/RequestOrder` to the `getOrder` method. +Requests with `http://samples/CreateOrder` are 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. +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. +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 non-anonymous, out-of-bound addresses. You can set `MessageSender` implementations in this property, the same as you would on the `WebServiceTemplate`. See <>. +Finally, there is the `messageSenders` property, which is required for sending response messages to non-anonymous, out-of-bound addresses. +You can set `MessageSender` implementations in this property, the same as you would on the `WebServiceTemplate`. +See <>. [[server-endpoint-interceptor]] === Intercepting Requests -- the `EndpointInterceptor` Interface -The endpoint mapping mechanism has the notion of endpoint interceptors. These can be extremely useful when you want to apply specific functionality to certain requests -- for example, dealing with security-related SOAP headers or the logging of request and response message. +The endpoint mapping mechanism has the notion of endpoint interceptors. +These can be extremely useful when you want to apply specific functionality to certain requests -- for example, dealing with security-related SOAP headers or the logging of request and response message. -Endpoint interceptors are typically defined by using a `` element in your application context. In this element, you can define endpoint interceptor beans that apply to all endpoints defined in that application context. Alternatively, you can use `` or `` elements to specify for which payload root name or SOAP action the interceptor should apply. The following example shows how to do so: +Endpoint interceptors are typically defined by using a `` element in your application context. +In this element, you can define endpoint interceptor beans that apply to all endpoints defined in that application context. +Alternatively, you can use `` or `` elements to specify for which payload root name or SOAP action the interceptor should apply. +The following example shows how to do so: ==== [source,xml] @@ -904,7 +1060,12 @@ Endpoint interceptors are typically defined by using a `` elem ---- ==== -In the preceding example, we define one "`global`" interceptor (`MyGlobalInterceptor`) that intercepts all requests and responses. We also define an interceptor that applies only to XML messages that have the `http://www.example.com` as a payload root namespace. We could have defined a `localPart` attribute in addition to the `namespaceUri` to further limit the messages the to which interceptor applies. 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 `` element. You can use bean references anywhere inside the `` element. +In the preceding example, we define one "`global`" interceptor (`MyGlobalInterceptor`) that intercepts all requests and responses. +We also define an interceptor that applies only to XML messages that have the `http://www.example.com` as a payload root namespace. +We could have defined a `localPart` attribute in addition to the `namespaceUri` to further limit the messages to which the interceptor applies. +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 the `` element. +You can use bean references anywhere inside the `` element. When you use `@Configuration` classes, you can extend from `WsConfigurerAdapter` to add interceptors: @@ -924,15 +1085,28 @@ public class MyWsConfiguration extends WsConfigurerAdapter { ---- ==== -Interceptors must implement {spring-ws-api}/server/EndpointInterceptor.html[`EndpointInterceptor`]. This interface defines three methods, one that can be used for handling the request message *before* the actual endpoint is processed, one that can be used for handling a normal response message, and one that can be used for handling fault messages. The second two are called *after* the endpoint is processed. These three methods should provide enough flexibility to do all kinds of pre- and post-processing. +Interceptors must implement {spring-ws-api}/server/EndpointInterceptor.html[`EndpointInterceptor`]. +This interface defines three methods, one that can be used for handling the request message *before* the actual endpoint is processed, one that can be used for handling a normal response message, and one that can be used for handling fault messages. +The second two are called *after* the endpoint is processed. +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 processing 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 processing 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. +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 processing 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 processing 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 that you can use in your Web service. Additionally, there is the `XwsSecurityInterceptor`, which is described in <>. +There are a number of standard `EndpointInterceptor` implementations that you can use in your Web service. +Additionally, there is the `XwsSecurityInterceptor`, which is described in <>. ==== `PayloadLoggingInterceptor` and `SoapEnvelopeLoggingInterceptor` -When developing a web service, it can be useful to log the incoming and outgoing XML messages. Spring WS facilitates this with the `PayloadLoggingInterceptor` and `SoapEnvelopeLoggingInterceptor` classes. The former logs only the payload of the message. The latter logs the entire SOAP envelope, including SOAP headers. The following example shows how to define the `PayloadLoggingInterceptor` in an endpoint mapping: +When developing a web service, it can be useful to log the incoming and outgoing XML messages. +Spring WS facilitates this with the `PayloadLoggingInterceptor` and `SoapEnvelopeLoggingInterceptor` classes. +The former logs only the payload of the message. +The latter logs the entire SOAP envelope, including SOAP headers. +The following example shows how to define the `PayloadLoggingInterceptor` in an endpoint mapping: ==== [source,xml] @@ -949,16 +1123,22 @@ You could use the `WsConfigurerAdapter` approach, as described earlier, for the ==== `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, responses, or both. +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, responses, or both. [NOTE] ==== -While request validation may sound like a good idea, it 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 fulfill 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." +While request validation may sound like a good idea, it 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 fulfill 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." ==== -The following example 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 by setting the `schemas` property. +The following example 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 by setting the `schemas` property. ==== [source,xml] @@ -976,7 +1156,9 @@ Of course, you could use the `WsConfigurerAdapter` approach, as described earlie ==== Using `PayloadTransformingInterceptor` -To transform the payload to another XML format, Spring-WS offers the `PayloadTransformingInterceptor`. This endpoint interceptor is based on XSLT style sheets and is especially useful when supporting multiple versions of a web service, because you can transform the older message format to the newer format. The following example uses the `PayloadTransformingInterceptor`: +To transform the payload to another XML format, Spring-WS offers the `PayloadTransformingInterceptor`. +This endpoint interceptor is based on XSLT style sheets and is especially useful when supporting multiple versions of a web service, because you can transform the older message format to the newer format. +The following example uses the `PayloadTransformingInterceptor`: ==== [source,xml] @@ -989,22 +1171,32 @@ To transform the payload to another XML format, Spring-WS offers the `PayloadTra ---- ==== -In the preceding example, we transform requests by using `/WEB-INF/oldRequests.xslt` and response messages by using `/WEB-INF/oldResponses.xslt`. Note that, since endpoint interceptors are registered at the endpoint-mapping level, you can create an endpoint mapping that applies to the "`old style`" messages and add the interceptor to that mapping. Hence, the transformation applies only to these "`old style`" message. +In the preceding example, we transform requests by using `/WEB-INF/oldRequests.xslt` and response messages by using `/WEB-INF/oldResponses.xslt`. +Note that, since endpoint interceptors are registered at the endpoint-mapping level, you can create an endpoint mapping that applies to the "`old style`" messages and add the interceptor to that mapping. +Hence, the transformation applies only to these "`old style`" message. You could use the `WsConfigurerAdapter` approach, as described earlier, for the `PayloadTransformingInterceptor` as well. [[server-endpoint-exception-resolver]] == Handling Exceptions -Spring-WS provides {spring-ws-api}/server/EndpointExceptionResolver.html[`EndpointExceptionResolver`] implementations to ease the pain of unexpected exceptions occurring while your message is being processed by an endpoint that matched the request. Endpoint exception resolvers somewhat resemble the exception mappings that can be defined in the web application descriptor `web.xml`. However, they provide a more flexible way to handle exceptions. They provide information about what endpoint was invoked when the exception was thrown. Furthermore, a programmatic way of handling exceptions gives you many more options for how to respond appropriately. Rather than expose the innards of your application by giving an exception and stack trace, you can handle the exception any way you want -- for example, by returning a SOAP fault with a specific fault code and string. +Spring-WS provides {spring-ws-api}/server/EndpointExceptionResolver.html[`EndpointExceptionResolver`] implementations to ease the pain of unexpected exceptions occurring while your message is being processed by an endpoint that matched the request. +Endpoint exception resolvers somewhat resemble the exception mappings that can be defined in the web application descriptor `web.xml`. +However, they provide a more flexible way to handle exceptions. +They provide information about what endpoint was invoked when the exception was thrown. +Furthermore, a programmatic way of handling exceptions gives you many more options for how to respond appropriately. +Rather than expose the innards of your application by giving an exception and stack trace, you can handle the exception any way you want -- for example, by returning a SOAP fault with a specific fault code and string. Endpoint exception resolvers are automatically picked up by the `MessageDispatcher`, so no explicit configuration is necessary. -Besides implementing the `EndpointExceptionResolver` interface, which is only a matter of implementing the `resolveException(MessageContext, endpoint, Exception)` method, you may also use one of the provided implementations. The simplest implementation is the `SimpleSoapExceptionResolver`, which creates a SOAP 1.1 Server or SOAP 1.2 Receiver fault and uses the exception message as the fault string. The `SimpleSoapExceptionResolver` is the default, but it can be overridden by explicitly adding another resolver. +Besides implementing the `EndpointExceptionResolver` interface, which is only a matter of implementing the `resolveException(MessageContext, endpoint, Exception)` method, you may also use one of the provided implementations. +The simplest implementation is the `SimpleSoapExceptionResolver`, which creates a SOAP 1.1 Server or SOAP 1.2 Receiver fault and uses the exception message as the fault string. +The `SimpleSoapExceptionResolver` is the default, but it can be overridden by explicitly adding another resolver. === `SoapFaultMappingExceptionResolver` -The `SoapFaultMappingExceptionResolver` is a more sophisticated implementation. This resolver lets you take the class name of any exception that might be thrown and map it to a SOAP Fault: +The `SoapFaultMappingExceptionResolver` is a more sophisticated implementation. +This resolver lets you take the class name of any exception that might be thrown and map it to a SOAP Fault: ==== [source,xml] @@ -1023,7 +1215,10 @@ The `SoapFaultMappingExceptionResolver` is a more sophisticated implementation. ---- ==== -The key values and default endpoint use a format of `faultCode,faultString,locale`, where only the fault code is required. If the fault string is not set, it defaults to the exception message. If the language is not set, it defaults to English. The preceding configuration maps exceptions of type `ValidationFailureException` to a client-side SOAP fault with a fault string of `Invalid request`, as follows: +The key values and default endpoint use a format of `faultCode,faultString,locale`, where only the fault code is required. +If the fault string is not set, it defaults to the exception message. +If the language is not set, it defaults to English. +The preceding configuration maps exceptions of type `ValidationFailureException` to a client-side SOAP fault with a fault string of `Invalid request`, as follows: ==== [source,xml,subs="verbatim,+quotes"] @@ -1043,7 +1238,9 @@ If any other exception occurs, it returns the default fault: a server-side fault === Using `SoapFaultAnnotationExceptionResolver` -You can also annotate exception classes with the `@SoapFault` annotation, to indicate the SOAP fault that should be returned whenever that exception is thrown. 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. The following example shows such an exception: +You can also annotate exception classes with the `@SoapFault` annotation, to indicate the SOAP fault that should be returned whenever that exception is thrown. +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. +The following example shows such an exception: ==== [source,java] @@ -1084,22 +1281,30 @@ Whenever the `MyBusinessException` is thrown with the constructor string `"Oops! When it comes to testing your Web service endpoints, you have two possible approaches: * Write Unit Tests, where you provide (mock) arguments for your endpoint to consume. -The advantage of this approach is that it is quite easy to accomplish (especially for classes annotated with `@Endpoint`). The disadvantage is that you are not really testing the exact content of the XML messages that are sent over the wire. +The advantage of this approach is that it is quite easy to accomplish (especially for classes annotated with `@Endpoint`). +The disadvantage is that you are not really testing the exact content of the XML messages that are sent over the wire. * Write Integrations Tests, which do test the contents of the message. -The first approach can easily be accomplished with mocking frameworks such as Mockito, EasyMock, and others. The next section focuses on writing integration tests. +The first approach can easily be accomplished with mocking frameworks such as Mockito, EasyMock, and others. +The next section focuses on writing integration tests. === Writing server-side integration tests -Spring-WS has support for creating endpoint integration tests. In this context, an endpoint is a class that handles (SOAP) messages (see <>). +Spring-WS has support for creating endpoint integration tests. +In this context, an endpoint is a class that handles (SOAP) messages (see <>). -The integration test support lives in the `org.springframework.ws.test.server` package. The core class in that package is the `MockWebServiceClient`. The underlying idea is that this client creates a request message and then sends it over to the endpoints that are configured in a standard `MessageDispatcherServlet` application context (see <>). These endpoints handle the message and create a response. The client then receives this response and verifies it against registered expectations. +The integration test support lives in the `org.springframework.ws.test.server` package. +The core class in that package is the `MockWebServiceClient`. +The underlying idea is that this client creates a request message and then sends it over to the endpoints that are configured in a standard `MessageDispatcherServlet` application context (see <>). +These endpoints handle the message and create a response. +The client then receives this response and verifies it against registered expectations. The typical usage of the `MockWebServiceClient` is: . . Create a `MockWebServiceClient` instance by calling `MockWebServiceClient.createClient(ApplicationContext)` or `MockWebServiceClient.createClient(WebServiceMessageReceiver, WebServiceMessageFactory)`. . Send request messages by calling `sendRequest(RequestCreator)`, possibly by using the default `RequestCreator` implementations provided in `RequestCreators` (which can be statically imported). -. Set up response expectations by calling `andExpect(ResponseMatcher)`, possibly by using the default `ResponseMatcher` implementations provided in `ResponseMatchers` (which can be statically imported). Multiple expectations can be set up by chaining `andExpect(ResponseMatcher)` calls. +. Set up response expectations by calling `andExpect(ResponseMatcher)`, possibly by using the default `ResponseMatcher` implementations provided in `ResponseMatchers` (which can be statically imported). +Multiple expectations can be set up by chaining `andExpect(ResponseMatcher)` calls. [NOTE] ==== @@ -1108,7 +1313,9 @@ The typical usage of the `MockWebServiceClient` is: . [NOTE] ==== -You can rely on the standard logging features available in Spring-WS 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 <> for more information. +You can rely on the standard logging features available in Spring-WS 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 <> for more information. ==== Consider, for example, the following web service endpoint class: @@ -1134,8 +1341,11 @@ public class CustomerEndpoint { } ---- -<1> The `CustomerEndpoint` in annotated with `@Endpoint`. See <>. -<2> The `getCustomerCount()` method takes a `CustomerCountRequest` as its argument and returns a `CustomerCountResponse`. Both of these classes are objects supported by a marshaller. For instance, they can have a `@XmlRootElement` annotation to be supported by JAXB2. +<1> The `CustomerEndpoint` in annotated with `@Endpoint`. +See <>. +<2> The `getCustomerCount()` method takes a `CustomerCountRequest` as its argument and returns a `CustomerCountResponse`. +Both of these classes are objects supported by a marshaller. +For instance, they can have a `@XmlRootElement` annotation to be supported by JAXB2. ==== The following example shows a typical test for `CustomerEndpoint`: @@ -1191,19 +1401,24 @@ public class CustomerEndpointIntegrationTest { } ---- -<1> This test uses the standard testing facilities provided in the Spring Framework. This is not required but is generally the easiest way to set up the test. -<2> The application context is a standard Spring-WS application context (see <>), read from `spring-ws-servlet.xml`. In this case, the application context contains a bean definition for `CustomerEndpoint` (or perhaps a `` is used). +<1> This test uses the standard testing facilities provided in the Spring Framework. +This is not required but is generally the easiest way to set up the test. +<2> The application context is a standard Spring-WS application context (see <>), read from `spring-ws-servlet.xml`. +In this case, the application context contains a bean definition for `CustomerEndpoint` (or perhaps a `` is used). <3> In a `@Before` method, we create a `MockWebServiceClient` by using the `createClient` factory method. <4> We send a request by calling `sendRequest()` with a `withPayload()` `RequestCreator` provided by the statically imported `RequestCreators` (see <>). We also set up response expectations by calling `andExpect()` with a `payload()` `ResponseMatcher` provided by the statically imported `ResponseMatchers` (see <>). -This part of the test might look a bit confusing, but the code completion features of your IDE are of great help. After typing `sendRequest(`, your IDE can provide you with a list of possible request creating strategies, provided you statically imported `RequestCreators`. The same applies to `andExpect()`, provided you statically imported `ResponseMatchers`. +This part of the test might look a bit confusing, but the code completion features of your IDE are of great help. +After typing `sendRequest(`, your IDE can provide you with a list of possible request creating strategies, provided you statically imported `RequestCreators`. +The same applies to `andExpect()`, provided you statically imported `ResponseMatchers`. ==== [[server-test-request-creator]] === Using `RequestCreator` and `RequestCreators` -Initially, the `MockWebServiceClient` needs to create a request message for the endpoint to consume. The client uses the `RequestCreator` strategy interface for this purpose: +Initially, the `MockWebServiceClient` needs to create a request message for the endpoint to consume. +The client uses the `RequestCreator` strategy interface for this purpose: ==== [source,java] @@ -1217,12 +1432,15 @@ public interface RequestCreator { ---- ==== -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 typically statically import `RequestCreators`. +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 typically statically import `RequestCreators`. [[server-test-response-matcher]] === Using `ResponseMatcher` and `ResponseMatchers` -When the request message has been processed by the endpoint and a response has been received, the `MockWebServiceClient` can verify whether this response message meets certain expectations. The client uses the `ResponseMatcher` strategy interface for this purpose: +When the request message has been processed by the endpoint and a response has been received, the `MockWebServiceClient` can verify whether this response message meets certain expectations. +The client uses the `ResponseMatcher` strategy interface for this purpose: ==== [source,java] @@ -1236,7 +1454,8 @@ public interface ResponseMatcher { ---- ==== -Once again, you can write your own implementations of this interface, throwing `AssertionError` instances 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 typically statically import this class. +Once again, you can write your own implementations of this interface, throwing `AssertionError` instances 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 typically statically import this class. The `ResponseMatchers` class provides the following response matchers: @@ -1246,7 +1465,8 @@ The `ResponseMatchers` class provides the following response matchers: | Description | `payload()` -| Expects a given response payload. May include https://github.com/xmlunit/user-guide/wiki/Placeholders[XMLUnit Placeholders]. +| Expects a given response payload. +May include https://github.com/xmlunit/user-guide/wiki/Placeholders[XMLUnit Placeholders]. | `validPayload()` | Expects the response payload to validate against given XSD schemas. @@ -1258,7 +1478,8 @@ The `ResponseMatchers` class provides the following response matchers: | Expects a given SOAP header to exist in the response message. | `soapEnvelope()` -| Expects a given SOAP payload. May include https://github.com/xmlunit/user-guide/wiki/Placeholders[XMLUnit Placeholders]. +| Expects a given SOAP payload. +May include https://github.com/xmlunit/user-guide/wiki/Placeholders[XMLUnit Placeholders]. | `noFault()` | Expects that the response message does not contain a SOAP Fault. diff --git a/spring-ws-docs/src/docs/asciidoc/tutorial.adoc b/spring-ws-docs/src/docs/asciidoc/tutorial.adoc index 7b8f7113..e24b9cf5 100644 --- a/spring-ws-docs/src/docs/asciidoc/tutorial.adoc +++ b/spring-ws-docs/src/docs/asciidoc/tutorial.adoc @@ -1,15 +1,24 @@ [[tutorial]] = Writing Contract-First Web Services -This tutorial shows you how to write <> -- that is, how to develop web services that start with the XML Schema or WSDL contract first followed by the Java code second. Spring-WS focuses on this development style, and this tutorial should help you get started. Note that the first part of this tutorial contains almost no Spring-WS specific information. It is mostly about XML, XSD, and WSDL. The <> focuses on implementing this contract with Spring-WS . +This tutorial shows you how to write <> -- that is, how to develop web services that start with the XML Schema or WSDL contract first followed by the Java code second. +Spring-WS focuses on this development style, and this tutorial should help you get started. +Note that the first part of this tutorial contains almost no Spring-WS specific information. +It is mostly about XML, XSD, and WSDL. +The <> focuses on implementing this contract with Spring-WS . -The most important thing when doing contract-first web service development is to think in terms of XML. This means that Java language concepts are of lesser importance. It is the XML that is sent across the wire, and you should focus on that. Java being used to implement the web service is an implementation detail. +The most important thing when doing contract-first web service development is to think in terms of XML. +This means that Java language concepts are of lesser importance. +It is the XML that is sent across the wire, and you should focus on that. +Java being used to implement the web service is an implementation detail. -In this tutorial, we define a web service that is created by a Human Resources department. Clients can send holiday request forms to this service to book a holiday. +In this tutorial, we define a web service that is created by a Human Resources department. +Clients can send holiday request forms to this service to book a holiday. == Messages -In this section, we focus on the actual XML messages that are sent to and from the web service. We start out by determining what these messages look like. +In this section, we focus on the actual XML messages that are sent to and from the web service. +We start out by determining what these messages look like. === Holiday @@ -25,11 +34,14 @@ In the scenario, we have to deal with holiday requests, so it makes sense to det ---- ==== -A holiday consists of a start date and an end date. We have also decided to use the standard https://www.cl.cam.ac.uk/~mgk25/iso-time.html[ISO 8601] date format for the dates, because that saves 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. +A holiday consists of a start date and an end date. +We have also decided to use the standard https://www.cl.cam.ac.uk/~mgk25/iso-time.html[ISO 8601] date format for the dates, because that saves a lot of parsing hassle. +We have also added a namespace to the element, to make sure our elements can be used within other XML documents. === Employee -There is also the notion of an employee in the scenario. Here is what it looks like in XML: +There is also the notion of an employee in the scenario. +Here is what it looks like in XML: ==== [source,xml] @@ -42,7 +54,8 @@ There is also the notion of an employee in the scenario. Here is what it looks l ---- ==== -We have used the same namespace as before. If this `` element could be used in other scenarios, it might make sense to use a different namespace, such as `http://example.com/employees/schemas`. +We have used the same namespace as before. +If this `` element could be used in other scenarios, it might make sense to use a different namespace, such as `http://example.com/employees/schemas`. === HolidayRequest @@ -65,21 +78,31 @@ Both the `holiday` element and the `employee` element can be put in a `` could have been the first element. What matters is that all of the data is there. In fact, the data is the only thing that is important: We take a data-driven approach. +The order of the two elements does not matter: `` could have been the first element. +What matters is that all the data is there. +In fact, the data is the only thing that is important: we take a data-driven approach. [[tutorial.xsd]] == Data Contract -Now that we have seen some examples of the XML data that we can use, it makes sense to formalize this into a schema. This data contract defines the message format we accept. There are four different ways of defining such a contract for XML: +Now that we have seen some examples of the XML data that we can use, it makes sense to formalize this into a schema. +This data contract defines the message format we accept. +There are four different ways of defining such a contract for XML: -* DTDs -* https://www.w3.org/XML/Schema[XML Schema (XSD)] -* http://www.relaxng.org/[RELAX NG] -* http://www.schematron.com/[Schematron] +* DTDs. +* https://www.w3.org/XML/Schema[XML Schema (XSD)]. +* http://www.relaxng.org/[RELAX NG]. +* http://www.schematron.com/[Schematron]. -DTDs have limited namespace support, so they are not suitable for web services. Relax NG and Schematron are easier than XML Schema. Unfortunately, they are not so widely supported across platforms. As a result, we use XML Schema. +DTDs have limited namespace support, so they are not suitable for web services. +Relax NG and Schematron are easier than XML Schema. +Unfortunately, they are not so widely supported across platforms. +As a result, we use XML Schema. -By far, the easiest way to create an XSD is to infer it from sample documents. Any good XML editor or Java IDE offers this functionality. Basically, these tools use some sample XML documents to generate a schema that validates them all. The end result certainly needs to be polished up, but it is a great starting point. +By far, the easiest way to create an XSD is to infer it from sample documents. +Any good XML editor or Java IDE offers this functionality. +Basically, these tools use some sample XML documents to generate a schema that validates them all. +The end result certainly needs to be polished up, but it is a great starting point. Using the sample described earlier, we end up with the following generated schema: @@ -124,7 +147,11 @@ Using the sample described earlier, we end up with the following generated schem ---- ==== -This generated schema 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 want to accept only a ``. By removing the wrapping element tags (thus keeping the types) and inlining the results, we can accomplish this, as follows: +This generated schema 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 want to accept only a ``. +By removing the wrapping element tags (thus keeping the types) and inlining the results, we can accomplish this, as follows: ==== [source,xml] @@ -173,7 +200,12 @@ The schema still has one problem: With a schema like this, you can expect the fo ---- ==== -Clearly, we must make sure that the start and end date are really dates. XML Schema has an excellent built-in `date` type that we can use. We also change the `NCName` s to `string` instances. Finally, we change the `sequence` in `` to `all`. This tells the XML parser that the order of `` and `` is not significant. Our final XSD now looks like the following listing: +Clearly, we must make sure that the start and end date are really dates. +XML Schema has an excellent built-in `date` type that we can use. +We also change the `NCName` s to `string` instances. +Finally, we change the `sequence` in `` to `all`. +This tells the XML parser that the order of `` and `` is not significant. +Our final XSD now looks like the following listing: ==== [source,xml] @@ -216,9 +248,15 @@ We store this file as `hr.xsd`. [[tutorial-service-contract]] == Service Contract -A service contract is generally expressed as a https://www.w3.org/TR/wsdl[WSDL] file. Note that, in Spring-WS, writing the WSDL by hand is not required. Based on the XSD and some conventions, Spring-WS can create the WSDL for you, as explained in the section entitled <>. The remainder of this section shows how to write WSDL by hand. You may want to skip to <>. +A service contract is generally expressed as a https://www.w3.org/TR/wsdl[WSDL] file. +Note that, in Spring-WS, writing the WSDL by hand is not required. +Based on the XSD and some conventions, Spring-WS can create the WSDL for you, as explained in the section entitled <>. +The remainder of this section shows how to write WSDL by hand. +You may want to skip to <>. -We start our WSDL with the standard preamble and by importing our existing XSD. To separate the schema from the definition, we use a separate namespace for the WSDL definitions: `http://mycompany.com/hr/definitions`. The following listing shows the preamble: +We start our WSDL with the standard preamble and by importing our existing XSD. +To separate the schema from the definition, we use a separate namespace for the WSDL definitions: `http://mycompany.com/hr/definitions`. +The following listing shows the preamble: ==== [source,xml] @@ -236,7 +274,8 @@ We start our WSDL with the standard preamble and by importing our existing XSD. ---- ==== -Next, we add our messages based on the written schema types. We only have one message, the `` we put in the schema: +Next, we add our messages based on the written schema types. +We only have one message, the `` we put in the schema: ==== [source,xml] @@ -260,9 +299,11 @@ We add the message to a port type as an operation: ---- ==== -That message finishes 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 have just defined) and a `service` (which tells the client where to invoke it). +That message finishes 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 have just defined) and a `service` (which tells the client where to invoke it). -Adding a concrete part is pretty standard. To do so, 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 works), and determine the `location` URL where you want the request to arrive (in this case, `http://mycompany.com/humanresources`): +Adding a concrete part is pretty standard. +To do so, 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 works), and determine the `location` URL where you want the request to arrive (in this case, `http://mycompany.com/humanresources`): ==== [source,xml] @@ -315,12 +356,14 @@ Adding a concrete part is pretty standard. To do so, refer to the abstract part <9> The `http://localhost:8080/holidayService/` address is the URL where the web service can be invoked. ==== -The preceding listing shows the final WSDL. We describe how to implement the resulting schema and WSDL in the next section. +The preceding listing shows the final WSDL. +We describe how to implement the resulting schema and WSDL in the next section. [[tutorial-creating-project]] == Creating the project -In this section, we use https://maven.apache.org/[Maven] to create the initial project structure for us. Doing so is not required but greatly reduces the amount of code we have to write to setup our HolidayService. +In this section, we use https://maven.apache.org/[Maven] to create the initial project structure for us. +Doing so is not required but greatly reduces the amount of code we have to write to set up our HolidayService. The following command creates a Maven web application project for us by using the Spring-WS archetype (that is, project template): @@ -334,7 +377,9 @@ mvn archetype:create -DarchetypeGroupId=org.springframework.ws \ ---- ==== -The preceding command creates a new directory called `holidayService`. In this directory is a `src/main/webapp` directory, which contains the root of the WAR file. You can find the standard web application deployment descriptor (`'WEB-INF/web.xml'`) here, which defines a Spring-WS `MessageDispatcherServlet` and maps all incoming requests to this servlet: +The preceding command creates a new directory called `holidayService`. +In this directory is a `src/main/webapp` directory, which contains the root of the WAR file. +You can find the standard web application deployment descriptor (`WEB-INF/web.xml`) here, which defines a Spring-WS `MessageDispatcherServlet` and maps all incoming requests to this servlet: ==== [source,xml,subs="verbatim,quotes"] @@ -362,20 +407,26 @@ The preceding command creates a new directory called `holidayService`. In this d ---- ==== -In addition to the preceding `WEB-INF/web.xml` file, you also need another, Spring-WS-specific, configuration file, named `WEB-INF/spring-ws-servlet.xml`. This file contains all of the Spring-WS-specific beans, such as `EndPoints` and `WebServiceMessageReceivers` 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 define a `MessageDispatcherServlet` with the name `'dynamite'`, the name of the Spring-WS-specific configuration file becomes `WEB-INF/dynamite-servlet.xml`. +In addition to the preceding `WEB-INF/web.xml` file, you also need another, Spring-WS-specific, configuration file, named `WEB-INF/spring-ws-servlet.xml`. +This file contains all the Spring-WS-specific beans, such as `EndPoints` and `WebServiceMessageReceivers` 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 define a `MessageDispatcherServlet` with the name `dynamite`, the name of the Spring-WS-specific configuration file becomes `WEB-INF/dynamite-servlet.xml`. -(You can see the contents of the `WEB-INF/spring-ws-servlet.xml` file for this example in <>.) - -Once you had the project structure created, you can put the schema and the WSDL from the previous section into `'WEB-INF/'` folder. +Once you had the project structure created, you can put the schema and the WSDL from the previous section into `WEB-INF/` folder. [[tutorial-implementing-endpoint]] == Implementing the Endpoint -In Spring-WS, you implement endpoints to handle incoming XML messages. An endpoint is typically created by annotating a class with the `@Endpoint` annotation. In this endpoint class, you can create one or more methods that handle incoming request. The method signatures can be quite flexible. You can include almost any sort of parameter type related to the incoming XML message, as we explain later in this chapter. +In Spring-WS, you implement endpoints to handle incoming XML messages. +An endpoint is typically created by annotating a class with the `@Endpoint` annotation. +In this endpoint class, you can create one or more methods that handle incoming request. +The method signatures can be quite flexible. +You can include almost any sort of parameter type related to the incoming XML message, as we explain later in this chapter. === Handling the XML Message -In this sample application, we use http://www.jdom.org/[JDom 2] to handle the XML message. We also use https://www.w3.org/TR/xpath20/[XPath], because it lets us select particular parts of the XML JDOM tree without requiring strict schema conformance. +In this sample application, we use http://www.jdom.org/[JDom 2] to handle the XML message. +We also use https://www.w3.org/TR/xpath20/[XPath], because it lets us select particular parts of the XML JDOM tree without requiring strict schema conformance. The following listing shows the class that defines our holiday endpoint: @@ -451,24 +502,32 @@ public class HolidayEndpoint { } ---- -<1> 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 makes it eligible for suitable for component scanning. +<1> 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 makes it eligible for suitable for component scanning. <2> The `HolidayEndpoint` requires the `HumanResourceService` business service to operate, so we inject the dependency in the constructor and annotate it with `@Autowired`. -Next, we set up XPath expressions by using the JDOM2 API. There are four expressions: `//hr:StartDate` for extracting the `` text value, `//hr:EndDate` for extracting the end date, and two for extracting the names of the employee. -<3> 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. +Next, we set up XPath expressions by using the JDOM2 API. +There are four expressions: `//hr:StartDate` for extracting the `` text value, `//hr:EndDate` for extracting the end date, and two for extracting the names of the employee. +<3> 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. -<4> The `handleHolidayRequest(..)` method is the main handling method, which gets passed the `` -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 by using a -`SimpleDateFormat` (the `parseData` method). With these values, we invoke a method on the business service. +<4> The `handleHolidayRequest(..)` method is the main handling method, which gets passed the `` 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 by using a `SimpleDateFormat` (the `parseData` method). +With these values, we invoke a method on the business service. Typically, this results in a database transaction being started and some records being altered in the database. Finally, we define a `void` return type, which indicates to Spring-WS that we do not want to send a response message. If we want a response message, we could return a JDOM Element to represent the payload of the response message. ==== -Using JDOM is just one of the options to handle the XML. Other options include DOM, dom4j, XOM, SAX, and StAX, but also marshalling techniques like JAXB, Castor, XMLBeans, JiBX, and XStream, as explained in <>. We chose JDOM because it gives us access to the raw XML and because it is based on classes (not interfaces and factory methods as with W3C DOM and dom4j), which makes the code less verbose. We use XPath because it is less fragile than marshalling technologies. We do not need strict schema conformance as long as we can find the dates and the name. +Using JDOM is just one of the options to handle the XML. +Other options include DOM, dom4j, XOM, SAX, and StAX, but also marshalling techniques like JAXB, Castor, XMLBeans, JiBX, and XStream, as explained in <>. +We chose JDOM because it gives us access to the raw XML and because it is based on classes (not interfaces and factory methods as with W3C DOM and dom4j), which makes the code less verbose. +We use XPath because it is less fragile than marshalling technologies. +We do not need strict schema conformance as long as we can find the dates and the name. -Because we use JDOM, we must add some dependencies to the Maven `pom.xml`, which is in the root of our project directory. Here is the relevant section of the POM: +Because we use JDOM, we must add some dependencies to the Maven `pom.xml`, which is in the root of our project directory. +Here is the relevant section of the POM: ==== [source,xml] @@ -493,7 +552,8 @@ Because we use JDOM, we must add some dependencies to the Maven `pom.xml`, which ---- ==== -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 `` element. +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 `` element. ==== [source,xml] @@ -516,7 +576,10 @@ Here is how we would configure these classes in our `spring-ws-servlet.xml` Spri === Routing the Message to the Endpoint -As part of writing the endpoint, we also used the `@PayloadRoot` annotation to indicate which sort of messages can be handled by the `handleHolidayRequest` method. In Spring-WS, this process is the responsibility of an `EndpointMapping`. Here, we route messages based on their content by using a `PayloadRootAnnotationMethodEndpointMapping`. The following listing shows the annotation we used earlier: +As part of writing the endpoint, we also used the `@PayloadRoot` annotation to indicate which sort of messages can be handled by the `handleHolidayRequest` method. +In Spring-WS, this process is the responsibility of an `EndpointMapping`. +Here, we route messages based on their content by using a `PayloadRootAnnotationMethodEndpointMapping`. +The following listing shows the annotation we used earlier: ==== [source,java] @@ -525,13 +588,16 @@ As part of writing the endpoint, we also used the `@PayloadRoot` annotation to i ---- ==== -The annotation shown in the preceding example basically means that whenever an XML message is received with the namespace `http://mycompany.com/hr/schemas` and the `HolidayRequest` local name, it is routed to the `handleHolidayRequest` method. By using the `` 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. +The annotation shown in the preceding example basically means that whenever an XML message is received with the namespace `http://mycompany.com/hr/schemas` and the `HolidayRequest` local name, it is routed to the `handleHolidayRequest` method. +By using the `` 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 is described in <>. +There are other ways to map endpoints to XML messages, which is described in <>. === Providing the Service and Stub implementation -Now that we have the endpoint, we need `HumanResourceService` and its implementation for use by `HolidayEndpoint`. The following listing shows the `HumanResourceService` interface: +Now that we have the endpoint, we need `HumanResourceService` and its implementation for use by `HolidayEndpoint`. +The following listing shows the `HumanResourceService` interface: ==== [source,java] @@ -565,13 +631,17 @@ public class StubHumanResourceService implements HumanResourceService { } ---- -<1> The `StubHumanResourceService` is annotated with `@Service`. This marks the class as a business facade, which makes this a candidate for injection by `@Autowired` in `HolidayEndpoint`. +<1> The `StubHumanResourceService` is annotated with `@Service`. +This marks the class as a business facade, which makes this a candidate for injection by `@Autowired` in `HolidayEndpoint`. ==== [[tutorial-publishing-wsdl]] == Publishing the WSDL -Finally, we need to publish the WSDL. As stated in <>, we do not need to write a WSDL ourselves. Spring-WS can generate one based on some conventions. Here is how we define the generation: +Finally, we need to publish the WSDL. +As stated in <>, we do not need to write a WSDL ourselves. +Spring-WS can generate one based on some conventions. +Here is how we define the generation: ==== [source,xml] @@ -584,15 +654,20 @@ Finally, we need to publish the WSDL. As stated in <> ---- -<1> 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 is `http://localhost:8080/holidayService/holiday.wsdl`. +<1> 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 is `http://localhost:8080/holidayService/holiday.wsdl`. <2> Next, we set the WSDL port type to be `HumanResource`. -<3> 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 do not have to change the URI manually. -For more information, see <>. For the location transformation to work, we need to add an init parameter to `spring-ws` -servlet in `web.xml` (shown in the next listing). -<4> We define the target namespace for the WSDL definition itself. Setting this attribute is not required. If not set, the WSDL has the same namespace as the XSD schema. -<5> The `xsd` element refers to the human resource schema we defined in <>. We placed the schema in the `WEB-INF` directory of the application. +<3> 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 do not have to change the URI manually. +For more information, see <>. +For the location transformation to work, we need to add an init parameter to `spring-ws` servlet in `web.xml` (shown in the next listing). +<4> We define the target namespace for the WSDL definition itself. +Setting this attribute is not required. +If not set, the WSDL has the same namespace as the XSD schema. +<5> The `xsd` element refers to the human resource schema we defined in <>. +We placed the schema in the `WEB-INF` directory of the application. ==== The following listing shows how to add the init parameter: @@ -607,6 +682,12 @@ The following listing shows how to add the init parameter: ---- ==== -You can create a WAR file by using `mvn install`. If you deploy the application (to Tomcat, Jetty, and so on) and point your browser at http://localhost:8080/holidayService/holiday.wsdl[this location], you see the generated WSDL. This WSDL is ready to be used by clients, such as http://www.soapui.org/[soapUI] or other SOAP frameworks. +You can create a WAR file by using `mvn install`. +If you deploy the application (to Tomcat, Jetty, and so on) and point your browser at http://localhost:8080/holidayService/holiday.wsdl[this location], you see the generated WSDL. +This WSDL is ready to be used by clients, such as http://www.soapui.org/[soapUI] or other SOAP frameworks. -That concludes this tutorial. The tutorial code can be found in the full distribution of Spring-WS. If you wish to continue, look at the echo sample application that is part of the distribution. After that, look at the airline sample, which is a bit more complicated, because it uses JAXB, WS-Security, Hibernate, and a transactional service layer. Finally, you can read the rest of the reference documentation. +That concludes this tutorial. +The tutorial code can be found in the full distribution of Spring-WS. +If you wish to continue, look at the echo sample application that is part of the distribution. +After that, look at the airline sample, which is a bit more complicated, because it uses JAXB, WS-Security, Hibernate, and a transactional service layer. +Finally, you can read the rest of the reference documentation. diff --git a/spring-ws-docs/src/docs/asciidoc/what-is-spring-ws.adoc b/spring-ws-docs/src/docs/asciidoc/what-is-spring-ws.adoc index 25d47d68..f693326f 100644 --- a/spring-ws-docs/src/docs/asciidoc/what-is-spring-ws.adoc +++ b/spring-ws-docs/src/docs/asciidoc/what-is-spring-ws.adoc @@ -3,17 +3,22 @@ == Introduction -Spring Web Services (Spring-WS) is a product of the Spring community and is focused on creating document-driven web services. Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services by using one of the many ways to manipulate XML payloads. The product is based on Spring itself, which means you can use the Spring concepts (such as dependency injection) as an integral part of your web service. +Spring Web Services (Spring-WS) is a product of the Spring community and is focused on creating document-driven web services. +Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services by using one of the many ways to manipulate XML payloads. +The product is based on Spring itself, which means you can use the Spring concepts (such as dependency injection) as an integral part of your web service. -People use Spring-WS for many reasons, but most are drawn to it after finding alternative SOAP stacks lacking when it comes to following web service best practices. Spring-WS makes the best practice an easy practice. This includes practices such as the WS-I basic profile, contract-first development, and having a loose coupling between contract and implementation. The other key features of Spring-WS are: +People use Spring-WS for many reasons, but most are drawn to it after finding alternative SOAP stacks lacking when it comes to following web service best practices. +Spring-WS makes the best practice an easy practice. +This includes practices such as the WS-I basic profile, contract-first development, and having a loose coupling between contract and implementation. +The other key features of Spring-WS are: -* <> -* <> -* <> -* <> -* <> -* <> -* <> +* <>. +* <>. +* <>. +* <>. +* <>. +* <>. +* <>. [[features-powerful-mappings]] === Powerful mappings @@ -33,7 +38,8 @@ Spring-WS builds on the Object/XML Mapping module in the Spring Framework, which [[features-reusing-your-spring-expertise]] === Reusing Your Spring expertise -Spring-WS uses Spring application contexts for all configuration, which should help Spring developers get up-to-speed quickly. Also, the architecture of Spring-WS resembles that of Spring-MVC. +Spring-WS uses Spring application contexts for all configuration, which should help Spring developers get up-to-speed quickly. +Also, the architecture of Spring-WS resembles that of Spring-MVC. [[features-support-for-ws-security]] === Support for WS-Security @@ -43,7 +49,8 @@ WS-Security lets you sign SOAP messages, encrypt and decrypt them, or authentica [[features-integration-with-spring-security]] === Integration with Spring Security -The WS-Security implementation of Spring-WS provides integration with Spring Security. This means you can use your existing Spring Security configuration for your SOAP service as well. +The WS-Security implementation of Spring-WS provides integration with Spring Security. +This means you can use your existing Spring Security configuration for your SOAP service as well. [[features-apache-license]] === Apache license @@ -52,16 +59,22 @@ You can confidently use Spring-WS in your project. == Runtime environment -Spring-WS requires a standard Java 17 Runtime Environment. Spring-WS is built on Spring Framework 6.x. +Spring-WS requires a standard Java 17 Runtime Environment. +Spring-WS is built on Spring Framework 6.x. Spring-WS consists of a number of modules, which are described in the remainder of this section. -* The XML module (`spring-xml`) contains various XML support classes for Spring-WS. This module is mainly intended for the Spring-WS framework itself and not web service developers. -* The Core module (`spring-ws-core`) is the central part of the Spring's web services functionality. It provides the central <> and <> interfaces, the <> framework (with powerful message dispatching), the various support classes for implementing web service endpoints, and the <> `WebServiceTemplate`. +* The XML module (`spring-xml`) contains various XML support classes for Spring-WS. +This module is mainly intended for the Spring-WS framework itself and not web service developers. +* The Core module (`spring-ws-core`) is the central part of the Spring's web services functionality. +It provides the central <> and <> interfaces, the <> framework (with powerful message dispatching), the various support classes for implementing web service endpoints, and the <> `WebServiceTemplate`. * The Support module (`spring-ws-support`) contains additional transports (JMS, Email, and others). -* The <> module (`spring-ws-security`) provides a WS-Security implementation that integrates with the core web service package. It lets you sign, decrypt and encrypt, and add principal tokens to SOAP messages. Additionally, it lets you use your existing Spring Security security implementation for authentication and authorization. +* The <> module (`spring-ws-security`) provides a WS-Security implementation that integrates with the core web service package. +It lets you sign, decrypt and encrypt, and add principal tokens to SOAP messages. +Additionally, it lets you use your existing Spring Security implementation for authentication and authorization. -The following figure shows and the dependencies between the Spring-WS modules. Arrows indicate dependencies (that is, Spring-WS Core depends on Spring-XML and the OXM module found in Spring 3 and higher). +The following figure shows and the dependencies between the Spring-WS modules. +Arrows indicate dependencies (that is, Spring-WS Core depends on Spring-XML and the Spring OXM). image::images/spring-deps.png[align="center"] @@ -69,8 +82,8 @@ image::images/spring-deps.png[align="center"] Spring-WS supports the following standards: -* SOAP 1.1 and 1.2 -* WSDL 1.1 and 2.0 (XSD-based generation is supported only for WSDL 1.1) -* WS-I Basic Profile 1.0, 1.1, 1.2, and 2.0 -* WS-Addressing 1.0 and the August 2004 draft -* SOAP Message Security 1.1, Username Token Profile 1.1, X.509 Certificate Token Profile 1.1, SAML Token Profile 1.1, Kerberos Token Profile 1.1, Basic Security Profile 1.1 +* SOAP 1.1 and 1.2. +* WSDL 1.1 and 2.0 (XSD-based generation is supported only for WSDL 1.1). +* WS-I Basic Profile 1.0, 1.1, 1.2, and 2.0. +* WS-Addressing 1.0 and the August 2004 draft. +* SOAP Message Security 1.1, Username Token Profile 1.1, X.509 Certificate Token Profile 1.1, SAML Token Profile 1.1, Kerberos Token Profile 1.1, Basic Security Profile 1.1. diff --git a/spring-ws-docs/src/docs/asciidoc/why-contract-first.adoc b/spring-ws-docs/src/docs/asciidoc/why-contract-first.adoc index 640bfd51..40096e35 100644 --- a/spring-ws-docs/src/docs/asciidoc/why-contract-first.adoc +++ b/spring-ws-docs/src/docs/asciidoc/why-contract-first.adoc @@ -1,24 +1,33 @@ [[why-contract-first]] = Why Contract First? -When creating web services, there are two development styles: contract-last and contract-first. When you use a contract-last approach, you start with the Java code and let the web service contract (in WSDL -- see sidebar) be generated from that. When using contract-first, you start with the WSDL contract and use Java to implement the contract. +When creating web services, there are two development styles: contract-last and contract-first. +When you use a contract-last approach, you start with the Java code and let the web service contract (in WSDL -- see sidebar) be generated from that. +When using contract-first, you start with the WSDL contract and use Java to implement the contract. .What is WSDL? **** -WSDL stands for Web Service Description Language. A WSDL file is an XML document that describes a web service. It specifies the location of the service and the operations (or methods) the service exposes. For more information about WSDL, see the https://www.w3.org/TR/wsdl[WSDL specification]. +WSDL stands for Web Service Description Language. +A WSDL file is an XML document that describes a web service. +It specifies the location of the service and the operations (or methods) the service exposes. +For more information about WSDL, see the https://www.w3.org/TR/wsdl[WSDL specification]. **** Spring-WS supports only the contract-first development style, and this section explains why. == Object/XML Impedance Mismatch -Similar to the field of ORM, where we have an https://en.wikipedia.org/wiki/Object-Relational_impedance_mismatch[Object/Relational impedance mismatch], converting Java objects to XML has a similar problem. At first glance, the O/X mapping problem appears simple: Create an XML element for each Java object to convert all Java properties and fields to sub-elements or attributes. However, things are not as simple as they appear, because there is a fundamental difference between hierarchical languages, such as XML (and especially XSD), and the graph model of Java. +Similar to the field of ORM, where we have an https://en.wikipedia.org/wiki/Object-Relational_impedance_mismatch[Object/Relational impedance mismatch], converting Java objects to XML has a similar problem. +At first glance, the O/X mapping problem appears simple: Create an XML element for each Java object to convert all Java properties and fields to sub-elements or attributes. +However, things are not as simple as they appear, because there is a fundamental difference between hierarchical languages, such as XML (and especially XSD), and the graph model of Java. NOTE: Most of the contents in this section were inspired by <> and <>. === XSD Extensions -In Java, the only way to change the behavior of a class is to subclass it to add the new behavior to that subclass. In XSD, you can extend a data type by restricting it -- that is, constraining the valid values for the elements and attributes. For instance, consider the following example: +In Java, the only way to change the behavior of a class is to subclass it to add the new behavior to that subclass. +In XSD, you can extend a data type by restricting it -- that is, constraining the valid values for the elements and attributes. +For instance, consider the following example: [source,xml] ---- @@ -29,13 +38,18 @@ In Java, the only way to change the behavior of a class is to subclass it to add ---- -This type restricts a XSD string by way of a regular expression, allowing only three upper case letters. If this type is converted to Java, we 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. +This type restricts a XSD string by way of a regular expression, allowing only three upper case letters. +If this type is converted to Java, we 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. === Unportable Types -One of the most important goals of a web service is to be interoperable: to support multiple platforms such as Java, .NET, Python, and others. Because all of these languages have different class libraries, you must use some common, cross-language format to communicate between them. That format is XML, which is supported by all of these languages. +One of the most important goals of a web service is to be interoperable: to support multiple platforms such as Java, .NET, Python, and others. +Because all of these languages have different class libraries, you must use some common, cross-language format to communicate between them. +That format is XML, which is supported by all of these languages. -Because of this conversion, you must make sure that you use portable types in your service implementation. Consider, for example, a service that returns a `java.util.TreeMap`: +Because of this conversion, you must make sure that you use portable types in your service implementation. +Consider, for example, a service that returns a `java.util.TreeMap`: ==== [source,java] @@ -50,9 +64,12 @@ public Map getFlights() { ---- ==== -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 probably ends up with a `System.Collections.Hashtable`, which has different semantics. +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 probably ends 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: +This problem is also present when working on the client side. +Consider the following XSD snippet, which describes a service contract: ==== [source,xml] @@ -69,7 +86,10 @@ This problem is also present when working on the client side. Consider the follo ---- ==== -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 probably use either a `java.time.LocalDateTime` or `java.time.Instant`. However, both of these classes actually describe times, rather than dates. So, we 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`. +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 probably use either a `java.time.LocalDateTime` or `java.time.Instant`. +However, both of these classes actually describe times, rather than dates. +So, we 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`. === Cyclic Graphs @@ -94,7 +114,9 @@ public class Passenger { ---- ==== -This is a cyclic graph: the `Flight` refers to the `Passenger`, which refers to the `Flight` again. Cyclic graphs like these are quite common in Java. If we take a naive approach to converting this to XML, we end up with something like: +This is a cyclic graph: the `Flight` refers to the `Passenger`, which refers to the `Flight` again. +Cyclic graphs like these are quite common in Java. +If we take a naive approach to converting this to XML, we end up with something like: ==== [source,xml] @@ -134,41 +156,53 @@ One way to solve this problem is to use references to objects that were already ---- ==== -This solves the recursion 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 the WS-I http://www.ws-i.org/Profiles/BasicProfile-1.1.html#SOAP_encodingStyle_Attribute[Basic Profile]). +This solves the recursion 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 the WS-I http://www.ws-i.org/Profiles/BasicProfile-1.1.html#SOAP_encodingStyle_Attribute[Basic Profile]). -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. +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. == Contract-first Versus Contract-last Besides the Object/XML Mapping issues mentioned in the previous section, there are other reasons for preferring a contract-first development style. -* <> -* <> -* <> -* <> +* <>. +* <>. +* <>. +* <>. [[contract-first-fragility]] === 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 use this approach, you 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. +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 use this approach, you 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. -Additionally, not all SOAP stacks generate the same web service contract from a Java contract. This means that changing your current SOAP stack for a different one (for whatever reason) might also change your web service contract. +Additionally, not all SOAP stacks generate the same web service contract from a Java contract. +This means that changing your current SOAP stack for a different one (for whatever reason) might also change your web service contract. When a web service contract changes, users of the contract have to be instructed to obtain the new contract and potentially change their code to accommodate for any changes in the contract. -For a contract to be useful, it must remain constant for as long as possible. If a contract changes, you have to contact all the users of your service and instruct them to get the new version of the contract. +For a contract to be useful, it must remain constant for as long as possible. +If a contract changes, you have to contact all the users of your service and instruct them to get the new version of the contract. [[contract-first-performance]] === Performance -When a Java object 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, and so on. In the end, half of the objects on the heap in your virtual machine might be converted into XML, which results in slow response times. +When a Java object 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, and so on. +In the end, half of the objects on the heap in your virtual machine might be converted into XML, which results 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. [[contract-first-reusability]] === Reusability -Defining your schema in a separate file lets you reuse that file in different scenarios. Consider the definition of an `AirportCode` in a file called `airline.xsd`: +Defining your schema in a separate file lets you reuse that file in different scenarios. +Consider the definition of an `AirportCode` in a file called `airline.xsd`: ==== [source,xml] @@ -186,6 +220,10 @@ You can reuse this definition in other schemas, or even WSDL files, by using an [[contract-first-versioning]] === 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 yet migrated. +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 yet migrated. -If using contract-first, we can have a looser coupling between contract and implementation. Such a looser coupling lets us 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. +If using contract-first, we can have a looser coupling between contract and implementation. +Such a looser coupling lets us 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.