Example usage for javax.xml.transform.dom DOMResult DOMResult

List of usage examples for javax.xml.transform.dom DOMResult DOMResult

Introduction

In this page you can find the example usage for javax.xml.transform.dom DOMResult DOMResult.

Prototype

public DOMResult() 

Source Link

Document

Zero-argument default constructor.

Usage

From source file:org.apache.fop.URIResolutionTestCase.java

private Document createAreaTree(File fo, FOUserAgent ua) throws TransformerException, FOPException {
    DOMResult domres = new DOMResult();
    //Setup Transformer to convert the area tree to a DOM
    TransformerHandler athandler = tfactory.newTransformerHandler();
    athandler.setResult(domres);/*  www . j  a v  a2s .  co  m*/

    XMLRenderer atrenderer = new XMLRenderer(ua);
    atrenderer.setContentHandler(athandler);
    ua.setRendererOverride(atrenderer);

    Fop fop = fopFactory.newFop(ua);

    Transformer transformer = tfactory.newTransformer(); //Identity transf.
    Source src = new StreamSource(fo);
    Result res = new SAXResult(fop.getDefaultHandler());
    transformer.transform(src, res);

    Document doc = (Document) domres.getNode();
    saveAreaTreeXML(doc, new File(backupDir, fo.getName() + ".at.xml"));
    return doc;
}

From source file:org.apache.juddi.mapping.MappingApiToModel.java

private static SignatureTransformDataValue mapSignatureTransformDataValue(Object xform) {
    SignatureTransformDataValue sdv = new SignatureTransformDataValue();
    if (xform instanceof String) {
        sdv.setContentType(String.class.getSimpleName());
        String xformStr = xform.toString();
        byte[] xformBytes = xformStr.getBytes();
        sdv.setContentBytes(xformBytes);
    } else if (xform instanceof Element) {
        sdv.setContentType(Element.class.getCanonicalName());
        Element xformEl = (Element) xform;
        String str = serializeTransformElement(xformEl);
        try {//w w  w.j  a  v  a2s.c o m
            sdv.setContentBytes(str.getBytes("UTF-8"));
        } catch (Exception e) {
            throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e);
        }
    } else if (xform instanceof byte[]) {
        sdv.setContentType(byte[].class.getSimpleName());
        sdv.setContentBytes((byte[]) xform);
    } else if (xform instanceof JAXBElement) {
        sdv.setContentType(Element.class.getCanonicalName());
        JAXBElement xformJAXB = (JAXBElement) xform;
        DOMResult domResult = new DOMResult();
        JAXB.marshal(xformJAXB, domResult);
        Element xformEl = ((Document) domResult.getNode()).getDocumentElement();
        String str = serializeTransformElement(xformEl);
        try {
            sdv.setContentBytes(str.getBytes("UTF-8"));
        } catch (Exception e) {
            throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e);
        }
    } else {
        throw new RuntimeException("Unrecognized type: " + xform.getClass().getCanonicalName());
    }
    return sdv;
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 * Digital signs a UDDI entity, such as a business, service, tmodel or
 * binding template using the map to provide certificate key stores and
 * credentials<br><br> The UDDI entity MUST support XML Digital
 * Signatures (tModel, Business, Service, Binding Template)
 *
 * @param <T> Any UDDI entity that supports digital signatures
 * @param jaxbObj/*  w  w  w . jav  a  2s .  co  m*/
 * @return an enveloped signed UDDI element, do not modify this object
 * after signing
 */
public <T> T signUddiEntity(T jaxbObj) {
    DOMResult domResult = new DOMResult();
    JAXB.marshal(jaxbObj, domResult);
    Document doc = ((Document) domResult.getNode());
    Element docElement = doc.getDocumentElement();

    try {
        KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE));
        URL url = Thread.currentThread().getContextClassLoader()
                .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
        if (url == null) {
            try {
                url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL();
            } catch (Exception x) {
            }
        }
        if (url == null) {
            try {
                url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
            } catch (Exception x) {
            }
        }
        KeyStore.PrivateKeyEntry keyEntry = null;
        if (!map.getProperty(SIGNATURE_KEYSTORE_FILETYPE).equalsIgnoreCase("WINDOWS-MY")) {
            ks.load(url.openStream(), (map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD)).toCharArray());
            if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) {
                keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                        new KeyStore.PasswordProtection(
                                map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()));
            } else {
                keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                        new KeyStore.PasswordProtection(
                                map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray()));
            }
        } else {
            //Windows only
            ks.load(null, null);
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    null);
        }

        PrivateKey privateKey = keyEntry.getPrivateKey();
        Certificate origCert = keyEntry.getCertificate();
        //PublicKey validatingKey = origCert.getPublicKey();
        this.signDOM(docElement, privateKey, origCert);

        DOMSource domSource = new DOMSource(doc);
        T result = (T) JAXB.unmarshal(domSource, jaxbObj.getClass());
        return result;
    } catch (Exception e) {
        throw new RuntimeException("Signature failure due to: " + e.getMessage(), e);
    }
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 * Digitally signs a UDDI entity, such as a business, service, tmodel or
 * binding template, provided you've already done the legwork to provide
 * the signing keys <br><br> The UDDI entity MUST support XML Digital
 * Signatures (tModel, Business, Service, Binding Template)
 *
 * @param <T>//from  w  w  w .  ja v  a2 s .c  o  m
 * @param jaxbObj
 * @param publicKey
 * @param privateKey
 * @return a signed entity
 */
