Pretty printing SOAP messages

If your dealing with SAAJ API or you want to create a Debug Message Handler that prints the SOAP Message then you can call SOAPmessage.writeTo(System.out), but this method writes the full SOAP message in one line and which can be little hard to read this is sample output


<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><wn:sayHello SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wn="http://ws.websphrenotes.com/"><arg0>Sunil</arg0></wn:sayHello></SOAP-ENV:Body></SOAP-ENV:Envelope>


If you want to pretty print the SOAPMessage then you can use the following method.


package com.webspherenotes.ws;
import java.io.ByteArrayOutputStream;

import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
public class SOAPHelper {
public static String getSOAPMessageAsString(SOAPMessage soapMessage) {
try {

TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();

// Set formatting

tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
"2");

Source sc = soapMessage.getSOAPPart().getContent();

ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
StreamResult result = new StreamResult(streamOut);
tf.transform(sc, result);

String strMessage = streamOut.toString();
return strMessage;
} catch (Exception e) {
System.out.println("Exception in getSOAPMessageAsString "
+ e.getMessage());
return null;
}

}
}


It generates the output which looks like this

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<wn:sayHello SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wn="http://ws.websphrenotes.com/">
<arg0>Sunil</arg0>
</wn:sayHello>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>



I ended up doing this because i could not find SaajOutputer.java class

10 comments: