Search in sources :

Example 91 with StreamResult

use of javax.xml.transform.stream.StreamResult in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_detached_signature.

static boolean test_create_detached_signature(String canonicalizationMethod, String signatureMethod, String digestMethod, String transform, KeyInfoType keyInfo, Content contentType, int port) throws Exception {
    System.out.print("Sign ...");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    // Create SignedInfo
    DigestMethod dm = fac.newDigestMethod(digestMethod, null);
    List transformList = null;
    if (transform != null) {
        TransformParameterSpec params = null;
        switch(transform) {
            case Transform.XPATH:
                params = new XPathFilterParameterSpec("//.");
                break;
            case Transform.XPATH2:
                params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("//.", XPathType.Filter.INTERSECT)));
                break;
            case Transform.XSLT:
                Element element = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xslt.getBytes())).getDocumentElement();
                DOMStructure stylesheet = new DOMStructure(element);
                params = new XSLTTransformParameterSpec(stylesheet);
                break;
        }
        transformList = Collections.singletonList(fac.newTransform(transform, params));
    }
    String url = String.format("http://localhost:%d/%s", port, contentType);
    List refs = Collections.singletonList(fac.newReference(url, dm, transformList, null, null));
    CanonicalizationMethod cm = fac.newCanonicalizationMethod(canonicalizationMethod, (C14NMethodParameterSpec) null);
    SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
    Key signingKey;
    Key validationKey;
    switch(signatureMethod) {
        case SignatureMethod.DSA_SHA1:
        case SignatureMethod.RSA_SHA1:
            KeyPair kp = generateKeyPair(sm);
            validationKey = kp.getPublic();
            signingKey = kp.getPrivate();
            break;
        case SignatureMethod.HMAC_SHA1:
            KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
            signingKey = kg.generateKey();
            validationKey = signingKey;
            break;
        default:
            throw new RuntimeException("Unsupported signature algorithm");
    }
    SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
    // Create KeyInfo
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List list = null;
    if (keyInfo == KeyInfoType.KeyValue) {
        if (validationKey instanceof PublicKey) {
            KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
            list = Collections.singletonList(kv);
        }
    } else if (keyInfo == KeyInfoType.x509data) {
        list = Collections.singletonList(kif.newX509Data(Collections.singletonList("cn=Test")));
    } else if (keyInfo == KeyInfoType.KeyName) {
        list = Collections.singletonList(kif.newKeyName("Test"));
    } else {
        throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
    }
    KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
    // Create an empty doc for detached signature
    Document doc = dbf.newDocumentBuilder().newDocument();
    DOMSignContext xsc = new DOMSignContext(signingKey, doc);
    // Generate signature
    XMLSignature signature = fac.newXMLSignature(si, ki);
    signature.sign(xsc);
    // Save signature
    String signatureString;
    try (StringWriter writer = new StringWriter()) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        Node parent = xsc.getParent();
        trans.transform(new DOMSource(parent), new StreamResult(writer));
        signatureString = writer.toString();
    }
    System.out.print("Validate ... ");
    try (ByteArrayInputStream bis = new ByteArrayInputStream(signatureString.getBytes())) {
        doc = dbf.newDocumentBuilder().parse(bis);
    }
    NodeList nodeLst = doc.getElementsByTagName("Signature");
    Node node = nodeLst.item(0);
    if (node == null) {
        throw new RuntimeException("Couldn't find Signature element");
    }
    if (!(node instanceof Element)) {
        throw new RuntimeException("Unexpected node type");
    }
    Element sig = (Element) node;
    // Validate signature
    DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
    signature = fac.unmarshalXMLSignature(vc);
    boolean success = signature.validate(vc);
    if (!success) {
        System.out.println("Core signature validation failed");
        return false;
    }
    success = signature.getSignatureValue().validate(vc);
    if (!success) {
        System.out.println("Cryptographic validation of signature failed");
        return false;
    }
    return true;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) KeyGenerator(javax.crypto.KeyGenerator) KeyPair(java.security.KeyPair) StreamResult(javax.xml.transform.stream.StreamResult) PublicKey(java.security.PublicKey) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Example 92 with StreamResult

use of javax.xml.transform.stream.StreamResult in project azure-tools-for-java by Microsoft.

the class AIParserXMLUtility method saveXMLFile.

/**
	 * save XML file and saves XML document.
	 * 
	 * @param fileName
	 * @param doc
	 * @return XML document or <B>null</B> if error occurred
	 * @throws IOException
	 * @throws WindowsAzureInvalidProjectOperationException
	 */
