Search code examples
javaweb-servicescxfinterceptor

How To Modify The Raw XML message of an Outbound CXF Request?


I would like to modify an outgoing SOAP Request. I would like to remove 2 xml nodes from the Envelope's body. I managed to set up an Interceptor and get the generated String value of the message set to the endpoint.

However, the following code does not seem to work as the outgoing message is not edited as expected. Does anyone have some code or ideas on how to do this?

public class MyOutInterceptor extends AbstractSoapInterceptor {

public MyOutInterceptor() {
        super(Phase.SEND); 
}

public void handleMessage(SoapMessage message) throws Fault { 
        // Get message content for dirty editing...
        StringWriter writer = new StringWriter();
        CachedOutputStream cos  = (CachedOutputStream)message.getContent(OutputStream.class); 
        InputStream inputStream = cos.getInputStream();
        IOUtils.copy(inputStream, writer, "UTF-8");
        String content = writer.toString();

        // remove the substrings from envelope...
        content = content.replace("<idJustification>0</idJustification>", "");
        content = content.replace("<indicRdv>false</indicRdv>", "");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(content.getBytes(Charset.forName("UTF-8")));
        message.setContent(OutputStream.class, outputStream);
} 

Solution

  • I had this problem as well today. After much weeping and gnashing of teeth, I was able to alter the StreamInterceptor class in the configuration_interceptor demo that comes with the CXF source:

    OutputStream os = message.getContent(OutputStream.class);
    CachedStream cs = new CachedStream();
    message.setContent(OutputStream.class, cs);
    
    message.getInterceptorChain().doIntercept(message);
    
    try {
        cs.flush();
        CachedOutputStream csnew = (CachedOutputStream) message.getContent(OutputStream.class);
    
        String soapMessage = IOUtils.toString(csnew.getInputStream());
        ...
    

    The soapMessage variable will contain the complete SOAP message. You should be able to manipulate the soap message, flush it to an output stream and do a message.setContent(OutputStream.class... call to put your modifications on the message. This comes with no warranty, since I'm pretty new to CXF myself!

    Note: CachedStream is a private class in the StreamInterceptor class. Don't forget to configure your interceptor to run in the PRE_STREAM phase so that the SOAP interceptors have a chance to write the SOAP message.