package pl.qumak;

import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.EndpointInterceptor;
import org.springframework.ws.soap.saaj.SaajSoapMessage;

import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import java.util.Iterator;


public class GlobalEndpointInterceptor implements EndpointInterceptor {
    @Override
    public boolean handleRequest(MessageContext messageContext, Object o) throws Exception {
        return true;
    }

    @Override
    public boolean handleResponse(MessageContext messageContext, Object o) throws Exception {
        return true;
    }

    @Override
    public boolean handleFault(MessageContext messageContext, Object o) throws Exception {
        return false;
    }

    @Override
    public void afterCompletion(MessageContext messageContext, Object o, Exception e) throws Exception {
        try {
            SOAPMessage soapMessage = ((SaajSoapMessage) messageContext.getResponse()).getSaajMessage();
            SOAPHeader header = soapMessage.getSOAPHeader();
            SOAPBody body = soapMessage.getSOAPBody();
            header.setPrefix("");
            body.setPrefix("");
            Iterator<SOAPBodyElement> it = body.getChildElements();
            while (it.hasNext()) {
                SOAPBodyElement node = it.next();
                node.setPrefix("");
                Iterator<SOAPBodyElement> it2 = node.getChildElements();
                while (it2.hasNext()) {
                    SOAPBodyElement node2 = it2.next();
                    node2.setPrefix("");
                    Iterator<SOAPBodyElement> it3 = node2.getChildElements();
                    while (it3.hasNext()) {
                        SOAPBodyElement node3 = it3.next();
                        node3.setPrefix("");
                    }
                }
            }
        } catch (SOAPException exx) {
            exx.printStackTrace();
        }
    }
}