public <T> T signUddiEntity(T jaxbObj, Certificate publicKey, PrivateKey privateKey) {
    DOMResult domResult = new DOMResult();
    JAXB.marshal(jaxbObj, domResult);
    Document doc = ((Document) domResult.getNode());
    Element docElement = doc.getDocumentElement();
    try {

        //PublicKey validatingKey = origCert.getPublicKey();
        this.signDOM(docElement, privateKey, publicKey);
        DOMSource domSource = new DOMSource(doc);
        T result = (T) JAXB.unmarshal(domSource, jaxbObj.getClass());
        return result;
    } catch (Exception e) {
        throw new RuntimeException("Signature failure due to: " + e.getMessage(), e);
    }
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 *
 * returns the public key of the signing certificate used for a signed
 * JAXB object.//  w ww . jav a 2s.  c  o m
 *
 * @param obj
 * @return null if the item is not signed or if it references a
 * certificate that is not present in the current keystore
 * @throws IllegalArgumentException for null input
 * @throws java.security.cert.CertificateException
 */
public X509Certificate getSigningCertificatePublicKey(Object obj)
        throws IllegalArgumentException, CertificateException {
    DOMResult domResult = new DOMResult();
    JAXB.marshal(obj, domResult);

    Document doc = ((Document) domResult.getNode());
    Element docElement = doc.getDocumentElement(); //this is our signed node
    return getSigningCertificatePublicKey(docElement);
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 * Verifies the signature on an enveloped digital signature on a UDDI
 * entity, such as a business, service, tmodel or binding template.
 * <br><Br>/* www.  j av a  2s  .c o  m*/
 * It is expected that either the public key of the signing certificate
 * is included within the signature keyinfo section OR that sufficient
 * information is provided in the signature to reference a public key
 * located within the Trust Store provided<br><Br> Optionally, this
 * function also validate the signing certificate using the options
 * provided to the configuration map.
 *
 * @param obj an enveloped signed JAXB object
 * @param OutErrorMessage a human readable error message explaining the
 * reason for failure
 * @return true if the validation passes the signature validation test,
 * and optionally any certificate validation or trust chain validation
 * @throws IllegalArgumentException for null input
 */
public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage)
        throws IllegalArgumentException {
    if (OutErrorMessage == null) {
        OutErrorMessage = new AtomicReference<String>();
        OutErrorMessage.set("");
    }
    if (obj == null) {
        throw new IllegalArgumentException("obj");
    }
    try {
        DOMResult domResult = new DOMResult();
        JAXB.marshal(obj, domResult);

        Document doc = ((Document) domResult.getNode());
        Element docElement = doc.getDocumentElement(); //this is our signed node

        X509Certificate signingcert = getSigningCertificatePublicKey(docElement);

        if (signingcert != null) {
            logger.info(
                    "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString());
            if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) {
                signingcert.checkValidity();
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) {
                logger.info("verifying revocation status via OSCP for X509 public key "
                        + signingcert.getSubjectDN().toString());
                X500Principal issuerX500Principal = signingcert.getIssuerX500Principal();
                logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by "
                        + issuerX500Principal.getName() + ", attempting to retrieve certificate");
                Security.setProperty("ocsp.enable", "false");
                X509Certificate issuer = FindCertByDN(issuerX500Principal);
                if (issuer == null) {
                    OutErrorMessage.set(
                            "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. "
                                    + OutErrorMessage.get());
                    //throw new CertificateException("unable to locate the issuers certificate in the trust store");
                } else {
                    RevocationStatus check = OCSP.check(signingcert, issuer);
                    logger.info("certificate " + signingcert.getSubjectDN().toString()
                            + " revocation status is " + check.getCertStatus().toString() + " reason "
                            + check.getRevocationReason().toString());
                    if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) {
                        OutErrorMessage
                                .set("Certificate status is " + check.getCertStatus().toString() + " reason "
                                        + check.getRevocationReason().toString() + "." + OutErrorMessage.get());

                        //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString());
                    }
                }
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_CRL)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) {
                logger.info("verifying revokation status via CRL for X509 public key "
                        + signingcert.getSubjectDN().toString());

                Security.setProperty("ocsp.enable", "false");
                System.setProperty("com.sun.security.enableCRLDP", "true");

                X509CertSelector targetConstraints = new X509CertSelector();
                targetConstraints.setCertificate(signingcert);
                PKIXParameters params = new PKIXParameters(GetTrustStore());
                params.setRevocationEnabled(true);
                CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                CertPathValidator certPathValidator = CertPathValidator
                        .getInstance(CertPathValidator.getDefaultType());
                CertPathValidatorResult result = certPathValidator.validate(certPath, params);
                try {
                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
                    logger.info("revokation status via CRL PASSED for X509 public key "
                            + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            if (map.containsKey(CHECK_TRUST_CHAIN)
                    && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) {
                logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString());
                try {
                    PKIXParameters params = new PKIXParameters(GetTrustStore());
                    params.setRevocationEnabled(false);
                    CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                    CertPathValidator certPathValidator = CertPathValidator
                            .getInstance(CertPathValidator.getDefaultType());
                    CertPathValidatorResult result = certPathValidator.validate(certPath, params);

                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;

                    TrustAnchor ta = pkixResult.getTrustAnchor();
                    X509Certificate cert = ta.getTrustedCert();

                    logger.info(
                            "trust chain validated X509 public key " + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage);
            if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) {
                //no error message and its cryptographically valid
                return true;
            }
            return false;
        }

        //last chance validation
        logger.info(
                "signature did not have an embedded X509 public key. reverting to user specified certificate");
        //cert wasn't included in the signature, revert to some other means
        KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE));
        URL url = Thread.currentThread().getContextClassLoader()
                .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
        if (url == null) {
            try {
                url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL();
            } catch (Exception x) {
            }
        }
        if (url == null) {
            try {
                url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
            } catch (Exception x) {
            }
        }
        if (url == null) {
            logger.error("");
            OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and"
                    + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get());
            return false;
        }
        KeyStore.PrivateKeyEntry keyEntry = null;

        ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray());

        if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()));
        } else {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray()));
        }

        Certificate origCert = keyEntry.getCertificate();
        if (map.containsKey(CHECK_TIMESTAMPS)) {
            if (origCert.getPublicKey() instanceof X509Certificate) {
                X509Certificate x = (X509Certificate) origCert.getPublicKey();
                x.checkValidity();
            }
        }
        PublicKey validatingKey = origCert.getPublicKey();
        return verifySignature(docElement, validatingKey, OutErrorMessage);
    } catch (Exception e) {
        //throw new RuntimeException(e);
        logger.error("Error caught validating signature", e);
        OutErrorMessage.set(e.getMessage());
        return false;
    }
}

