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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
{
………………………………………………………
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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";
    }
}
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
2
3
4
5
6
7
8
9
10
<?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>
<?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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
{
………………………………………………………
}
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
2
3
4
5
6
7
8
9
10
11
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);
    }
 
}
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

Karibasappa G C (KB)
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