-->

Sunday, April 22, 2012

How to log SOAP Request and response XML in log file

Thanks to http://www.coderanch.com/t/549539/Web-Services/java/Convert-SOAP-response-SOAP-XmL
http://qa.netbeans.org/modules/j2ee/promo-g/end2end/hello_ws.html

It is mostly desired to log the SOAP request and response XML into log file.
But there is no direct way, using which you can log the XML, because the XML generation part is in the control of the webservice framework. But the good news that you can configure it to print the XML where ever you like it to.

Configure logging of XML on server side using Netbeans

Creating web project
  1. Go to File - New Project - Web - Web Application
  2. Specify HelloWs as Project Name
  3. Specify project's directory
  4. Choose Java EE 5 as J2EE version and
  5. Click Finish
Creating web service
  1. Go to File - New File - Web services - Web Service - Next
  2. Specify name of web service, eg. HelloWebService
  3. Specify package for the web service, eg. org.netbeans.end2end.hellosample
  4. Click Finish
Implementing web service
  1. Uncomment commented code in source file
  2. Add serviceName="GreeterWs" to WebService annotation
  3. Add operationName="sayHi" to WebMethod annotation
  4. Add @WebParam(name="name") to String param argument of method operation
  5. Add new sayHello(String): String operation to web service using Web Service -> Add Operation... action in editor
    Implement both operation, so the implementation class will look like this:
Creating message handler
  • Go to File - New File - Web services - Message Handler - Next
  • Specify name of message handler, eg. MessageHandler
  • Specify package for the message handler, eg. org.netbeans.end2end.hellosample
  • Click Finish
  • Implement simple log method in handler, eg. like on following picture:


  • And add handler to the webservice using Configure Handlers... action in context menu on HelloWebService's node

Configure logging of XML on client side using Netbeans

Write a myHandler as follows:
import java.io.IOException;  
import java.util.Set;  
  
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;  
  
public class MyHandler implements SOAPHandler {  
  
    public boolean handleMessage(SOAPMessageContext smc) {  
  
        Boolean outboundProperty = (Boolean) smc  
                .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);  
  
        SOAPMessage message = smc.getMessage();  
        // This if condition gets reversed when we write
        // code on client side.
        if (outboundProperty.booleanValue()) {  
            System.out.print(" SOAP Request ");  
        } else {  
            System.out.print(" SOAP Respone ");  
        }  
  
        try {  
            message.writeTo(System.out);  
        } catch (SOAPException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        System.out.println("");  
        // if this function will return true, only then the chaining concept will work.
        // if we return outboundProperty which happens to be false in some cases
        // the chaining will not work.  
        //return outboundProperty;  
        return true;
  
    }  
  
    public Set getHeaders() {  
        return null;  
    }  
  
    public boolean handleFault(SOAPMessageContext context) {  
        return true;  
    }  
  
    public void close(MessageContext context) {  
    }  
}  
And write myHanlderResolver like this:
import java.util.ArrayList;  
import java.util.List;  
  
import javax.xml.ws.handler.HandlerResolver;  
import javax.xml.ws.handler.PortInfo;  
  
public class MyHandlerResolver implements HandlerResolver {  
  
    public List getHandlerChain(PortInfo portInfo) {  
        ArrayList handlerChain = new ArrayList();  
        handlerChain.add(new MyHandler());  
        return handlerChain;  
    }  
  
} 
To associate your handler with the web service, you need to do something like this:
myws.service = new myws_Service(); 
System.out.println("Now setting the HandlerResolver");
// Following two 
HandlerResolver myHanlderResolver = new MyHandlerResolver();
service.setHandlerResolver(myHanlderResolver);
System.out.println("myHandlerResolver has been set.");

How to convert SOAPMessage to a String

'
private String log(SOAPMessage message) throws SOAPException, IOException
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        message.writeTo(out);
        logger.debug(out.toString());
        return out.toString();
    }
You might like reading this : http://javakafunda.blogspot.in/2012/04/how-to-format-xml-string-in-java.html

11 comments:

  1. thanks for this article

    ReplyDelete
  2. 1) The service.setHandlerResolver() thing did nothing on the client side, instead the add handler that you mention on the server side worked.
    2) You might want to correct the typoes, like soapmessagecontext and myhandler. And the ArrayList must be of type Handler, not myhandler.
    3) After doing all this it worked, so thank you nevertheless.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. I followed your instruction, but some reason it does not execute MyHandler class. I am using Websphere application server and used RAD to generated client stub (Generated By:JAX-WS RI IBM 2.1.6 in JDK 6 (JAXB RI IBM JAXB 2.1.10 in JDK 6). Please advise.

    ReplyDelete
    Replies
    1. This thing worked for me n websphere and is currently running in production. Visit source link, you might find something useful.

      Delete
    2. This thing worked for me n websphere and is currently running in production. Visit source link, you might find something useful.

      Delete
    3. I created handler-chain.xml and used @HandlerChain in my Service class for it to work. However, my next question is can I use the same SoapHandler implemented class to process different webservices.
      Thank you.

      Delete
    4. No. I think this can be used to process only 1 webservice as each webservice needs to have its own handler.

      Delete
  5. I need a java sample application to sign a SOAP request with a public key. Can someone help?

    ReplyDelete
  6. Here I leave a way to save the logs of soap messages with c#
    http://www.systemdeveloper.org/2014/06/tracesoapmessage

    ReplyDelete