JAX-WS SOAP handler client side

In the previous article, We have created a web service and attached a handler to retrieve the client MAC address in header block, for every incoming SOAP message.

In this article, we will create a web service client which can access the web service published in previous article.

Most important thing here is to define a SOAP handler to the client so that every outgoing message from client will have a client’s MAC address added in the header of a SOAP message.

Step 1

Create a maven project
soap_handler_client_proj_structure

Step 2

Run wsimport command

wsimport command generates all the required files by taking WSDL generated by the published service in the previous article.

wsimport -keep http://localhost:8888/ws/soapHandler?wsdl -d C:\Users\RAJ\Desktop\output
-keep : option to keep the generated files
-d : option to sepcify the folder where the generated files will be stored

soap_handler_wsimport_cmd_line_output

Now check the Output in the folder
Command has generated 6 source files and 6 class files

soap_handler_wsimport_cmd_files_output

We need to concentrate only on HelloWorldServiceImplService.java for client development

Step 3

Copy all these generated source files into project

HelloWorldServiceImplService.java looks like below

  1. import java.net.MalformedURLException;
  2. import java.net.URL;
  3. import javax.xml.namespace.QName;
  4. import javax.xml.ws.Service;
  5. import javax.xml.ws.WebEndpoint;
  6. import javax.xml.ws.WebServiceClient;
  7. import javax.xml.ws.WebServiceException;
  8. import javax.xml.ws.WebServiceFeature;
  9.  
  10.  
  11. /**
  12.  * This class was generated by the JAX-WS RI.
  13.  * JAX-WS RI 2.2.9-b130926.1035
  14.  * Generated source version: 2.2
  15.  *
  16.  */
  17. @WebServiceClient(name = "HelloWorldServiceImplService", targetNamespace = "http://ws.kb.com/",
  18.                                    wsdlLocation = "http://localhost:8888/ws/soapHandler?wsdl")
  19. public class HelloWorldServiceImplService
  20.     extends Service
  21. {
  22. ………………………………………………………
  23. }
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 * 
 */
@WebServiceClient(name = "HelloWorldServiceImplService", targetNamespace = "http://ws.kb.com/", 
                                   wsdlLocation = "http://localhost:8888/ws/soapHandler?wsdl")
public class HelloWorldServiceImplService
    extends Service
{
………………………………………………………
}


Step 4

Create a SOAP Handler

  1. package com.kb;
  2.  
  3. import java.io.IOException;
  4. import java.util.Set;
  5.  
  6. import javax.xml.namespace.QName;
  7. import javax.xml.soap.SOAPConstants;
  8. import javax.xml.soap.SOAPEnvelope;
  9. import javax.xml.soap.SOAPException;
  10. import javax.xml.soap.SOAPHeader;
  11. import javax.xml.soap.SOAPHeaderElement;
  12. import javax.xml.soap.SOAPMessage;
  13. import javax.xml.ws.handler.MessageContext;
  14. import javax.xml.ws.handler.soap.SOAPHandler;
  15. import javax.xml.ws.handler.soap.SOAPMessageContext;
  16.  
  17. public class MACAddressInjectHandler implements SOAPHandler<SOAPMessageContext>{
  18.  
  19.     public boolean handleMessage(SOAPMessageContext context) {
  20.         System.out.println("Client : handleMessage() Begin");
  21.         Boolean outBoundProperty  = (Boolean)
  22.                                           context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
  23.         //If its an outgoing message from client, then outBoundProperty will be true
  24.         if(outBoundProperty){
  25.             try{
  26.                 SOAPMessage soapMsg = context.getMessage();
  27.                 SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
  28.                     SOAPHeader soapHeader = soapEnv.getHeader();
  29.  
  30.                     //if no header, add the header
  31.                 if (soapHeader == null){
  32.                     soapHeader = soapEnv.addHeader();
  33.                  }
  34.                 String macAddress = getMACAddress();
  35.                      
  36.                 //add a soap header called "macAddress"
  37.                 QName qname = new QName("http://ws.kb.com/", "macAddress");
  38.                 SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(qname);
  39.  
  40.                 soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
  41.                 //Add MAC address to SOAP header
  42.                 soapHeaderElement.addTextNode(macAddress);
  43.                 soapMsg.saveChanges();
  44.  
  45.  
  46.                    //Output the message to console
  47.                    soapMsg.writeTo(System.out);
  48.  
  49.                 }catch(SOAPException e){
  50.                     System.err.println(e);
  51.                 }catch(IOException e){
  52.                     System.err.println(e);
  53.                 }
  54.  
  55.                 }
  56.  
  57.               //Returning true makes other handler chain to continue the execution
  58.               return true;
  59.     }
  60.  
  61.     public boolean handleFault(SOAPMessageContext context) {
  62.         System.out.println("Client : handleFault() Begin");
  63.         return true;
  64.     }
  65.  
  66.     public void close(MessageContext context) {
  67.         System.out.println("Client : close() Begin");
  68.        
  69.     }
  70.  
  71.     public Set<QName> getHeaders() {
  72.         System.out.println("Client : getHeaders() Begin");
  73.         return null;
  74.     }
  75.    
  76.     private String getMACAddress(){
  77.         //Write a java code to get client machine MAC address and return it dynamically
  78.         //Returning valid MAC address
  79.         return "E0-DB-55-A4-10-Z4";
  80.  
  81. //Returning invalid MAC address
  82.         //return "E0-DB-55-A4-10-Q1";
  83.     }
  84. }
package com.kb;

import java.io.IOException;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
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;

