43
WA2103 Programming Java SOAP Web Services with JAX- WS - WebSphere 8 / RAD 8 Web Age Solutions Inc. USA: 1-877-517-6540 Canada: 1-866-206-4644 Web: http://www.webagesolutions.com

WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

  • Upload
    vominh

  • View
    216

  • Download
    0

Embed Size (px)

Citation preview

Page 1: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

WA2103 Programming JavaSOAP Web Services with JAX-

WS - WebSphere 8 / RAD 8

Web Age Solutions Inc.USA: 1-877-517-6540Canada: 1-866-206-4644Web: http://www.webagesolutions.com

Page 2: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

The following terms are trademarks of other companies:

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.

UNIX is a registered trademark of The Open Group in the United States and other countries.

Linux is a trademark of Linus Torvalds in the United States, other countries, or both.

IBM, WebSphere, DB2 and Tivoli are trademarks of the International Business Machines Corporation in the United States, other countries, or both.

Other company, product, and service names may be trademarks or service marks of others.

For customizations of this book or other sales inquiries, please contact us at:

USA: 1-877-517-6540, email: [email protected]: 1-866-206-4644 toll free, email: [email protected]

Copyright © 2012 Web Age Solutions Inc.

This publication is protected by the copyright laws of Canada, United States and any other country where this book is sold. Unauthorized use of this material, including but not limited to, reproduction of the whole or part of the content, re-sale or transmission through fax, photocopy or e-mail is prohibited. To obtain authorization for any such activities, please write to:

Web Age Solutions Inc.439 University AveSuite 820TorontoOntario, M5G 1Y8

Page 3: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Table of ContentsChapter 1 - Introduction to JAX-WS...................................................................................5

1.1 What is JAX-WS?.....................................................................................................51.2 Advantages of JAX-WS............................................................................................61.3 Why Do We Need a Programming Model?..............................................................71.4 Basic Java to WSDL Mapping..................................................................................71.5 Developing a Service Provider..................................................................................81.6 The Service Implementation Class............................................................................91.7 The Service Endpoint Interface (SEI).....................................................................101.8 The Service Endpoint Interface (SEI).....................................................................101.9 Service Implementation Options.............................................................................111.10 Developing a Consumer........................................................................................131.11 Static Client Development....................................................................................131.12 The Service Class..................................................................................................141.13 The Service Class..................................................................................................151.14 The BindingProvider Interface..............................................................................161.15 The BindingProvider Interface..............................................................................171.16 The BindingProvider Interface..............................................................................171.17 Summary...............................................................................................................18

Chapter 2 - WS-Addressing...............................................................................................212.1 What is WS-Addressing?........................................................................................212.2 WS-Addressing and Long Running Services..........................................................212.3 WS-Addressing and Long Running Services..........................................................222.4 WS-Addressing and Long Running Services..........................................................232.5 Other Uses of WS-Addressing................................................................................232.6 WS-Addressing SOAP Header Elements................................................................242.7 Example Client SOAP Request...............................................................................252.8 Example Callback SOAP Request..........................................................................252.9 Writing JAX-WS Clients to use WS-Addressing...................................................262.10 Enabling Asynchronous Service Requests............................................................272.11 Enabling Asynchronous Service Requests............................................................272.12 Enabling Asynchronous Service Requests............................................................272.13 Using WS-Addressing from the Client.................................................................282.14 Using WS-Addressing from the Client.................................................................282.15 Providing an AsyncHandler to Handle Callbacks.................................................292.16 Providing an AsyncHandler to Handle Callbacks.................................................302.17 WS-Addressing Headers in SOAP Messages.......................................................302.18 WS-Addressing Sequence of Events.....................................................................322.19 Asynchronous "Polling"........................................................................................332.20 Endpoint References.............................................................................................332.21 Endpoint References.............................................................................................342.22 Associating Actions with WSDL Operations.......................................................342.23 Associating Actions with WSDL Operations.......................................................352.24 Faults.....................................................................................................................352.25 Security and Firewall Issues..................................................................................35

Page 4: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

2.26 Summary...............................................................................................................36Chapter 3 - WS-ReliableMessaging...................................................................................37

3.1 The Problem with HTTP.........................................................................................373.2 Enter WS-ReliableMessaging.................................................................................383.3 When to Use Reliable Messaging?.........................................................................383.4 How Does WS-RM Work?.....................................................................................393.5 Importance of Persistence.......................................................................................403.6 The Problem With Firewall.....................................................................................413.7 How Does WS-MakeConnection Work?................................................................413.8 Using WS-MakeConnection...................................................................................423.9 Summary.................................................................................................................43

Page 5: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

ObjectivesKey objectives of this chapter

What is JAX-WS?

Why do we need JAX-WS?

Creating a basic Web Service provider.

Creating a basic Web Service consumer.

1.1 What is JAX-WS?

JAX-WS stands for Java API for XML-based Web Services. It provides the programming model to develop a Web Service provider and consumer using Java.

JAX-WS is a vendor neutral specification. A service provider or consumer developed using JAX-WS can be deployed in any Java EE platform with minimal change.

JAX-WS requires at least Java SE 5.

Although, JAX-WS can be used from J2EE 1.4, most applications would be running on Java EE 5 or later.

JAX-WS Specification

JAX-WS (or JSR 224) is a programming API to develop Web Services for the Java environment. The URL of the JSR is: http://jcp.org/en/jsr/detail?id=224.

JAX-WS is the next iteration of JAX-RPC. JAX-RPC (JSR 101).

Application server vendors are gradually migrating their Web Services stack from JAX-RPC to JAX-WS. In most cases, both APIs are supported. Some features may not have been ported to JAX-WS yet. In this case, one will have to continue to develop JAX-RPC based service provider or consumer. For example, in some platform, to use WS-Security, you may have to use JAX-RPC.

If you will be using JAX-WS, chances are high that you are also using Java EE 5. Although, the connection between the two are not very strong. It is conceivable that one uses JAX-WS from a J2EE 1.4 based application. However, you must use Java SE 5 to use JAX-WS.

Page 6: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

1.2 Advantages of JAX-WS

JAX-WS makes many improvements over the previous API JAX-RPC. They fall mostly under these categories:

◊ Much simpler programming model achieved through annotations like @WebService.

◊ Much better vendor neutral code for service provider and consumer.

◊ More advanced programming API for asynchronous Web Service development, message attachment using MTOM and others.

Vendor neutrality is achieved by JAX-WS in two ways:

◊ Application code developed by the developers or generated by any tool are now vendor neutral. Previously with JAX-RPC, such code, especially the generated code was vendor specific.

