Enterprise Integration Zone is brought to you in partnership with:

Meera has posted 70 posts at DZone. You can read more from them at their website. View Full User Profile

Creating SOAP Message Handlers in 3 Simple Steps - Part 1

08.13.2008
| 48499 views |
  • submit to reddit

This tutorial takes a look at SOAP Message handlers and how easy it is to write handlers using JAX-WS 2.0. JAX-WS 2.0 allows both regular Java classes and stateless EJBs(Session beans) to be exposed as web services. The JAX-WS 2.0 is the core specification that defines the web services standard for Java EE 5 specification. JAX-WS 2.0 is an extension of the Java API for XML-RPC (JAX-RPC) 1.0.

SOAP message handlers are used to intercept the SOAP message as they make their way from the client to the end-point service and vice-versa. These handlers intercept the SOAP message for both the request and response of the Web Service. If you are familiar with EJB interceptors, handlers are similar to EJB interceptors and are defined in an XML file.

A few typical scenarios where you would be using SOAP Message handlers are: to encrypt and decrypt messages, to support logging, caching and in some cases auditing, and in rare cases to provide transaction management as well.

So much for the theory. Lets see the three basic steps to use a simple log handler to intercept and print our SOAP messages (request and response).

In this tutorial, we are going to expose an EJB 3 stateless session bean as a web service which is simple and can be done by adding the @WebService annotation. So, here comes the source code for the interface as well as the implementation class which is self explanatory:

Listing 1: Remote Interface

package com.ws;

import javax.ejb.Remote;

/**
*
* @author meerasubbarao
*/
@Remote
public interface HelloWebServiceRemote {

String sayHello(String name);

}

Listing 2: Bean Implementation

package com.ws;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
*
* @author meerasubbarao
*/
@WebService
@Stateless
public class HelloWebServiceBean implements HelloWebServiceRemote {

@WebMethod(operationName = "sayHello")
public String sayHello(@WebParam(name = "name") String name) {
return "Hello " + name;
}


}

You can package the two source files in a jar, deploy to your application server, and test it. Quite simple, right? For this tutorial, I am using GlassFish V2 application server and SoapUI to test my web services. Shown below are the request and response from SoapUI:



Now that we know our web services work, lets start writing the message handler, which as I said earlier is just 3 steps. So, what are these SOAP message handlers? They are simple Java classes that can used to modify SOAP messages; both request as well as response. These handlers have access to both the SOAP header as well as the body of the message.

Lets move on to create SOAP message handlers:

Step 1. Implement the SOAPHandler interface.

package com.ws;

import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/**
*
* @author meerasubbarao
*/
public class LogMessageHandler implements SOAPHandler<SOAPMessageContext> {

public boolean handleMessage(SOAPMessageContext messageContext) {
return true;
}

public Set<QName> getHeaders() {
return Collections.EMPTY_SET;
}

public boolean handleFault(SOAPMessageContext messageContext) {
return true;
}

public void close(MessageContext context) {
}

}

The handleMessage() method is invoked for both incoming as well as outgoing messages. Lets add a new method called log() and invoke this method from the handleMessage method. Shown below are both the methods:

 private void log(SOAPMessageContext messageContext) {
SOAPMessage msg = messageContext.getMessage(); //Line 1
try {
msg.writeTo(System.out); //Line 3
} catch (SOAPException ex) {
Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}

In line 1, we are retrieving the SOAPMessage from the message context. Line 3 will print the incoming and outgoing messages in our GlassFish console.

Invoke this method from within the handleMessage() as shown:

public boolean handleMessage(SOAPMessageContext messageContext) {
log(messageContext);
return true;
}

Step 2: Create the XML file for the Handler Chain.

Create this XML file in the same package as the web service with the name LogMessage_handler.xml.

<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
<handler-chain>
<handler>
<handler-name>com.ws.LogMessageHandler</handler-name>
<handler-class>com.ws.LogMessageHandler</handler-class>
</handler>
</handler-chain>
</handler-chains>

Lets take a close look at the various elements used above:

1. <handler-chains> is the root element that will contain a list of all handler chains that are defined for the Web Service.
2. The <handler-chain> child element of the <handler-chains> element lists all the handlers in the handler chain.
3. Within the <handler-chain> element is defined the <handler>, each handler element must in turn specify the name and also the fully qualified name of the Java class that implements the handler. If you have more than one handler, specify each one of them within the handler-chain element.

Step 3: Invoking the Handler

The @HandlerChain annotation is used to define a set of handlers that are invoked in response to a SOAP message. So, within our HelloWebServiceBean implementaion, you need to make a simple change to invoke the Log Handler as shown below in Line 1:

package com.ws;

import javax.ejb.Stateless;
import javax.jws.HandlerChain;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
*
* @author meerasubbarao
*/
@WebService
@Stateless
@HandlerChain(file = "LogMessage_handler.xml") // Line 1
public class HelloWebServiceBean implements HelloWebServiceRemote {

@WebMethod(operationName = "sayHello")
public String sayHello(@WebParam(name = "name") String name) {
return "Hello " + name;
}
}

We added the annotation for the handlers; lets recompile, repackage and redeploy the application.

Now invoke the web service from SoapUI and see if it works. If it does, we should be able to see the request and response logged in our GlassFish console window.

Here is the final output:

**RemoteBusinessJndiName: com.ws.CustomerManagerRemote; remoteBusIntf: com.ws.CustomerManagerRemote
LDR5010: All ejb(s) of [EJBWebServices] loaded successfully!
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.com/"><soapenv:Header/><soapenv:Body><ws:sayHello>

<name>Javalobby</name>
</ws:sayHello></soapenv:Body></soapenv:Envelope>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:sayHelloResponse xmlns:ns2="http://ws.com/"><return>Hello Javalobby</return></ns2:sayHelloResponse></S:Body></S:Envelope>

In this article, we saw how simple and easy it was to create and use SOAP Handlers to intercept request and response of SOAP messages. We implemented the SOAPHandler interface, wrote minimal XML to define the handler chain, and finally added one simple annotation to the web service implementation class. We were also able to test these web service using SoapUI.

In Part 2 of this series, we will see how to actually parse the SOAP Headers, and also use multiple handlers. Stay tuned for more..

Published at DZone with permission of its author, Meera Subbarao.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: