package net.catcert.trustedX.Creation.XAdES.T;

import org.apache.axis.client.Stub;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.commons.configuration.Configuration;

import utils.TrustedXConfiguration;
import utils.Util;
import utils.UtilTrustedX;

import com.safelayer.trustedx.client.smartwrapper.Constants;
import com.safelayer.trustedx.client.smartwrapper.SmartHeader;
import com.safelayer.trustedx.client.smartwrapper.SmartSignRequest;
import com.safelayer.trustedx.client.smartwrapper.SmartSignResponse;

/**
 * XML signature generation
 * 
 * @author aalcaide
 */
public class CreateSignature_XAdES_T_Enveloped {

	private static final String path_in = "in/docs_to_sign/";
	private static final String path_out = "out/Signatures/XAdES/";

	private static final String filename = "Demo.xml";
	

	public static void main(String[] args) {
		try {

			Configuration conf = TrustedXConfiguration.getConfiguration();
			String host = conf.getString("host");
			String distinguishedName = conf.getString("distinguishedname");
			String dipositari = conf.getString("dipositari");
			String rol  = conf.getString("rol");

			// Definition of Signature Request endpoint
			SmartSignRequest ssr = new SmartSignRequest(host);
			
			// Add customized header elements for SOAP
			Stub stub = (Stub) ssr.getStub();
			stub.setHeader(null, "Rol", rol);
			stub.setHeader(null, "Dipositari", dipositari);

			// XML Signature (XAdES)
			ssr.setProfile(Constants.Profile.XADES);
			
			// Read of XML data			
			ssr.setInputXmlBase64(Util.readBinaryFileB64(path_in + filename));
			
			// XAdES signature form
			ssr.setSignatureFormat(Constants.SignatureFormat.ES_T);
			
			// Signature Placement
			ssr.setSignaturePlacement(Constants.SignaturePlacement.ENVELOPED);
			ssr.setXmlEnvelopedXPathAfter("//*[local-name()='ssc']//*[local-name()='description']");
			
			// Key selection using Distinguished Name
			ssr.setKeySubjectName(distinguishedName);

			// Sending request
			SmartSignResponse ssrs = ssr.send();

			if (UtilTrustedX.checkSW(ssrs.getResultMajor(), ssrs.getResultMinor(), ssrs.getResultMessage())) {
				String destFilename = path_out + filename.substring(0, filename.lastIndexOf("."))
						+ "_Signature_XAdES_T_Enveloped.xml";
				Util.writeBinaryFile(destFilename, ssrs.getDocumentWithSignatureXml().getBytes());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}