public class MACAddressInjectHandler implements SOAPHandler<SOAPMessageContext>{

	public boolean handleMessage(SOAPMessageContext context) {
		System.out.println("Client : handleMessage() Begin");
		Boolean outBoundProperty  = (Boolean) 
                                          context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		//If its an outgoing message from client, then outBoundProperty will be true
		if(outBoundProperty){
			try{
			    SOAPMessage soapMsg = context.getMessage();
			    SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
		            SOAPHeader soapHeader = soapEnv.getHeader();

		            //if no header, add the header
			    if (soapHeader == null){
			    	soapHeader = soapEnv.addHeader();
			     }
			    String macAddress = getMACAddress();
		             
			    //add a soap header called "macAddress"
	            QName qname = new QName("http://ws.kb.com/", "macAddress");
	            SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(qname);

	            soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
	            //Add MAC address to SOAP header
	            soapHeaderElement.addTextNode(macAddress);
	            soapMsg.saveChanges();


			       //Output the message to console
			       soapMsg.writeTo(System.out);

				}catch(SOAPException e){
					System.err.println(e);
				}catch(IOException e){
					System.err.println(e);
				}

			    }

			  //Returning true makes other handler chain to continue the execution
			  return true;
	}

	public boolean handleFault(SOAPMessageContext context) {
		System.out.println("Client : handleFault() Begin");
		return true;
	}

	public void close(MessageContext context) {
		System.out.println("Client : close() Begin");
		
	}

	public Set<QName> getHeaders() {
		System.out.println("Client : getHeaders() Begin");
		return null;
	}
	
	private String getMACAddress(){
		//Write a java code to get client machine MAC address and return it dynamically
		//Returning valid MAC address
		return "E0-DB-55-A4-10-Z4";

//Returning invalid MAC address
		//return "E0-DB-55-A4-10-Q1";
	}
}


In this handler , we are just adding MAC address to the SOAP header

Step 5

Create a SOAP handler xml file

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee"
  3.     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  4.     <javaee:handler-chain>
  5.         <javaee:handler>
  6.             <javaee:handler-
  7.                             class>com.kb.handler.MACAddressInjectHandler</javaee:handler-class>
  8.         </javaee:handler>
  9.     </javaee:handler-chain>
  10. </javaee:handler-chains>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema">
	<javaee:handler-chain>
		<javaee:handler>
			<javaee:handler-
                            class>com.kb.handler.MACAddressInjectHandler</javaee:handler-class>
		</javaee:handler>
	</javaee:handler-chain>
</javaee:handler-chains>


We have created the handler-chain.xml file to add our SOAP handler MACAddressInjectHandler in the handler list.

Step 6

Attach a SOAP handler to web service client

  1. package com.kb.ws;
  2.  
  3. import java.net.MalformedURLException;
  4. import java.net.URL;
  5.  
  6. import javax.jws.HandlerChain;
  7. import javax.xml.namespace.QName;
  8. import javax.xml.ws.Service;
  9. import javax.xml.ws.WebEndpoint;
  10. import javax.xml.ws.WebServiceClient;
  11. import javax.xml.ws.WebServiceException;
  12. import javax.xml.ws.WebServiceFeature;
  13.  
  14.  
  15. /**
  16.  * This class was generated by the JAX-WS RI.
  17.  * JAX-WS RI 2.2.9-b130926.1035
  18.  * Generated source version: 2.2
  19.  *
  20.  */
  21. @WebServiceClient(name = "HelloWorldServiceImplService", targetNamespace = "http://ws.kb.com/", wsdlLocation = "http://localhost:8888/ws/soapHandler?wsdl")
  22. @HandlerChain(file="../handler/handler-chain.xml")
  23. public class HelloWorldServiceImplService
  24.     extends Service
  25. {
  26. ………………………………………………………
  27. }
package com.kb.ws;

import java.net.MalformedURLException;
import java.net.URL;

import javax.jws.HandlerChain;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 * 
 */
@WebServiceClient(name = "HelloWorldServiceImplService", targetNamespace = "http://ws.kb.com/", wsdlLocation = "http://localhost:8888/ws/soapHandler?wsdl")
@HandlerChain(file="../handler/handler-chain.xml")
public class HelloWorldServiceImplService
    extends Service
{
………………………………………………………
}


In this web service client, we are giving information about the handlers using @HandlerChain annotation.
In this annotation,we have specified the handler-chain.xml file name developed in previous step.

Step 7

Create a client to access the published web service

  1. package com.kb.client;
  2.  
  3. import com.kb.ws.HelloWorldService;
  4. import com.kb.ws.HelloWorldServiceImplService;
  5.  
  6. public class HelloWorldClient {
  7.     public static void main(String[] args) {
  8.         HelloWorldServiceImplService service = new HelloWorldServiceImplService();
  9.         HelloWorldService serviceInterface = service.getHelloWorldServiceImplPort();
  10.         String response = serviceInterface.sayHelloWorld();
  11.         System.out.println(response);
  12.     }
  13.  
  14. }
package com.kb.client;

import com.kb.ws.HelloWorldService;
import com.kb.ws.HelloWorldServiceImplService;

public class HelloWorldClient {
	public static void main(String[] args) {
		HelloWorldServiceImplService service = new HelloWorldServiceImplService();
		HelloWorldService serviceInterface = service.getHelloWorldServiceImplPort();
		String response = serviceInterface.sayHelloWorld();
		System.out.println(response);
	}

}


We have created a client class to invoke the web service.

Download this project SOAPHandlerClient.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on