Monday May 11, 2009

Asynchronous Webservice

Asynchronous Webservice Client: Client side asynchrony can be achieved using the following,

  1. Async Polling

  2. Async Callback-handler

1. Create a Calculator Application using the examples which comes with glassfishesb/netbeans

 calculator app

2.  Observe the webservice client for the above, note the webservice interface has a single operation which is by default a synchronous call, we will see how to generate the interface which makes the same call in an asynchronous way

3. Enable Asynchronous Client : note the interface now has two more operations

enable asyn client

4. How to invoke using the above generated service endpoint interface ,

Async Polling

The client application will invoke the async polling operation on the stub and check for a response on the Response object. The response is available when Response.isDone returns true.<com.sun.CalculateResponse> resp = port.calculateAsync(x, y);
 while(!resp.isDone()) {
  // do something

System.out.println("Result = "+resp.get().getReturn());

Async CallbackHandler

In this case the  client application has to provide an AsyncHandler by implementing the<T> interface.

// Async callback handler

class CalculatorWSCallbackHandler implements<com.sun.CalculateResponse> {
    private com.sun.CalculateResponse output;

    public void handleResponse(<com.sun.CalculateResponse> response) {
        try {
            output = response.get();
        } catch(Exception ex) {
            // handle exception

    com.sun.CalculateResponse getResponse() {
         return output;

// The async handler is then passed as a parameter of the async callback method:

CalculatorWSCallbackHandler asyncHandler = new CalculatorWSCallbackHandler();
 // process asynchronous response here
 java.util.concurrent.Future<? extends java.lang.Object> result = port.calculateAsync(x, y, asyncHandler);
 while(!result.isDone()) {
  // do something
 out.println("Result = "+asyncHandler.getResponse().getReturn());

5. Using the Dispatch Api

Four types of MEP are supported using the dispatch API

  • Object response = dispatch.invoke(T);

  • dispatch.invokeOneway(T);

  • Response<T> response = dispatch.invokeAsync(T);

  • Future<?> response = dispatch.invokeAsync(T, AsyncHandler);

The example shows how the asynchronous invocation can be made while using the SOAPMessage

Aysnc Polling

Response<SOAPMessage> res = dispatch.invokeAsync(soapMessage);
 while (!res.isDone()) {
     //do some work
 SOAPMessage soapM = res.get();

Async CallbackHandler

class ResponseHandler implements<SOAPMessage> {

 SOAPMessage output = null;

 public void handleResponse(Response<SOAPMessage> arg0) {
     try {
  output = arg0.get();
     } catch (Exception e) {
  // handle exception
 SOAPMessage getResponse() {
     return output;

 ResponseHandler rhandler = new ResponseHandler();
 Future<? extends java.lang.Object> f = dispatch.invokeAsync(message, rhandler);
     //do some work
 SOAPMessage m = rhandler.getResponse();

Using WS-Addressing

WS-addressing supports asynchronous MEP , here is one example taken from the specification, Note the replyTo part of the Request message, Any service implementing ws-addressing specification will send the response message based on the replyTo Message addresing property


    <wsa:To S:mustUnderstand="1">http://fabrikam123.example</wsa:To>


    <wsa:To S:mustUnderstand="1">


The diagram below shows the flow  of messages


Note: if replyTo contains an anonymous URI

When an application/client uses anonymous URI, it says that there is no real endpoint available for this address. Using the anonymous URI is equivalent to not using the ReplyTo header, the response must flow back in the HTTP response message. The web-service must be able to dynamically switch between synchronous and asynchronous modes on the basis of replyTo or faultTo headers.


More info

  1. Async Client

  2. WS-Addressing

Tuesday Mar 03, 2009

WS-Addressing and stateful webservice


WS-addressing and its use

  • Provides transport-neutral mechanisms to address Web services and messages.

  • Stateful webservice, Web services are usually stateless, , however it is possible to enable webservice to be stateful i.e. to share multiple instances of service endpoints between subsequent invocation.

  • Simple and complex Message Exchange Patterns

  • Used for other WS-\* specification like reliable Messaging, WS-MetadataExchange, WS-Security

WS-Addressing and stateful webservice

We will dive in details how stateful sebservice is created? how a client can access the same? and how metro/jax-ws maintain the state in between subsequent invocation?, We will make use of the examples which comes with metro/jax-ws RI


Server ( and

@Stateful @WebService @Addressing
public class Book {
    private final String id;
    private volatile List<String> reviews = new ArrayList<String>();
    public Book(String id) { = id;
    public String getId() {
        return id;
    public synchronized void postReview(String review) {
        List<String> l = new ArrayList<String>(reviews);
        reviews = l;
    public List<String> getReviews() {
        return reviews;
    public boolean equals(Object that) {
        if (that == null || this.getClass() != that.getClass()) return false;
    public int hashCode() {
        return id.hashCode();

    public static StatefulWebServiceManager<Book> manager;

public class BookStore {
    public W3CEndpointReference getProduct(String id) {
        return Book.manager.export(new Book(id));

See the which is stateful webservice, this is done by declaring Stateful annotation on a class. Note the class also have a public static method/field that takes StatefulWebServiceManager. Once the service is deployed the jax-ws does the resource injection on the field or the method. A stateful web service ( does not need to have a default constructor. Most of the time user would to define a constructor that takes some arguments, so that each instance carries certain state. Each instance of a stateful web service( is identified by an unique EndpointReference. creates an instance of a class, JAX-WS RI assign a unique EPR for the instance as follows   Book.manager.export(new Book(id))

        BookStore bookstore = new BookStoreService().getBookStorePort();
        BookService service = new BookService();

        1. Book book1 = service.getPort(bookstore.getProduct("abc001"), Book.class);
        2.  book1.getId();
        3. book1.postReview("This book is great!");
        4. book1.getReviews();

        similar code for book2....

Once the client runtime receives the EPR info , it uses the EPR info in the subsequent call, i.e When client send messages to this EPR, the JAX-WS RI makes sure that the particular exported instance associated with that EPR will receive a service invocation. We will see shortly how this is achieved


Digging Deeper 

We will trace the soap request response for the client code (line 1, 2, and 3). This will give an clear idea how an Endpoint can associate the request with an exported instance of an EPR, and how the exported instance is  identified using an unique Identifier. 

1. Invoke BookStore service( bookstore.getProduct("abc001")) , Note the soap request-response, The response contain the EPR details which contains the address and the unique <jaxws:objectid>, note this objectid is used in subsequent call to the BookService, and this how the jaxws RI find out which instance of the EPR will get the invocation

get endpoint reference 

2. book1.getId(); note the soap request, here the jax-ws inserts the required addressing headers and the <jaxws:objectid>,  

get id of the book 

3.  book1.postReview("This book is great!"); note the soap request, here also the jax-ws inserts the required addressing headers and the <jaxws:objectid>,  

post review of the book


 More Info



Tuesday Feb 24, 2009

WS-SecureConversation, Improve performance of your Webservice

Public key cryptography

WS-Security make extensive use of the public key cryptography. Public key cryptography(asymmetric key) is computationally more expensive than symmetric key cryptographic, see the following link for more  info, so the solution is to make use of combination of asymmetric and symmetric key cryptography.  


While message authentication is useful for simple or one-way messages, parties that wish to exchange multiple messages typically establish a secure security context in which to exchange multiple messages. A security context is shared among the communicating parties for the lifetime of a communications session. Once the context and secret have been established (authenticated), Derived Keys can be used for signing and encryption of the messages. Some of features of ws-secureconversation are

  • similar to SSL

  • create a security context

  • message processing is  much faster at both client and webservice endpoint

  • transparent to the user 


 Esstablishing Security Context

A security context needs to be created and shared by the communicating parties before being used. This is done by creatring a Security Context Token(SCT). The specification defines three different ways of establishing a security context among the parties of a secure communication.

  • SCT created by a  STS(security token service)

  • SCT created by one of the communicating parties and propagated with a message

  • SCT created through negotiation/exchanges

WS-Secure Conversation is built on top of two other web services specifications, they are WS-Security and WS-Trust. In metro/wsit each web service enabled for WS-SecureConversation has an associated STS that is used to issue and manage security contexts

To request a Security Context Token(SCT) , an RequestSecurityToken(RST) is sent to the webservice endpoint which is setup using secure conversation , the request is transparently routed to the trust service which responds with a RequestSecurityTokenResponse , the response is send back to the client, Note the sample below also show DerivedKeyToken, we will talk about derived keys in a moment.

 Sample SecurityContextToken and DerivedKeyToken



                xmlns:ns16="" wsu:Id="_3">
    <wsse:SecurityTokenReference wsu:Id="_5002">
        <wsse:Reference ValueType="" URI="#uuid-4063ae9b-fe66-4e09-a5fb-8fda903f34d8" />


note the element /wsc:SecurityContextToken/wsc:Identifier This required element identifies the security context using an absolute URI. Each security context URI MUST be unique to both the sender and recipient. It is RECOMMENDED that the value be globally unique in time and space 

Derived Keys  

A security context token implies or contains a shared secret. This secret MAY be used for signing and/or encrypting messages, but it is RECOMMENDED that derived keys be used for signing and encrypting messages associated only with the security context

Using a common secret, parties may define different key derivations to use. For example, four keys may be derived so that two parties can sign and encrypt using separate keys. In order to keep the keys fresh (prevent providing too much data for analysis), subsequent derivations may be used 

 how the derived keys are used


How Keys are derived? 

A subset of the mechanism defined for TLS in RFC 2246. Specifically, P_SHA-1 function is used to generate a sequence of bytes that can be used to generate security keys. the algorithm is refered to as:

This function is used with three values – secret, label, and seed. The secret is the shared secret that is exchanged (note that if two secrets were securely exchanged, possible as part of an initial exchange, they are concatenated in the order they were sent/received).Secrets are processed as octets representing their binary value (value prior to encoding). The label is the concatenation of the client's label and the service's label. These labels can be discovered in each party's policy (or specifically within a <wsc:DerivedKeyToken> token). Labels are processed as UTF-8 encoded octets. If either isn't specified in the policy, then a default value of "WS-SecureConversation" (represented as UTF-8 octets) is used. The seed is the concatenation of nonce values (if multiple were exchanged) that were exchanged (initiator + receiver). The nonce is processed as a binary octet sequence (the value prior to base64 encoding). The nonce seed is required, and MUST be generated by one or more of the communicating parties.The P_SHA-1 function has two parameters – secret and value. The label and the seed is concatenated to create the value. That is:

P_SHA1 (secret, label + seed)

Syntax For Derived Keys

<DerivedKeyToken wsu:Id="..." Algorithm="...">


for more details for each of the element see the specification

How To Configure in Composite Application/WSIT editor

GlasfishESB , metro support the following security profiles, chose one of the security profile in the CASA editor and then configure for secure-conversation

  • Username Authentication with Symmetric Keys

  • Mutual Certificates Security

  • Transport Security (SSL)

  • Message Authentication over SSL

  • SAML Authorization over SSL

  • Endorsing Certificate

  • SAML Sender Vouches with Certificates

  • SAML Holder of Key

  • STS Issued Token

  • STS Issued Token with Service Certificate

  • STS Issued Endorsing Token

how to configure

Thursday Feb 12, 2009

Mtom, Soap with Attachment in Composite Applications

Mtom is used to optimize the transmission of soap message over the wire. MTOM uses a  wire format of a SOAP message by selectively encoding portions of the message, whilst still presenting an XML Infoset to the SOAP application. Optimization is available only for element content that is in a canonical lexical representation of the xs:base64Binary data type  

This article talks how to use mtom in glassfish esb, what are the limitation current implementation has , how to overcome the same

[Read More]

Thursday Feb 05, 2009

Soap1.2 in GlassfishESB

This article show how to use soap1.2 in glassfishesb or javacaps or openesb, also talks about some of the point to note in terms of changes or the differences with soap1.1 

[Read More]



« September 2016