◊ XML to Java class data mapping is now completely vendor neutral and controlled by the JAXB specification (JSR 222).

Advantages

Java SE has added support for annotations. Annotations are used by the developers to specify qualifying statements about a class, member variable or method. You can think of them as metadata. Annotations are later processed by an external entity, such as a EJB container or Web Services engine to understand the different qualities of a class or its member variables and methods.

Annotations have had a beneficial effect on Java programming. It has made EJB programming simpler. Now, with JAX-WS, annotations have made Web Services development much easier than JAX-RPC. For example, to create a Web Service provider using a POJO, all you have to do is annotate the class with @WebService. We will learn about some of these basic annotations in this chapter. A separate chapter will describe them in more details.

The JAX-RPC did not quite nail down the Java to XML mapping. This lead to development of Web Service providers and consumer that only ran in a certain Java vendor's platform. Similarly, any code that was generated in the server or client side had many vendor specific constructs. It was hard to write a provider application and deploy it in multiple Java vendor's platform. With JAX-WS, these problems are largely resolved. XML to Java mapping is now fully controlled through JAXB. Any hand developed code or generated code will most likely be vendor neutral. This will really help companies who need to run their service in multiple vendor's platform.

6

Page 7: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

1.3 Why Do We Need a Programming Model?

A Web Services programming model, such as JAX-WS or Microsoft's Windows Communication Foundation (WCF) isolates the programming logic from the low level details of Web Services. For example:

