DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Consuming SOAP Service With Apache CXF and Spring
  • Web Service Testing Using Neoload
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above

Trending

  • Scalable System Design: Core Concepts for Building Reliable Software
  • Emerging Data Architectures: The Future of Data Management
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • GDPR Compliance With .NET: Securing Data the Right Way
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Creating SOAP Message Handlers in 3 Simple Steps - Part 1

Creating SOAP Message Handlers in 3 Simple Steps - Part 1

By 
Meera Subbarao user avatar
Meera Subbarao
·
Aug. 13, 08 · Interview
Likes (0)
Comment
Save
Tweet
Share
85.6K Views

Join the DZone community and get the full member experience.

Join For Free

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 */@Remotepublic 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@Statelesspublic 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:

Image title



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 1public 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..

SOAP Web Protocols Web Service

Opinions expressed by DZone contributors are their own.

Related

  • Consuming SOAP Service With Apache CXF and Spring
  • Web Service Testing Using Neoload
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!