package com.example;

import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.message.WSSecHeader;
import org.apache.wss4j.dom.message.WSSecSignature;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

public class ExampleWsSecurity {
    public static void main(String[] args) throws Exception {
        // Simple SOAP envelope
        String soap = "" +
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                "<soapenv:Body>\n" +
                "  Meow kucing\n" +
                "</soapenv:Body>\n" +
                "</soapenv:Envelope>";

        // Parse SOAP to DOM
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document doc = dbf.newDocumentBuilder()
                .parse(new ByteArrayInputStream(soap.getBytes(StandardCharsets.UTF_8)));

        // Load crypto from properties (assumes crypto.properties in classpath)
        Crypto crypto = CryptoFactory.getInstance("crypto.properties");

        // Insert WS-Security header
        WSSecHeader secHeader = new WSSecHeader(doc);
        secHeader.insertSecurityHeader();

        // Sign SOAP Body only
        WSSecSignature signature = new WSSecSignature(secHeader);
        signature.setUserInfo("wsstest", "changeit"); // alias and password
        signature.setSigCanonicalization(WSConstants.C14N_EXCL_OMIT_COMMENTS); 
        signature.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
        signature.setSignatureAlgorithm(WSConstants.RSA_SHA256);
        signature.setDigestAlgo(WSConstants.SHA256);

        Document signedDoc = signature.build(crypto);

        // Print signed SOAP message
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();

        StringWriter sw = new StringWriter();
        transformer.transform(new DOMSource(signedDoc), new StreamResult(sw));
        System.out.println(sw.toString());
    }
}
