Thursday, January 28, 2010

Metro : Printing / dumping out the contents of a SOAP packet

I've used Metro a lot and I've always battled to have decent logging.

In the web service, I normally log all the inputs and the outputs and all the exceptions. Wouldn't it be easier if you could just log all the requests and responses which would guarantee that you had all the information all of the time?

I just couldn't figure out how.

Until I came across "MessageDumpingFeature". You find this in the Glassfish \lib directory in the webservices-rt.jar file.

If you've generated web services using Metro, you find the code below very familiar. All you really need to do is replace:

service.getWebServiceName();

with

service.getWebServiceName(messageDumper);

The code looks like:

 

import com.sun.xml.ws.assembler.MessageDumpingFeature;

... snip ...

messageDumper = new MessageDumpingFeature();

ServiceName service = new ServiceName();
WebServiceName port = service.getWebServiceName(messageDumper);
// TODO initialize WS operation arguments here
java.lang.String xxx = "yyy";
java.lang.String yyy = "zzz"
// TODO process result here
ResultName result = port.doWebService(xxx, yyy);

String request = messageDumper.nextMessage();
String response = messageDumper.nextMessage();

System.out.println (request);
System.out.println (response);

... snip ...

} catch (Exception ex) {
String request = messageDumper.nextMessage();
String response = messageDumper.nextMessage();

System.out.println (request);
System.out.println (response);
}


It prints out both normal responses and SOAP Faults.

A request would be dumped like:

 
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:doWebService xmlns:ns2="http://namespace/">
<xxx>yyy</xxx>
<yyy>zzz</yyy>
</ns2:doWebService>
</S:Body>
</S:Envelope>


A valid response would be dumped like:

 
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:doWebService xmlns:ns2="http://namespace/">
<return>
<aaa>bbb</aaa>
<bbb>ccc</bbb>
</return>
</ns2:doWebService>
</S:Body>
</S:Envelope>


A SOAP fault would be dumped like:

 
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
<faultcode>S:Server</faultcode>
<faultstring>SomeErrorString</faultstring>
<detail>
<ns2:SomeException xmlns:ns2="http://namespace/">
<message>SomeErrorMessage</message>
</ns2:SomeException>
</detail>
</S:Fault>
</S:Body>
</S:Envelope>


Of course, instead of dumping out the request / response, it could be written to a file instead.

Enjoy!

No comments: