// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package ws.server;

import org.w3c.dom.*;
import org.apache.axis.*;
import org.apache.axis.message.*;
import org.apache.axis.handlers.*;
import org.apache.xml.security.*;
import org.apache.xml.security.signature.*;
import org.apache.xpath.*;

import samples.security.*;

public class DoubleSigLog extends BasicHandler {
    static {
        Init.init();
    }
    public void invoke(MessageContext msgctx) {
        Message req = msgctx.getRequestMessage();
        if(req != null) {
            System.out.println("Request");
            System.out.println("=======");
            try {
                req.writeTo(System.out);
            } catch (Exception ex) {
                // ????
            }
            System.out.println();
            check(req);
        }
        Message resp = msgctx.getResponseMessage();
        if(resp != null) {
            try {
                SOAPEnvelope env = msgctx.getResponseMessage().getSOAPEnvelope();
                msgctx.setResponseMessage(new Message(new SignedSOAPEnvelope(msgctx, env, "http://xml-security")));
                resp = msgctx.getResponseMessage();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            System.out.println("Response");
            System.out.println("========");
            try {
                resp.writeTo(System.out);
            } catch (Exception ex) {
                // ????
            }
            System.out.println();
            check(resp);
        }
    }
    private static void check(Message msg) {
        try {
            Document doc = msg.getSOAPEnvelope().getAsDocument();
            CachedXPathAPI xpath = new CachedXPathAPI();
            Element nsctx = doc.createElement("nsctx");
            nsctx.setAttribute("xmlns:ds", org.apache.xml.security.utils.Constants.SignatureSpecNS);
            Element sigelm = (Element)xpath.selectSingleNode(doc, "//ds:Signature", nsctx);
            if(sigelm == null) {
                System.out.println("====> Not signed");
            } else {
                XMLSignature sig = new XMLSignature(sigelm, "http://xml-security");
                if(sig.checkSignatureValue(sig.getKeyInfo().getPublicKey())) {
                    System.out.println("====> Valid signature for " + sig.getKeyInfo().getX509Certificate().getSubjectDN().getName());
                } else {
                    System.out.println("====> Invalid signature");
                }
            }
        } catch (Exception ex) {
            System.out.println("====> Error locating signature");
        }
    }
}    
