List of usage examples for javax.xml.transform.dom DOMResult getNode
public Node getNode()
From source file:org.apache.fop.plan.PreloaderPlan.java
private Document getDocument(InputStream in) throws TransformerException { TransformerFactory tFactory = TransformerFactory.newInstance(); //Custom error listener to minimize output to console ErrorListener errorListener = new DefaultErrorListener(log); tFactory.setErrorListener(errorListener); Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(errorListener); Source source = new StreamSource(in); DOMResult res = new DOMResult(); transformer.transform(source, res);//from ww w. j a v a 2s . c om Document doc = (Document) res.getNode(); return doc; }
From source file:org.apache.fop.tools.EventProducerCollectorTask.java
/** * Updates the translation file with new entries for newly found event producer methods. * @param modelFile the model file to use * @throws IOException if an I/O error occurs *///from w ww.j a va 2 s.com protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource(getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource(getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
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);//from w w w .j a v a 2s. c om 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 ww. j av a 2s . 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//ww w . j av a2 s . 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>// w ww. j a v a 2 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./*ww w. j a va 2s. c om*/ * * @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>/* w w w . j a v 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.ja va 2 s . c o m*/ 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 {/*from w w w. ja v a 2s . c om*/ 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); } }