From source file:org.apache.juddi.v3.tck.TckBusiness.java

private <T> T signJAXBObject(T jaxbObj) {
    DOMResult domResult = new DOMResult();
    JAXB.marshal(jaxbObj, domResult);
    Document doc = ((Document) domResult.getNode());
    Element docElement = doc.getDocumentElement();

    try {/*from  w w  w . j a v  a2 s.  com*/
        KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE);
        URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE);
        ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray());
        KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(SIGNATURE_KEYSTORE_ALIAS,
                new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray()));
        PrivateKey privateKey = keyEntry.getPrivateKey();
        Certificate origCert = keyEntry.getCertificate();
        PublicKey validatingKey = origCert.getPublicKey();
        TckSigningUtil.signDOM(docElement, privateKey, origCert);

        DOMSource domSource = new DOMSource(doc);
        T result = (T) JAXB.unmarshal(domSource, jaxbObj.getClass());
        return result;
    } catch (Exception e) {
        throw new RuntimeException("Signature failure due to: " + e.getMessage(), e);
    }
}

From source file:org.apache.juddi.v3.tck.TckBusiness.java

private boolean verifySignedJAXBObject(Object obj) {
    try {//  w w w .  j ava2s.  c o m
        DOMResult domResult = new DOMResult();
        JAXB.marshal(obj, domResult);
        Document doc = ((Document) domResult.getNode());
        Element docElement = doc.getDocumentElement();

        KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE);
        URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE);
        ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray());
        KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(SIGNATURE_KEYSTORE_ALIAS,
                new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray()));
        PrivateKey privateKey = keyEntry.getPrivateKey();
        Certificate origCert = keyEntry.getCertificate();
        PublicKey validatingKey = origCert.getPublicKey();
        return TckSigningUtil.verifySignature(docElement, validatingKey);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.ode.utils.xsl.XslTransformHandler.java

