package example.common.handler;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class SoapServerSideHandler implements SOAPHandler<SOAPMessageContext> {

    static Logger logger = LoggerFactory.getLogger(SoapServerSideHandler.class);

    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext context) {
        return true;
    }

    public boolean handleFault(SOAPMessageContext context) {
        SOAPMessage message = context.getMessage();
        SOAPPart part = message.getSOAPPart();
        NodeList exceptions = part.getElementsByTagNameNS(
                "http://jax-ws.dev.java.net/", "exception");
        if (exceptions.getLength() == 1) {
            handleException((Element) exceptions.item(0));
        }
        return true;
    }

    void handleException(Element exception) {
        if (logger.isDebugEnabled()) {
            String note = exception.getAttribute("note");
            logger.debug("note=" + note);
        }
        exception.removeAttribute("note");
        NodeList stackTraces = exception.getElementsByTagNameNS(
                "http://jax-ws.dev.java.net/", "stackTrace");
        int statckTracesLength = stackTraces.getLength();
        for (int i = 0; i < statckTracesLength; ++i) {
            Node stackTrace = stackTraces.item(i);
            stackTrace.getParentNode().removeChild(stackTrace);
        }
        logger.debug("stackTrace removed.");
    }

    public void close(MessageContext context) {
    }

}
