tags:

views:

216

answers:

1

Is it possible to view the request and the response for a Spring WS client using WebServicesTemplate and Jxb2Marshaller as the marshaling engine?

I simply wan to to log the xml, not perform any actions upon the raw xml.

A: 

Was able to figure it out - if you add a ClientInterceptor like this to the WebServicesTemplate interceptors:

package com.wuntee.interceptor;

import java.io.ByteArrayOutputStream;

import org.apache.log4j.Logger;
import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.MessageContext;

public class LoggerInterceptor implements ClientInterceptor {
    private Logger logger = Logger.getLogger(this.getClass().getName());

    public boolean handleFault(MessageContext context) throws WebServiceClientException {
        return false;
    }

    public boolean handleRequest(MessageContext context) throws WebServiceClientException {
        logger.info("handleRequest");
        logRequestResponse(context);        
        return true;
    }

    public boolean handleResponse(MessageContext context) throws WebServiceClientException {
        logger.info("handleResponse");
        logRequestResponse(context);
        return true;
    }

    private void logRequestResponse(MessageContext context){
        try{
            logger.info("Request:");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            context.getRequest().writeTo(out);
            byte[] charData = out.toByteArray();
            String str = new String(charData, "ISO-8859-1");
            logger.info(str);
        } catch(Exception e){
            logger.error("Could not log request: ", e);
        }

        if(context.hasResponse()){
            try{
                logger.info("Response:");
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                context.getResponse().writeTo(out);
                byte[] charData = out.toByteArray();
                String str = new String(charData, "ISO-8859-1");
                logger.info(str);
            } catch(Exception e){
                logger.error("Could not log response: ", e);
            }
        }
    }

}
wuntee
The only problem with this solution is if there is a problem unmarshaling the response your handleResponse method will never be called. I have yet to find a solution to work around this issue.
Mike Deck