package test;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.codec.binary.Base64;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.Document;

import test.token.jaxb.Principal;
import test.token.jaxb.Token;

public class Test {

	public static void main(String[] args) throws Exception {
		// setup the token & principal
		Token token = new Token();
		Principal principal = new Principal();
		
		principal.setUsername("test");
		token.setPrincipal(principal);

		// setup a marshaller and SringWriter to store the XML
		StringWriter sw = new StringWriter();
		JAXBContext jc = JAXBContext.newInstance("test.token.jaxb");
		Marshaller marshaller = jc.createMarshaller();
		
		marshaller.marshal(token, sw);
		System.out.println(sw.toString());

		// setup the private key used for signing
		String privKeyString = "MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBALszx4Z8h092GhQuR07RlE+qAPKuRRsLuvn+W6Ac8qzpoPLLTQDha5AkZ5EOkCYmxlJrwMWwE9VdsimzeTC+T8FWnCWdHhUhMm5TTDCz1P0CZLOw96ASFet9ZWGshEuXhFbPa/yZFH22wyjT0pJHvXonxugu5BFGxyRROYjHA6CPAhUAt0XOsTy69S865BHwQ3KixqAeeIECgYEAlGDyHRAetidSoufvpX7r4DFcY29ITMPuS1tNyVDGkRL/XcOM8wTq1IbBAtXnHNyKhIQUsDnzPgdsQRKUNvN10sxg7/i5npBRnNLtbg5wGF3fiAaeUougKdxpGyXNguT8s7MJu0kmQm37PvuFeY7yOPk8F8c7dCUGTpULZdgD1jAEFgIUHczL827ESRUdoGHBToQj95F/eNk=";
		PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privKeyString));
		KeyFactory keyFactory = KeyFactory.getInstance("DSA");
		PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
			
		// convert the XML into a Document
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		DocumentBuilder db = dbf.newDocumentBuilder();
		ByteArrayInputStream bais = new ByteArrayInputStream(sw.toString().getBytes());
		Document doc = db.parse(bais);

		// output the Document
		XMLUtils.outputDOMc14nWithComments(doc, System.out);
		
		// setup the XMLSignature (not sure what the BaseURI is!)
		XMLSignature sig = new XMLSignature(doc, "", XMLSignature.ALGO_ID_SIGNATURE_DSA);

		doc.getFirstChild().appendChild(sig.getElement());

		// create and apply the transform to our document
		Transforms transforms = new Transforms(doc);
		transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
	}

}