◊ Developers keep developing code using Java classes (or, C# in Microsoft platform) and the programming model takes care of converting data from the class objects to XML and vice versa.

◊ The programming model takes care of formatting the over all SOAP document. Programmer's can control some aspects of the document using API if they wish to do so.

◊ Finally, the Web Services engine deals with all network communication between the service provider and consumer.

Web Services Programming Model

One of the major advantages of having a programming model (or API) for Web Service is that the developers do not have to get involved in the gritty details of Web Services, such as, HTTP, SOAP and XML. In a way this is similar to how Servlet programming isolates the programmers from the details of the HTTP communication protocol.

With JAX-WS, a developer keeps the focus on the business logic in various Java classes. Conversion of Java object data to XML and the SOAP document are taken care of by JAX-WS. Advanced programmers can control many aspects of this XML conversion and SOAP document generation using the JAX-WS and JAXB API. Much of this API is available in the form of easy to use annotations.

1.4 Basic Java to WSDL Mapping

JAX-WS is responsible for mapping WSDL and XML schema to Java classes. Here we discuss the basics of this mapping.

An XML data type defined in the WSDL is mapped to a JavaBean class. This mapping is controlled by the JAXB rules.

A <portType> in the WSDL is mapped to a Java interface known as the Service Endpoint Interface (SEI).

Each <operation> in the <portType> maps to a method in the SEI.

The input parameters of a Java method are mapped to an <input> message of the operation. Similarly, the return value of the Java method is

7

Page 8: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

mapped to an <output> of the operation.

Any fault thrown by an operation is mapped to a Java exception thrown by the corresponding method.

1.5 Developing a Service Provider

A Web Service implementation is created using a Java class that has been annotated with the @javax.jws.WebService annotation.

The Java class may be a POJO in a web module (WAR file). Or, it can be a stateless session bean class in an EJB module.

Example:package com.webage.quote;

import javax.jws.*;

@WebServicepublic class Quote { public double getQuote(String symbol) { //Retrieve quote from database double quotedPrice = ...; return quotedPrice; }}

This is a complete implementation of a Web Service with one operation – getQuote. We didn't have to do anything with XML, SOAP or WSDL!

Service Provider

Here we discuss the very basics of creating a service provider. Later, we will learn many complex options for service creation. But, at the bottom line is, to implement a service you must have a Java class that has been annotated with @WebService. This Java class can be a regular class in a web module or a stateless session EJB class in a EJB module. Using an EJB for Web Service implementation has a few advantages. For example, the business logic runs within a distributed transaction scope. Also, if you already have an EJB, you can make it available to non-Java client applications by creating a Web Service out of it.

8

Page 9: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

1.6 The Service Implementation Class

The class must be public and must be annotated with @WebService.

By default, all public methods will be exposed as operations of the Web Service.

To selectively expose certain methods as operations, you can take one of two approaches:

◊ Use a Service Endpoint Interface (SEI). This is discussed later.

◊ Annotate the methods to be excluded using @WebMethod(exclude=true). Example:

@WebServicepublic class Quote { public double getQuote(String symbol) { //... } @WebMethod(exclude=true) public internalMethod() { //... }}

Only the getQuote() method will be exposed as a Web Service operation.

The class must have a public default (no-argument) constructor.

Input parameters, return types and exceptions thrown by all exposed methods must be compatible with the JAXB 2.0 Java to XML Schema mapping definition.

Service implementation Class

When you annotate a class with @WebService, all public methods are automatically exposed as the operations of the Web Service. As a result, there is no need to individually annotate each method with @WebMethod. This annotation is used to exclude certain public methods from being exposed. This is particularly handy when you are Web Service enabling an existing class from a legacy application. The class may have certain methods that are not fit for public consumption.

Each exposed method will correspond to a <operation> element in the <portType> of the service. By default, the name of the operation will be same as the Java method name. This may not be ideal or acceptable in some cases. You can specify the name of the operation using the "operationName" attribute of @WebMethod. For example:

9

Page 10: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

@WebMethod(operationName="GetStockQuote")public double getQuote(String symbol) { //...}

This will make the name of the operation in the WSDL file to be "GetStockQuote".

1.7 The Service Endpoint Interface (SEI)

An SEI is a Java interface that is used to specify the methods that will be exposed as Web Services operations.

SEI directly corresponds to the <portType> in a WSDL file. It is an abstract description of what the service is capable of doing. The implementation class provides the concrete existence of the service.

The use of SEI is totally optional as you can implement a Web service without an SEI. However, SEI leads to a cleaner description of what the Web Service does.

To create an SEI, define a Java interface and annotate it with @WebService. Example:

package com.webage.quote;//...@WebServicepublic interface QuoteSvc { public double getQuote(String symbol);}

1.8 The Service Endpoint Interface (SEI)

The implementation class specifies the SEI using the endpointInterface attribute of the @WebService annotation.

◊ You should also use the 'implements' Java keyword to implement the interface to get compilation errors if there are mis-matches

@WebService(endpointInterface="com.webage.quote.QuoteSvc")public class Quote implements QuoteSvc { public double getQuote(String symbol) { //... } public internalMethod() {

10

Page 11: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

//... }}

Note the following about the example above:

◊ Only the getQuote() method will be exposed an operation.

◊ Both SEI and implementation class must be annotated with @WebService.

All methods in the SEI will always be exposed as operations. You can not exclude them using the @WebMethod annotation.

Input parameters and return types of all methods of the SEI must be compatible with the JAXB 2.0 Java to XML Schema mapping definition.

SEI

Technically the Java class which implements the web service does not have to specify 'implements QuoteSvc' in the example above because the 'endpointInterface' property is the only thing JAX-WS will look at. It is highly suggested to implement the Java interface though because then the Java compiler can catch when method signatures don't match up instead of getting odd runtime errors.

Although SEI is not strictly required, it is generally recommended that you use them. They tend to lead to better design. There are a few main uses of SEI. When a service is being created from ground up, the designer should define the SEI to capture the essence of the service. The SEI will describe in accurate details the contract between the service provider and the consumer. Once the SEI is defined, the developers can implement the business logic for the methods.

SEI can also help you Web Service enable an existing (legacy) Java class. Create the SEI and add to it all the methods of the class that should be exposed. Use the @WebMethod annotation in the SEI to further decorate and qualify the methods. Then implement the SEI from the class. This way, you don't have to use the @WebMethod annotation extensively in the class itself making it a clean solution.

1.9 Service Implementation Options

You can create the service implementation class in one of two ways:

◊ Top-down: You generate the implementation class and SEI from a WSDL file.

◊ Bottom-up: Develop the SEI and implementation class and annotate them with @WebService, @WebMethod etc. JAX-WS will

11

Page 12: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

generate the WSDL for you.

The top-down approach (also known as design first or contract first) defines the service interface in a WSDL file. Then the SEI, implementation class and JavaBeans corresponding to the XML data types are generated. The generated SEI and implementation classes are automatically annotated with @WebService.

◊ This is the recommended approach since the wire level XML data format can be precisely controlled through the XML schema definition.

◊ A vendor may provide its own tool for code generation. JAX-WS reference implementation provides the wsimport command line tool.

The bottom-up approach is useful when you already have the service implementation class. This is common when a legacy application must exposed as a Web Service.

◊ The problem with this approach is that the wire level data XML format will be controlled by the default mapping rules of JAXB. You can alter the mapping but that will require extensive and time consuming use of various JAX-WS and JAXB annotations.

Options

In Service Oriented Architecture (SOA) the service contract is of paramount importance. The contract is defined in a WSDL file. It captures the service operation names and the input and output XML data format. The XML data format is defined using XML schema. The schema is very carefully defined using corporate standards. A data type may be already defined as a part of another service. In this case, the data type is re-used. The top-down approach lends itself well with this contract oriented design. First the XML schema and WSDL are defined. Then the SEI, service implementation class and the JavaBeans corresponding to the XML data types are generated. These classes will be heavily annotated with JAXB and JAX-WS annotations. Also, the generated implementation class will have skeletal method definitions. The developer will need to fill in the actual business logic in these methods.

12

Page 13: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

1.10 Developing a Consumer

Hello?

JAX-WS provides the programming model to develop a Web Service consumer.

The Web Service itself does not have to be developed using JAX-WS or Java.

◊ For example, the service may have been developed using C# and .NET. You should be able to develop a client using JAX-WS.

There are mainly two approaches to building a JAX-WS consumer:

◊ Dynamic client: This type of a consumer program can invoke any web service. For example, a generic Web Service testing tool and performance measurement tool will fall under this category.

◊ Static client: This type of a client can invoke operations of a specific Web Service. Developing such a client is very easy using JAX-WS.

1.11 Static Client Development

The core components of a static client are:

◊ The Service Endpoint Interface (SEI). This represents the <portType> section of the WSDL. This is same as the SEI we have discussed for service implementation.

◊ The JavaBean classes that correspond to the XML data types.

◊ The service class. This class represents the <service> element of the WSDL.

13

Page 14: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

These are generated from the WSDL of the Web Service.

◊ Every vendor will have their own tool to generate the client side code.

The consumer application takes these basic steps:

1. Instantiates an object of the service class.

2. From the service object, the consumer retrieves a stub or proxy. The stub object implements the SEI.

3. Using the stub object, the consumer can easily call the available methods in the SEI. This translates into a SOAP operation call.

Example:QuoteService svc = new QuoteService();QuoteSvc quotePort = svc.getQuotePort(); //Get the stubdouble val = quotePort.getQuote("WAS"); //SOAP call

Static Client

The client uses the service class as a factory to get a hold of the stub object (also known as proxy). A service class object represents a <service> element within the WSDL file. A <service> element contains one or more <port> elements. If a service is accessible by multiple communication protocol, such as HTTP and messaging, there will be a separate <port> element for each protocol. The stub represents a <port> element within the service.

The client first creates an instance of the service class. It then gets a stub object from it. The stub object implements the SEI. That means, the client can start calling the operations exposed by the Web service by calling the corresponding method in the stub object. Each such method call will internally cause the Web Services runtime to submit a SOAP request using the communication protocol specified for the <port>.

1.12 The Service Class

The service class is generated for you. Still, it's good to know about it in some level of detail.

The service class extends the javax.xml.ws.Service class.

The service class class is annotated using @WebServiceClient. Example:@WebServiceClient(name = "QuoteService", targetNamespace = "http://quote.webage.com/", wsdlLocation = "http://host:8080/QuoteProject/QuoteService?wsdl")

14

Page 15: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

public class QuoteService extends Service {

It will have a constructor that is used to supply the location of the WSDL file and the name of the service as specified in the <service> element. Example:

public QuoteService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName);}

1.13 The Service Class

A default constructor will also be available that supplies the default values of the WSDL location and service name:

public QuoteService() { super( new URL("http://host:8080/QuoteProject/QuoteService?wsdl"), new Qname( "http://quote.webage.com/", "QuoteService"));}

The service class will contain a method that returns a stub object.

◊ A stub represents a <port> element inside the <service>. A stub implements the SEI.

◊ This method simply delegates to the Service.getPort() method.@WebEndpoint(name = "QuotePort")public QuoteSvc getQuotePort() { return super.getPort( new Qname( "http://quote.webage.com/", "QuotePort"), QuoteSvc.class);}The Service Class

The service class is a part of the code generated for the client. By default, the name of the service class is same as the value of the "name" attribute of the <service> element in the WSDL.

15

Page 16: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

A client is interested in the service class only for two reasons. It should be able to instantiate an object of the service class. After that, it should be able to get a stub object from the service object.

The constructor of the service class allows us to override the location of the WSDL file. At the time of code generation, the WSDL location will most likely point to the local development machine. This will be the default WSDL location. Needless to say that this location will not work in the production machine. As a result, you must know how to override the URL of the WSDL file. Generally speaking, avoid using the default constructor.

The constructor also takes as input the name of the service as it appears in the <service> element of the WSDL. This name generally doesn't change from development to production. Notice, though, how a fully qualified name (namespace plus local name) is supplied using the Qname object.

In summary, to create a service object that overrides the WSDL URL, you will need to write code like this in the consumer application.QuoteService svc = new QuoteService( new URL("http://production_hostname/QuoteProject/QuoteService?wsdl"), new Qname("http://quote.webage.com/", "QuoteService"));

The service class will also have a getPortName() method that returns the stub object. Where PortName must be same as the "name" attribute of the <port> element within the <service> element in question. A developer need to simply know the expected name of the method and use it. The actual details of the implementation of the method is of no consequence. For the sake of completeness, you should know that this method is annotated with @WebEndpoint. The "name" attribute of the annotation points to the name of the <port>. The method implementation simply calls the Service.getPort() method.

1.14 The BindingProvider Interface

The communication protocol specific configuration properties of a stub can be controlled through the javax.xml.ws.BindingProvder interface.

◊ For example, if a stub represents a <port> that uses the SOAP over HTTP protocol, you will be able to set the SOAP endpoint URL using the BindingProvider interface.

Every stub object implements the BindingProvider interface.

The binding provider object maintains a java.util.Map to hold various SOAP request specific configurations. This is called the request context.

◊ A consumer saves configuration values here prior to making a SOAP call.

16

Page 17: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

1.15 The BindingProvider Interface

Similarly, a Map is used to hold response specific configuration. This is called the response context.

The stub implements the SEI as well as the BindingProvider interface. The binding provider contains a map for the request configuration and another map for the response configuration.

1.16 The BindingProvider Interface

The following example shows how to supply the SOAP endpoint URL:QuoteService svc = new QuoteService();QuoteSvc quotePort = svc.getQuotePort(); //Get the stub

BindingProvider bp = (BindingProvider) quotePort;Map<String, Object> context = bp.getRequestContext();context.put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://production_host/QuoteProject/QuoteService");

double val = quotePort.getQuote("WAS"); //SOAP callThe BindingProvider Interface

Binding provider plays a crucial role in the client side. It allows a consumer application to configure various properties of the SOAP communication. At minimum, you should know how to dynamically set the SOAP endpoint URL. By default, when the client side code is generated, the endpoint will most

17

Stub/Proxy

SEI BindingProvider

Request ContextMap

Response ContextMap

Implements ImplementsContains Contains

Page 18: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

likely be set for the development environment. Typically, you will see "localhost" or "127.0.0.1" being used in the URL. This will work fine in the development machine but will invariably fail in production.

The example above shows how to override the default endpoint URL. First, we typecast the stub into a BindingProvider object. Then, we call the getRequestContext() to obtain the request context map. Within the map we store the endpoint URL property.

Useful properties you can set in the request context are as follows:

Name ValueBindingProvider.ENDPOINT_ADDRESS_PROPERTY The SOAP endpoint URL string.BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY

If the Web Service is protected by basic HTTP authentication, you can supply the user ID and password strings.

BindingProvider.SESSION_MAINTAIN_PROPERTY Set to Boolean.TRUE or Boolean.FALSE. If set to true, session information, such as cookies will be preserved between multiple operation invocations.

In addition to these standard properties, your vendor may define properties to control more advanced aspects of communication. For example, if you wish to use WS-Security or WS-Addressing, your vendor may require you to configure additional vendor specific properties in the request or response context.

1.17 Summary

JAX-WS is a major improvement over JAX-RPC as a programming model for Java based Web Service provider and consumer development.

JAX-WS uses the JAXB standard for Java to XML data mapping.

A service provider is a Java class annotated using @WebService.

The service provider class can be a POJO in a web module or a stateless session EJB class in an EJB module.

In top-down development, you generate a provider class from a WSDL file.

In bottom-up development an existing Java class is Web Service enabled. System generates the WSDL file.

Although optional, it is recommended that you develop the SEI to capture the contract of the service.

18

Page 19: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 1 - Introduction to JAX-WS

Using JAX-WS, you can build a client for a service that may have been developed using any programming language.

A client uses the service class and stub to make operation calls.

A client uses the BindingProvider interface to configure various properties of the communication with the service provider.

19

Page 20: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as
Page 21: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

ObjectivesKey objectives of this chapter

What is WS-Addressing

WS-Addressing and Long Running Services

WS-Addressing SOAP Header Elements

Writing JAX-WS Clients to use WS-Addressing

Security and Firewall Issues

2.1 What is WS-Addressing?

Web Services Addressing (WS-Addressing) is a W3C specification that provides a standard, transport-neutral way of providing endpoint addresses for web services and storing them in messages

Typically HTTP serves as the transport protocol in which case URLs form the endpoint addresses. According to WS-Addressing specification, the URLs are found inside of SOAP messages as headers.

By storing the address of the service provider and in some cases the consumer within the SOAP message, we are able to solve a whole new set of problems. We will look at that next.

2.2 WS-Addressing and Long Running Services

WS-Addressing allows a client to invoke a service that can take days or weeks to complete. A long running process is a primary example of such a service.

Page 22: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

Seller (Service Provider)

Buyer (Consumer)

1. Operation: getPriceQuoteInput: Product ID

2. Ok, give me a few more days to work on it

3. Here’s the price

4. Thanks

WS-Addressing and Long Running Services

With WS-Addressing, the client-server communication goes as follows:

1. The client sends a SOAP request. In the SOAP header, the client includes a reply to URL endpoint. The server will later use this to send a callback notification as we will see shortly.

2. The Web Service implementation replies with an empty SOAP document right away. The implementation begins to do the work which can take a long time to finish.

3. Finally, when the Web Service implementation finishes doing the work, it sends a SOAP request to the client. The request contains the result of the work. This is actually the output of the operation invoked in step 1. This request is called a callback.

4. The client returns an empty SOAP reply document.

2.3 WS-Addressing and Long Running Services

When an operation takes a long time to complete, the client usually can’t afford to wait for a response. WS-Addressing resolves this problem through the use of the callback mechanism.

In this mechanism, the client sends a SOAP message to the service provider to invoke an operation. The SOAP request contains a URL where the server can send a callback SOAP request when the work is done. This is called the ReplyTo address.

◊ The service sends an empty SOAP response with HTTP status code 202 to acknowledge the request.

22

Page 23: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

2.4 WS-Addressing and Long Running Services

The client then waits for a callback request to come from the service. It does so by listening for SOAP requests.

Eventually, when the work is done in the service provider, it sends a SOAP request to the client using the ReplyTo address. This request contains the output result of the operation just completed.

◊ The client sends an empty SOAP response with HTTP status code 202 to acknowledge the callback.

It is possible that the client had sent many such requests to many service providers. Every callback request from a service provider must be correlated with the original request from the client. There are two ways you can correlate a callback with an operation invocation request. See the details below.

WS-Addressing and Long Running Services

Correlation of messages

WS-Addressing automatically assigns a unique message ID for every SOAP request in the <MessageID> element. The callback request contains a <RelatesTo> element that points to the ID of the original message.

2.5 Other Uses of WS-Addressing

In WS-Addressing each conversation has a unique correlation identifier. This mechanism can be exploited to implement stateful services. Each instance of the state is identified through the correlation identifier.

◊ WS-Resource specification is designed to deal with stateful services. It uses WS-Addressing.

Many WS-* specifications, such as WS-ReliableMessaging uses WS-Addressing under the covers. These specifications require out-of-band communication between the consumer and the service provider.

Other Uses of WS-Addressing

Stateful Services

23

Page 24: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

A stateful service can preserve state about a client. Every time the clients ends a request, the state needs to be located in the server among the state for the many clients that the server is maintaining. The correlation identifier used by WS-Addressing can be used for that.

Out-of-band Communication

Usually when a client invokes an operation a single SOAP request is generated. Some WS-* specifications require additional SOAP communications before and/or after the actual SOAP communication. These additional communication is to support infrastructural behavior such as ensured delivery. They are called out-of-band communication.

2.6 WS-Addressing SOAP Header Elements

WS-Addressing specifies a number of XML elements that go inside the SOAP <Header> to include various information:

◊ <wsa:To> - the destination endpoint for a message (service provider’s URI)

◊ <wsa:From> - the source endpoint for a message

◊ <wsa:ReplyTo> - the endpoint that the message recipient should send a response to

◊ <wsa:FaultTo> - the endpoint that the message recipient should send a fault to

◊ <wsa:Action> - a URI that identifies the meaning of the message. See details below.

◊ <wsa:MessageID> - a unique id for the message. Serves as a correlation id. It’s used by the client to match back to the original request that was made.

◊ <wsa:RelatesTo> - a URI corresponding with the related message’s <wsa:MessageID> property. Used when the service provider sends back a reply.

WS-Addressing SOAP Header Elements

wsa is a namespace prefix for the http://www.w3.org/2005/08/addressing namespace.

The Use of the <Action> Element

in WS-Addressing, the <action> element is mandatory in the SOAP header. It is meant to describe the nature of the request. For a regular application using WS-Addressing, this element can be set to any

24

Page 25: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

value. Some WS-* specifications that use WS-Addressing under the covers may use this element for internal purposes.

2.7 Example Client SOAP Request<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope"xmlns:wsa="http://www.w3.org/2005/08/addressing"xmlns:acme="http://www.acme.com"><S:Header> ... <wsa:To>http://www.acme.com/quote</wsa:To> <wsa:ReplyTo> <wsa:Address>http://clientHost:9080/quoteClientApp </wsa:Address> </wsa:ReplyTo>

<wsa:MessageID>urn:uuid:ABC</wsa:MessageID>

<wsa:Action> wsa:To>http://www.acme.com/quote/getPriceQuote </wsa:Action> ...</S:Header><S:Body>...</S:Body></S:Envelope>

Example Client SOAP Request

In this example above, we see how the <ReplyTo>, <To>, <MessageID>, and <Action> elements are set in the SOAP header.

2.8 Example Callback SOAP Request<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope"xmlns:wsa="http://www.w3.org/2005/08/addressing"xmlns:acme="http://www.acme.com"><S:Header> ... <wsa:To>http://clientHost:9080/quoteClientApp</wsa:To> <wsa:MessageID>urn:uuid:XYZ</wsa:MessageID> <wsa:RelatesTo>urn:uuid:ABC</wsa:RelatesTo>

25

Page 26: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

...</S:Header><S:Body>...</S:Body></S:Envelope>

Example Callback SOAP Request

In this example, we see how the <RelatesTo> element contains the ID of the original request message. The client can use this information to correlate the callback with the original request. We also see how the <To> element contains the address specified in the original request’s <ReplyTo> element.

2.9 Writing JAX-WS Clients to use WS-Addressing

WS-Addressing is programming-language neutral. In order to utilize it, you need to use a programming API

JAX-WS (Java API for XML-Based Web Services), which we use for creating Java-based web services, also provides a standard way of implementing WS-Addressing in Java

Typically, no changes needs to be made to the web service implementation. Develop a WSDL as usual and generate a skeletal service from it. Some of the operations in the service can be long running and have output parameters.

The bulk of the work takes place in the client (consumer) development. There are three special steps that need to be performed, which we’ll examine shortly:

◊ Annotate the WSDL file to enable asynchronous messaging

◊ Enable WS-Addressing in the client code

◊ Invoke the operation asynchronously

Writing JAX-WS Clients to use WS-Addressing

JAX-WS allows the same operations to be invoked synchronously or asynchronously. It depends on the client what mechanism will be used.

26

Page 27: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

2.10 Enabling Asynchronous Service Requests

The steps for creating the client are as follows:

◊ In the WSDL, add a namespace prefix for JAX-WS annotation tags:<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions name="movie_service" targetNamespace="http://www.mycom.com/movie" xmlns:jaxws="http://java.sun.com/xml/ns/jaxws" xmlns:m="http://www.mycom.com/movie" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

2.11 Enabling Asynchronous Service Requests

In the <portType> element, add the jaxws:enableAsyncMapping annotation to enable asynchronous messaging

<wsdl:portType name="movie_service"> <wsdl:operation name="addMovie"> <wsdl:input message="m:addMovieRequest"/> <wsdl:output message="m:addMovieResponse"/> </wsdl:operation> <jaxws:bindings> <jaxws:enableAsyncMapping> true </jaxws:enableAsyncMapping> </jaxws:bindings></wsdl:portType>

2.12 Enabling Asynchronous Service Requests

Generate the client side proxy code from the WSDL file. For each operation defined in the <portType>, three methods will be added to the proxy. For example, for the addMovie operation, these methods will be added:

◊ String addMovie(MovieType m) – This is the usual method that invokes an operation in a synchronous manner.

27

Page 28: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

◊ Response<AddMovieResponse> addMovieAsync(MovieType movie) – This method allows polling style asynchronous communication

◊ Future<?> addMovieAsync(MovieType movie, AsyncHandler<AddMovieResponse> asyncHandler) – This method needs to be called to use WS-Addressing. The method returns immediately. The AsyncHandler object is notified when the callback arrives from the service provider. The JAX-WS client runtime calls the handleResponse method of the AsyncHandler object to do that.

Enabling Asynchronous Service Requests

Future is a generic interface introduced in Java SE 6 that represents the result of an asynchronous operation.

2.13 Using WS-Addressing from the Client

In the client (servlet), create the proxy object as usual:MovieService_Service proxy = new MovieService_Service();MovieService svc = proxy.getMovieServiceSOAPPort();

Prepare the input object (a movie) as usual:MovieType movie = new MovieType();movie.setTitle("Back to the Future");movie.setRating("PG");movie.setDescription("A teenager travels back in time to 1955 in a Delorean, meets his parents, and must make sure they fall in love.");movie.getActor().add("Michael J. Fox");

2.14 Using WS-Addressing from the Client

There are two ways to enable WS-Addressing

◊ If the web service runtime supports JAX-WS 2.1 or later you can pass in an instance of the AddressingFeature class when creating the proxy

MovieService svc = proxy.getMovieServiceSOAPPort(

28

Page 29: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

new AddressingFeature()); ◊ Vendor-specific code. The following code is IBM specific:

BindingProvider bp = (BindingProvider) svc;bp.getRequestContext().put("com.ibm.websphere.webservices.use.async.mep", Boolean.TRUE);

Enabling WS-Addressing implies that the JAX-WS client and server runtimes are capable of generating and processing WS-Addressing headers

Using WS-Addressing from the Client

If you don't add the above code, there is only one request-response pair used, not two, and WS-Addressing is NOT used. The client actually waits to get a response back from the server before proceeding onwards. Hence, the invocation is synchronous, not asynchronous.<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <ns2:addMovie xmlns:ns2="http://www.mycom.com/movie"> <movie rating="PG" title="Back to the Future"> <description>A teenager travels back in time to 1955 in a Delorean, meets his parents, and must make sure they fall in love.</description> <actor>Michael J. Fox</actor> </movie> </ns2:addMovie> </soapenv:Body></soapenv:Envelope>

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <ns2:addMovieResponse xmlns:ns2="http://www.mycom.com/movie"> <status>SUCCESS:Back to the Future</status> </ns2:addMovieResponse> </soapenv:Body></soapenv:Envelope>

2.15 Providing an AsyncHandler to Handle Callbacks

Create the AsyncHandler anonymous inner class. It can also be a real class.

AsyncHandler<AddMovieResponse> ah = newAsyncHandler<AddMovieResponse>() { public void handleResponse(Response<AddMovieResponse>

29

Page 30: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

response) { try { String status = response.get().getStatus(); logger.info("Status: " + status); } catch (Exception e) { e.printStackTrace(); } }};

AsyncHandler is a generic interface defined by the JAX-WS specification that clients implement to receive asynchronous callbacks

The response.get() method returns the output data type of the invoked operation (AddMovieResponse in this case)

Providing an AsyncHandler to Handle Callbacks

Response is a generic interface introduced in Java SE 6 that extends the Future interface (also introduced in Java SE 6).

2.16 Providing an AsyncHandler to Handle Callbacks

Finally, invoke the addMovie operation asynchronously using WS-Addressing and supplying the AsyncHandler instance:

logger.info("Calling addMovieAsync");svc.addMovieAsync(movie, ah);logger.info("addMovieAsync has returned");

The following output will be printed to the console immediately:[7/17/08 11:50:22:406 EDT] 00000029 Client I Calling addMovieAsync[7/17/08 11:50:22:453 EDT] 00000029 Client I addMovieAsync has returned

2.17 WS-Addressing Headers in SOAP Messages

When the code runs, the client will include WS-Addressing headers in the

30

Page 31: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

SOAP request:<soapenv:Envelope><soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"> <wsa:To>http://localhost:9081/ServerWeb/MovieService</wsa:To> <wsa:ReplyTo> <wsa:Address>http://192.168.1.100:9080/IBM_WS_SYS_RESPONSESERVLET /ClientApp:ClientWeb.war/services/ MovieService.MovieServiceSOAPPort</wsa:Address> </wsa:ReplyTo> <wsa:MessageID>urn:uuid:DAACB25BD722A9A8BD1216341100249 </wsa:MessageID> <wsa:Action>http://www.mycom.com/movie/NewOperation</wsa:Action></soapenv:Header> ... Normal SOAP Body ....

After the work is finished in the server, you will see the output from handleResponse:

◊ [7/17/08 11:50:32:593 EDT] 0000003e Client I Status: SUCCESS:Back to the Future

WS-Addressing Headers in SOAP Messages

IBM WebSphere Application Server 7 was used as the runtime for the above example.

31

Page 32: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

2.18 WS-Addressing Sequence of Events

ServerWebClientWeb

Servlet

AsyncHandler

Movie Service Proxyand

Client Runtime

1. addMovieAsync(movie, ah)

2. Operation: addMovieInput: movie

Movie Service Class

6. handle-Response(response)

4. Callback request

3. Empty reply

5. Empty reply

WS-Addressing Sequence of Events

In the example above:

1. The client invokes the addMovieAsync operation on the movie service proxy. It passes it a MovieType object (movie) and a reference to the AsyncHandler object. AsyncHandler is a generic interface defined by the JAX-WS specification that clients implement to receive asynchronous callbacks.

2. The JAX-WS runtime generates a SOAP request. In the SOAP header, the client includes a reply to URL endpoint. The server will later use this to send a callback notification as we will see shortly.

3. The server runtime replies with an empty SOAP document right away. In the server side, the addMovie method of the service implementation class begins to execute, which takes a long time to finish.

4. After addMovie() method returns, the server runtime sends a SOAP request to the client. The request contains the result of the work. This is actually the output of the operation invoked in step 1. This request is called a callback.

5. The client runtime replies with an empty SOAP reply document.

6. The client runtime invokes the AsyncHandler’s handleReponse method passing it a Response object. The Response object maps to the addMovie operation’s output message, which means it

32

Page 33: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

contains a status element of type string.

2.19 Asynchronous "Polling"

Another approach to use the asynchronous capabilities of WS-Addressing is to have the client "poll" the Future object returned by invoking the service asynchronously

◊ This might be used for the situation where the client wants to wait for the service response before finishing but can do other tasks while waiting for the service response

The client can check if the 'Response' object returned by the 'xxxAsync' method is "Done" and get the response message if it is

Response<AddMovieResponse> response = svc.addMovieAsync(movie);

// Do other thingsif (response.isDone()) {

AddMovieResponse wrappedMessage = response.get();

// Work with the wrapped message like normalString status = wrappedMessage.getStatus();

}Asynchronous "Polling"

In the example above you could also write a loop that kept checking until the response from the service was done.

The "polling" approach might be a little easier to conceptualize since there is no separate "AsyncHandler" object involved.

2.20 Endpoint References

WS-Addressing defines a method of describing web service endpoints, for cases where information on those endpoints needs to be communicated as part of a web service exchange

◊ For example, in WS-Atomic Transactions, when a service “flows a context”, it needs to communicate the location of the transaction

33

Page 34: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

registration service, so that participants can join

◊ An endpoint reference looks like:<wsa:EndpointReference> <wsa:Address>xs:anyURI</wsa:Address> <wsa:ReferenceProperties>... </wsa:ReferenceProperties> ? <wsa:ReferenceParameters>... </wsa:ReferenceParameters> ? <wsa:PortType>xs:QName</wsa:PortType> ? <wsa:ServiceName PortName="xs:NCName"?>xs:QName</wsa:ServiceName> ? <wsp:Policy> ... </wsp:Policy>*</wsa:EndpointReference>

2.21 Endpoint References

Most of the pieces of the endpoint reference are self-explanatory

The 'Reference Parameters' are copied into the SOAP header when the endpoint is called

◊ For instance, the parameters might include a key or authentication token.

2.22 Associating Actions with WSDL Operations

Explicit Association: The “wsa:Action' attribute can be placed on the 'input' and 'output' message elements in the WSDL:

<definitions targetNamespace="http://example.com/stockquote" ...> ... <portType name="StockQuotePortType"> <operation name="GetLastTradePrice"> <input message="tns:GetTradePricesInput" wsa:Action="http://example.com/GetQuote"/> <output message="tns:GetTradePricesOutput" wsa:Action="http://example.com/Quote"/>

34

Page 35: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

</operation> </portType> ...</definitions>

2.23 Associating Actions with WSDL Operations

Implicit Associations:

◊ If the 'wsa:Action' attribute is not used, the action is derived from the namespace, port name, and input or output name.

◊ e.g. for above, ' http://example.com/stockquote/ StockQuotePortType/ GetTradePricesInput' would be the input action

2.24 Faults

If a WS-Addressing-compliant endpoint returns a fault, it must include message information headers on all fault messages, and use the following as the “action”:

http://schemas.xmlsoap.org/ws/2004/08/addressing/fault

2.25 Security and Firewall Issues

A man-in-the-middle application can alter the <ReplyTo> element and intercept the callback request. To prevent this, it is highly recommended that the SOAP message be signed by the client using WS-Security.

◊ That way, the server can ensure that the SOAP message was not altered in any way and that the message did come from the client and not from a man in the middle.

For the server to be able to send a callback SOAP request to the client,

35

Page 36: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 2 - WS-Addressing

the client must be accessible over the network. That means, you will need to open a firewall port on the client side. This may be problematic in some situations. For example, the client is a Windows desktop application that someone is using from an office or hotel room.

◊ If opening up a firewall is not an option, WS-Addressing will not work. Look for alternative ways, such as WS-Make Connection which is discussed in a separate chapter.

2.26 Summary

This chapter covered the following topics:

◊ What is WS-Addressing

◊ WS-Addressing and Long Running Services

◊ WS-Addressing SOAP Header Elements

◊ Writing JAX-WS Clients to use WS-Addressing

◊ Security and Firewall Issues

36

Page 37: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 3 - WS-ReliableMessaging

ObjectivesKey objectives of this chapter

What is WS-ReliableMessaging?

Why do we need this?

How does WS-ReliableMessaging work?

Introduction to WS-MakeConnection.

3.1 The Problem with HTTP

By default, HTTP protocol does not guarantee delivery of request or response messages. A message delivery can easily fail under these situations:

◊ Network connection is down between the client and the server.

◊ The recipient of the message, client or the server, is not available to receive it. This can happen due to a server crash, schedule maintenance shutdown or application malfunction.

As SOA becomes popular and more and more business interaction happens using Web Service, the unreliability of HTTP becomes a huge problem. For example, a lost request for order placement can harm both the buyer and the supplier.

Traditionally, the problem was solved by using SOAP over a messaging protocol instead of HTTP. For example, a SOAP message sent using a messaging product like WebSphere MQ or Microsoft MQ will guarantee delivery of the message.

SOAP over messaging works very well, but has one major problem – lack of standardization. For example, if the sender puts the SOAP message in a WebSphere MQ queue, the recipient must also use WebSphere MQ. This becomes a problem in business-to-business communication where you can not expect all businesses to use the same messaging product.

Page 38: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 3 - WS-ReliableMessaging

3.2 Enter WS-ReliableMessaging

Web Services Reliable Messaging (WS-ReliableMessaging or WS-RM for short) attempts to solve the problem of guaranteed delivery in a standard and vendor neutral fashion.

One of its major achievements is to enable guaranteed delivery over plain HTTP. Although, the specification does not restrict itself with HTTP, the ubiquitous nature of HTTP will make it a very popular protocol for reliable messaging.

In summary, two main advantages are:

◊ The sender and receiver can use plain HTTP protocol. There is no need to use expensive messaging software that have traditionally used proprietary protocols to achieve reliable messaging.

◊ The sender and receiver can use different vendor's Web Services platform. They should interoperate just fine (see details below).

Enter WS-ReliableMessaging

Web Services Interoperability (WS-I) has a special profile to deal with reliable messaging. This is called Reliable Secure Profile Version (WS-I RSP). As long as the Web Service vendor's WS-ReliableMessaging conforms to the guidelines put forward by this profile, it should interoperate well with another compliant vendor's implementation.http://www.ws-i.org/deliverables/workinggroup.aspx?wg=reliablesecure

3.3 When to Use Reliable Messaging?

Ask yourself what will happen if a SOAP request or response is lost? If that can cause lost revenue, reduced customer satisfaction and overall bad impression in the marketplace, you should consider reliable messaging.

◊ As a rule of thumb, messages exchanged outside of the company's boundary should be as reliable as possible. This is because you have little control over the reliability of the public networks. Also, lost messages involving a customer or partner organization generally has more negative implication than internal communication failure.

You can also use WS-ReliableMessaging to implement disconnected

38

Page 39: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 3 - WS-ReliableMessaging

computing. For example, a sales person can file an expense on the road while disconnected. System will fail to send SOAP messages due to the lack of network connection. As soon as the laptop connects to the network the messages are sent.

WS-RM also allows sending a very large message in multiple chunks. Only the segments that fail to transfer need to be retried. This speeds up error recovery.

The sender's application does not have to wait for the entire message to be transported to the receiver. It can submit the message to its Web Service's platform which deals with the message transfer and error recovery. This makes applications that send large messages more responsive to the user.

3.4 How Does WS-RM Work?

Client App(sender)

WS-RMRuntime

1. Send message

Server App(Receiver)

WS-RMRuntime

6. Deliver message2. Transmit message

3. HTTP 202 Reply

4. Send Acknowledgement

5. HTTP 202 Reply

A client can send a one-way message for an operation that returns no output or a two-way message involving an input and an output message.

For each input or output message, a pair of separate SOAP requests are used. The first request sends the message. The second request comes from the recipient acknowledging the receipt. See details below.

If the sender does not get the acknowledgement within a specific time limit, it re-sends the original request. This is how any problems with the network or server runtime is handled.

39

Page 40: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 3 - WS-ReliableMessaging

How Does WS-RM Work?

In the example above, we see how a one-way operation call is made by a client. In this case, there is only the input message and the operation does not return any output. The sequence of activities as follows:

1. The client submits the message with the WS-RM runtime and returns immediately. It does not wait for the message to be transferred.

2. The WS-RM runtime on the client side sends a SOAP request containing the input message to the WS-RM time of the recipient. In case of any failure, the message is sent again.

3. The server side replies immediately with an empty SOAP message and HTTP status code 202. The server side saves the message somewhere. This will be delivered to the server application whenever suitable.

4. The server side sends a SOAP request to the client (sender) acknowledging the delivery. In advanced situations, the sender sends a large message in multiple chunks. The acknowledgement message lists all the segments that have been received so far. If this list is missing some of the segments, or the sender does not get the acknowledgement message in time, the missing segments or the entire message is sent again.

5. The original sender replies back with an empty SOAP message and HTTP status code 202.

6. At some point of time, the server's WS-RM runtime delivers the message to the Web Service implementation code. That means, the Web Service does not have to be available when the message was transferred. Also, if a large message was sent in chunks, the receiver's WS-RM runtime will make sure that all the chunks are available before delivering the message to the service implementation.

3.5 Importance of Persistence

For truly guaranteed deliver, the WS-RM runtime of sender and receiver should always save messages in a durable storage.

For example, in case of a network problem, the sender may have to keep on trying to transmit a message. Meanwhile, the sender's machine or runtime may be restarted due to power failure of any unforeseen reason. If the message was persisted, the sender's WS-RM runtime can continue to retry. Otherwise, the message will be lost.

For performance reasons, your Web Service vendor may persist the messages in memory only. That is fine for development. In production choose a durable storage mechanism.

40

Page 41: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 3 - WS-ReliableMessaging

3.6 The Problem With Firewall

WS-ReliableMessaging depends heavily on the WS-Addressing standard. The acknowledgement message is actually a WS-Addressing callback notification.

This means, the sender will have to open ports in firewall for the receiver to be able to connect and send a message. This may be a problem if the sender is a desktop machine behind a firewall that the user has no control over (such as an airport or hotel room).

To work around the problem the WS-MakeConnection specification was created. Starting with WS-RM 1.1, WS-MakeConnection can be used as an alternative to WS-Addressing.

You can also use WS-MakeConnection on its own in place of WS-Addressing to solve the problems that WS-Addresisng solves (asynchronous notification).

We will now briefly discuss WS-MakeConnection and how it is used by WS-RM.

3.7 How Does WS-MakeConnection Work?

Client Server1. GetQuote(ReplyTo=Xyz)

2. HTTP 202

3. MakeConnection(Address=Xyz)

4. HTTP 202

5. MakeConnection(Address=Xyz)

6. GetQuoteResponse

WS-MakeConnection allows a client to start a long running task in the server and find out when the work is done. It uses a polling approach compared to Ws-Addressing that uses a callback approach.

The original request from the client contains a ReplyTo address using the

41

Page 42: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 3 - WS-ReliableMessaging

same mechanism as WS-Addressing. Except, the address is not a real URL but a unique identifier of the request. The server can take a long time to process this request.

The client periodically sends a MakeConnection request to the server. The Address value contains the request identifier. If the server is still processing the original request, an empty SOAP reply with HTTP status code 202 is sent. Otherwise, the server sends a SOAP reply that contains the result of the operation call.

How Does WS-MakeConnection Work?

In the example above, client invokes the GetRequest operation of the service that can take several hours to complete.

1. Client sends a SOAP request to the server. The SOAP header contains <ReplyTo> which contains a unique identifier of the request.

2. Server responds immediately with an empty SOAP reply and HTTP status code 202.

3. After a while, the client sends a MakeConnection SOAP request. The <Address> element in the SOAP header contains the original request identifier.

4. Server responds with an empty SOAP reply and HTTP status code 202. This tells the client that the work is still in progress.

5. Client sends a MakeConnection request again.

6. This time, the server responds with the output of the GetRequest operation.

3.8 Using WS-MakeConnection

You can use this approach pretty much as an alternative to WS-Addressing. In fact, WS-RM 1.1 gives you an option of using either.

If it is not possible for the sender to open firewall ports, use WS-MakeConnection.

You should be aware of some of the issues with this polling type approach:

◊ Sender may send several MakeConnection requests increasing network chatter.

◊ The callback mechanism of WS-Addressing notifies the sender of

42

Page 43: WA2103 Programming Java SOAP Web Services with JAX- WS ... · Chapter 1 - Introduction to JAX-WS 1.3 Why Do We Need a Programming Model? A Web Services programming model, such as

Chapter 3 - WS-ReliableMessaging

completion of work in real time. On the other hand, with the polling approach there may be delay between when the work is actually done in the server and when the sender sends a MakeConnection request.

3.9 Summary

There are compelling business reasons to choose reliable messaging.

WS-Reliable messaging makes a great contribution to SOA by enabling guaranteed delivery over plain HTTP.

We also discussed WS-MakeConnection that can solve the problem that WS-Addressing has with firewall.

43