11
Oct
13

How to replace an incoming SOAP message JAX-WS


This page describes how to replace an incoming SOAP message with a custom one. More specifically the page will allow you to record and play back SOAP messages that have been sent in the past.

The SOAP messages will need to be intercepted. This is done by the HandlerResolver. The resolver will identify if its an incoming or outgoing message.

Incoming messages will be replaced by a custom message that you construct.

Note: Due to the request-response nature of this solution it is not suited for un-marshaling messages that have been saved in the past.

App.java

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.PortInfo;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import com.test.client.Customer;
import com.test.client.CustomerService;


public class App {

	public static void main(String args[]) throws Exception {
		Service service = Service.create(new URL("http://localhost:8080/jax-ws-spring-jboss/customerService?wsdl"),
				new QName("http://test.com/", "CustomerServiceImplService"));
		addDebugSupport(service);
		CustomerService customerService = service.getPort(CustomerService.class);

		for(Customer customer : customerService.getCustomer("1")) {
			System.out.println(customer.getId());
		}
	}

	private static final Document buildMessage() throws Exception {
		String xml = "<ns2:getCustomerResponse xmlns:ns2=\"http://com/test/\"><customer><ns2:id>1</ns2:id></customer><customer><ns2:id>5</ns2:id></customer></ns2:getCustomerResponse>";
		  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();  
		  docBuilderFactory.setNamespaceAware(true);  
		  DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();  
		  return docBuilder.parse(new InputSource(new StringReader(xml))); 
	}
	
	private static void addDebugSupport(Service service) {
	    service.setHandlerResolver(new HandlerResolver() {
	        public List<Handler> getHandlerChain(PortInfo portInfo) {
	            List<Handler> handlerChain = new ArrayList<Handler>();
	            handlerChain.add(new SOAPHandler<SOAPMessageContext>() {
	                public boolean handleMessage(SOAPMessageContext context) {
	                    try {
							log(context);
						} catch (Exception e) {
							throw new RuntimeException(e);
						}
	                    return true;
	                }
	                public boolean handleFault(SOAPMessageContext context) {
	                	return true;
	                }
	                public void close(MessageContext context) {}
	                public Set<QName> getHeaders() {return null;}
	            });
	            return handlerChain;
	        }
	        private void log(SOAPMessageContext smc) throws Exception {
	            Boolean outboundProperty = (Boolean) smc
	                    .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
	            if(outboundProperty.booleanValue()) {
	                System.out.println("Outbound message:");                  
	            } else {
	                System.out.println("Inbound message:");

	                MessageFactory mf;
					mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
	                SOAPMessage msg = mf.createMessage();  
	                msg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");  
	                SOAPPart soapPart = msg.getSOAPPart();  
	                SOAPBody soapBody = msg.getSOAPBody();  
	                SOAPEnvelope envelope = soapPart.getEnvelope();     
	                SOAPHeader header = msg.getSOAPHeader();     
	                header.detachNode();   
	                soapBody.addDocument(buildMessage());  
	                msg.saveChanges();     
		            smc.setMessage(msg);
	            }
	            SOAPMessage message = smc.getMessage();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                message.writeTo(baos);
                System.out.println(baos.toString());
	        }
	    });
	}
}
Advertisements

1 Response to “How to replace an incoming SOAP message JAX-WS”


  1. June 30, 2014 at 12:06 am

    after getting the soap mesage how to process to validate it.. can you show me how .. i have a request soap message in my handler class with large amount of data in it.. i need to validate each and every data.. can you help me


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 74 other followers

October 2013
S M T W T F S
« Aug   Dec »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 801,397 hits

%d bloggers like this: