package pl.qumak.xml;

import org.apache.ws.security.handler.WSHandlerConstants;
import org.apache.wss4j.dom.engine.WSSecurityEngineResult;
import org.apache.wss4j.dom.handler.WSHandlerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor;
import org.xml.sax.SAXParseException;

import javax.xml.transform.TransformerException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.List;

/**
 * Created by kingdom on 24.08.17.
 */
public class LoggedPayloadValidatingInterceptor extends PayloadValidatingInterceptor {


    @Override
    protected boolean handleRequestValidationErrors(org.springframework.ws.context.MessageContext messageContext, SAXParseException[] errors)
            throws TransformerException {

        SoapMessage soapMessage = (SoapMessage) messageContext.getRequest();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            X509Certificate x509Certificate = getCertFromMessage(messageContext);
        } catch (Exception e) {
        }
        try {
            soapMessage.writeTo(byteArrayOutputStream);
        } catch (IOException e) {
        }
        return super.handleRequestValidationErrors(messageContext, errors);
    }

    public X509Certificate getCertFromMessage(MessageContext messageContext) throws Exception {
        X509Certificate x509Certificate = null;
        List<WSHandlerResult> wsHandlerResultList = (List<WSHandlerResult>) messageContext.getProperty(WSHandlerConstants.RECV_RESULTS);
        WSHandlerResult wsHandlerResult = wsHandlerResultList.get(0);
        List<WSSecurityEngineResult> wsSecurityEngineResultList = wsHandlerResult.getResults();

        WSSecurityEngineResult wsSecurityEngineResult = null;
        for (WSSecurityEngineResult result : wsSecurityEngineResultList) {
            int resultAction =
                    ((java.lang.Integer) result.get(WSSecurityEngineResult.TAG_ACTION)).intValue();
            if (resultAction == org.apache.wss4j.dom.WSConstants.SIGN) {
                wsSecurityEngineResult = result;
            }
        }
        if (wsSecurityEngineResult != null) {
            x509Certificate = (X509Certificate) wsSecurityEngineResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
        }
        return x509Certificate;
    }
}
