How to get incoming & outgoing soap xml in a simple way using Apache CXF?

Marco picture Marco · Jun 14, 2012 · Viewed 57.4k times · Source

I have been fiddling around with server side interceptors on CXF. But is seems that it is not a trivial task to implement simple incoming and outgoing interceptors that give me a plain string containing the SOAP XML.

I need to have the plain XML in the interceptor so that I can use them for specific logging tasks. The standard LogIn & LogOut interceptors are not up to the task. Is anyone willing to share some example on how I could implement a simple incoming interceptor that is able to get the incoming SOAP XML and a outgoing interceptor to again get the SOAP XML?

Answer

annkatrin picture annkatrin · Jun 15, 2012

Found the code for an incoming interceptor here: Logging request/response with Apache CXF as XML

My outgoing interceptor:

import java.io.OutputStream;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.io.CacheAndWriteOutputStream;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.io.CachedOutputStreamCallback;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;

public class MyLogInterceptor extends LoggingOutInterceptor {

    public MyLogInterceptor() {
        super(Phase.PRE_STREAM);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        OutputStream out = message.getContent(OutputStream.class);
        final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(out);
        message.setContent(OutputStream.class, newOut);
        newOut.registerCallback(new LoggingCallback());
    }

    public class LoggingCallback implements CachedOutputStreamCallback {
        public void onFlush(CachedOutputStream cos) {
        }

        public void onClose(CachedOutputStream cos) {
            try {
                StringBuilder builder = new StringBuilder();
                cos.writeCacheTo(builder, limit);
                // here comes my xml:
                String soapXml = builder.toString();
            } catch (Exception e) {
            }
        }
    }
}