/**
 * Transforms a Source document to a result using the XSL stylesheet referenced
 * by the provided URI. The stylesheet MUST have been parsed previously.
 * @param uri referencing the stylesheet
 * @param source XML document//from   w  w  w  .ja v  a2 s.co m
 * @param parameters passed to the stylesheet
 * @param resolver used to resolve includes and imports
 * @return result of the transformation (XSL, HTML or text depending of the output method specified in stylesheet.
 */
public Object transform(QName processQName, URI uri, Source source, Map<QName, Object> parameters,
        URIResolver resolver) {
    Templates tm;
    synchronized (_templateCache) {
        tm = (Templates) _templateCache.get(processQName, uri);
    }
    if (tm == null)
        throw new XslTransformException("XSL sheet" + uri + " has not been parsed before transformation!");
    try {
        Transformer tf = tm.newTransformer();
        tf.setURIResolver(resolver);
        if (parameters != null) {
            for (Map.Entry<QName, Object> param : parameters.entrySet()) {
                tf.setParameter(param.getKey().getLocalPart(), param.getValue());
            }
        }
        String method = tf.getOutputProperties().getProperty("method");
        if (method == null || "xml".equals(method)) {
            DOMResult result = new DOMResult();
            tf.transform(source, result);
            Node node = result.getNode();
            if (node.getNodeType() == Node.DOCUMENT_NODE)
                node = ((Document) node).getDocumentElement();
            if (__log.isDebugEnabled())
                __log.debug("Returned node: type=" + node.getNodeType() + ", " + DOMUtils.domToString(node));
            return node;
        } else {
            // text and html outputs are handled the same way
            StringWriter writerResult = new StringWriter();
            StreamResult result = new StreamResult(writerResult);
            tf.transform(source, result);
            writerResult.flush();
            String output = writerResult.toString();
            if (__log.isDebugEnabled())
                __log.debug("Returned string: " + output);
            return output;
        }
    } catch (TransformerConfigurationException e) {
        throw new XslTransformException(e);
    } catch (TransformerException e) {
        throw new XslTransformException("XSL Transformation failed!", e);
    }
}

From source file:org.apache.solr.handler.loader.XMLLoader.java

@Override
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream,
        UpdateRequestProcessor processor) throws Exception {
    final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());

    InputStream is = null;//from  w w w  .  j  a  va 2s  .co m
    XMLStreamReader parser = null;

    String tr = req.getParams().get(CommonParams.TR, null);
    if (tr != null) {
        final Transformer t = getTransformer(tr, req);
        final DOMResult result = new DOMResult();

        // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces
        // an internal result DOM tree, we just access it directly as input for StAX):
        try {
            is = stream.getStream();
            final InputSource isrc = new InputSource(is);
            isrc.setEncoding(charset);
            final XMLReader xmlr = saxFactory.newSAXParser().getXMLReader();
            xmlr.setErrorHandler(xmllog);
            xmlr.setEntityResolver(EmptyEntityResolver.SAX_INSTANCE);
            final SAXSource source = new SAXSource(xmlr, isrc);
            t.transform(source, result);
        } catch (TransformerException te) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te);
        } finally {
            IOUtils.closeQuietly(is);
        }
        // second step: feed the intermediate DOM tree into StAX parser:
        try {
            parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode()));
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
        }
    }
    // Normal XML Loader
    else {
        try {
            is = stream.getStream();
            if (log.isTraceEnabled()) {
                final byte[] body = IOUtils.toByteArray(is);
                // TODO: The charset may be wrong, as the real charset is later
                // determined by the XML parser, the content-type is only used as a hint!
                log.trace("body",
                        new String(body, (charset == null) ? ContentStreamBase.DEFAULT_CHARSET : charset));
                IOUtils.closeQuietly(is);
                is = new ByteArrayInputStream(body);
            }
            parser = (charset == null) ? inputFactory.createXMLStreamReader(is)
                    : inputFactory.createXMLStreamReader(is, charset);
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
            IOUtils.closeQuietly(is);
        }
    }
}