protected static boolean saveXMLFile(String fileName, Document doc) throws IOException, Exception {
    File xmlFile = null;
    FileOutputStream fos = null;
    Transformer transformer;
    try {
        xmlFile = new File(fileName);
        fos = new FileOutputStream(xmlFile);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        transformer = transFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult destination = new StreamResult(fos);
        // transform source into result will do save
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, destination);
    } catch (Exception excp) {
        Activator.getDefault().log(excp.getMessage(), excp);
        throw new Exception(String.format("%s%s", Messages.saveErrMsg, excp.getMessage()));
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return true;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) TransformerFactory(javax.xml.transform.TransformerFactory) StreamResult(javax.xml.transform.stream.StreamResult) FileOutputStream(java.io.FileOutputStream) File(java.io.File) IOException(java.io.IOException)

Example 93 with StreamResult

use of javax.xml.transform.stream.StreamResult in project azure-tools-for-java by Microsoft.

the class ParseXML method saveXMLDocument.

/**
     * Save XML file and saves XML document.
     *
     * @param fileName
     * @param doc
     * @return boolean
     * @throws Exception object
     */
static boolean saveXMLDocument(String fileName, Document doc) throws Exception {
    // open output stream where XML Document will be saved
    File xmlOutputFile = new File(fileName);
    FileOutputStream fos = null;
    Transformer transformer;
    try {
        fos = new FileOutputStream(xmlOutputFile);
        // Use a Transformer for output
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(fos);
        // transform source into result will do save
        transformer.transform(source, result);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return true;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) TransformerFactory(javax.xml.transform.TransformerFactory) StreamResult(javax.xml.transform.stream.StreamResult) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 94 with StreamResult

use of javax.xml.transform.stream.StreamResult in project azure-tools-for-java by Microsoft.

the class ParserXMLUtility method saveXMLFile.

/**
	 * save XML file and saves XML document.
	 *
	 * @param fileName
	 * @param doc
	 * @return XML document or <B>null</B> if error occurred
	 * @throws IOException
	 * @throws Exception
	 */
public static boolean saveXMLFile(String fileName, Document doc) throws Exception {
    File xmlFile = null;
    FileOutputStream fos = null;
    Transformer transformer;
    try {
        xmlFile = new File(fileName);
        fos = new FileOutputStream(xmlFile);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        transformer = transFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult destination = new StreamResult(fos);
        // transform source into result will do save
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, destination);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return true;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) TransformerFactory(javax.xml.transform.TransformerFactory) StreamResult(javax.xml.transform.stream.StreamResult) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 95 with StreamResult

use of javax.xml.transform.stream.StreamResult in project azure-tools-for-java by Microsoft.

the class XMLHelper method main.

public static void main(String[] argv) {
    if (argv.length < 4) {
        System.out.println("[Failed] Please specify the arguments $XML_FILE $XPATH $NEW_VALUE $JOIN_OR_REPLACE.");
        System.exit(1);
    }
    String FILEPATH = argv[0];
    String XPATH = argv[1];
    String NEW_VALUE = argv[2];
    String CHANGETYPE = argv[3];
    boolean DISPLAY_LOG = false;
    if (argv.length > 4 && argv[4].toLowerCase().equals("true")) {
        DISPLAY_LOG = true;
    }
    try {
        System.out.println("Starting to modify XML " + FILEPATH);
        // Read the content from xml file
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(FILEPATH);
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression expression = xpath.compile(XPATH);
        Node targetNode = (Node) expression.evaluate(doc, XPathConstants.NODE);
        String oldValue = targetNode.getNodeValue();
        String newValue = "";
        if (CHANGETYPE.equals("JOIN")) {
            newValue = oldValue + NEW_VALUE;
        }
        if (DISPLAY_LOG) {
            System.out.println("The old value is " + oldValue);
            System.out.println("The new value is " + newValue);
        }
        targetNode.setNodeValue(newValue);
        // Write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(FILEPATH));
        transformer.transform(source, result);
        System.out.println("Modify XML Finished.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) IOException(java.io.IOException) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) File(java.io.File)

Aggregations

StreamResult (javax.xml.transform.stream.StreamResult)448 Transformer (javax.xml.transform.Transformer)267 DOMSource (javax.xml.transform.dom.DOMSource)234 StringWriter (java.io.StringWriter)206 TransformerFactory (javax.xml.transform.TransformerFactory)138 TransformerException (javax.xml.transform.TransformerException)125 Document (org.w3c.dom.Document)103 IOException (java.io.IOException)94 StreamSource (javax.xml.transform.stream.StreamSource)88 Source (javax.xml.transform.Source)74 Test (org.junit.Test)73 DocumentBuilder (javax.xml.parsers.DocumentBuilder)65 ByteArrayOutputStream (java.io.ByteArrayOutputStream)64 Element (org.w3c.dom.Element)59 File (java.io.File)58 Result (javax.xml.transform.Result)57 StringReader (java.io.StringReader)56 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)53 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)50 ByteArrayInputStream (java.io.ByteArrayInputStream)44