public static String encodeXML(Document document, boolean compress, boolean encrypt, boolean location) { // XFormsServer.logger.debug("XForms - encoding XML."); // Get SAXStore // TODO: This is not optimal since we create a second in-memory representation. Should stream instead. final SAXStore saxStore = new SAXStore(); // NOTE: We don't encode XML comments and use only the ContentHandler interface final Source source = location ? new LocationDocumentSource(document) : new DocumentSource(document); TransformerUtils.sourceToSAX(source, saxStore); // Serialize SAXStore to bytes // TODO: This is not optimal since we create a third in-memory representation. Should stream instead. final byte[] bytes; try { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); saxStore.writeExternal(new ObjectOutputStream(byteArrayOutputStream)); bytes = byteArrayOutputStream.toByteArray(); } catch (IOException e) { throw new OXFException(e); } // Encode bytes return encodeBytes(bytes, compress, encrypt); }
/** * XML Pretty Printer XSLT Transformation * * @param document the Dom4j Document * @return the transformed document */ public static Document styleDocument( Document document ) { // load the transformer using JAXP TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = factory.newTransformer( new StreamSource( ParserUtils.class .getResourceAsStream( "/org/apache/directory/shared/dsmlv2/DSMLv2.xslt" ) ) ); } catch ( TransformerConfigurationException e1 ) { LOG.warn( "Failed to create the XSLT transformer", e1 ); // return original document return document; } // now lets style the given document DocumentSource source = new DocumentSource( document ); DocumentResult result = new DocumentResult(); try { transformer.transform( source, result ); } catch ( TransformerException e ) { // return original document return document; } // return the transformed document return result.getDocument(); }
/** * Applies an XSLT template on the XML in the sourceDocument. The resulting Dom4j Document is * returned. * * @param xml * the source xml * @param template * the XSLT template * @return the resulting XML */ public String applyTemplate(String xml, InputStream template, String url) { try { boolean hasId; // This regular expression has been created to find out if there is an id after // the entity name in the url. For example: // https://livebuilds.openbravo.com/erp_main_pgsql/ws/dal/ADUser/100 String regExp = "^(.*)[dal]+[\\/][A-Za-z0-9]+[\\/][A-Za-z0-9]+"; final TransformerFactory factory = TransformerFactory.newInstance(); final Transformer transformer = factory.newTransformer(new StreamSource(template)); final DocumentSource source = new DocumentSource(DocumentHelper.parseText(xml)); final StringWriter sw = new StringWriter(); final StreamResult response = new StreamResult(sw); if (url.matches(regExp)) { hasId = true; } else { hasId = false; } transformer.setParameter("hasId", hasId); transformer.setParameter("url", url); transformer.transform(source, response); return sw.toString(); } catch (final Exception e) { throw new OBException(e); } }
public static Document transform(Transformer transformer, Document d) throws TransformerException { DocumentSource source = new DocumentSource(d); DocumentResult result = new DocumentResult(); // TODO: Allow the user to specify stylesheet parameters? transformer.transform(source, result); return result.getDocument(); }
@Override public void finish() { try { BugCollection bugCollection = getBugCollection(); bugCollection.setWithMessages(true); // Decorate the XML with messages to display Document document = bugCollection.toDocument(); // new AddMessages(bugCollection, document).execute(); // Get the stylesheet as a StreamSource. // First, try to load the stylesheet from the filesystem. // If that fails, try loading it as a resource. InputStream xslInputStream = getStylesheetStream(stylesheet); StreamSource xsl = new StreamSource(xslInputStream); xsl.setSystemId(stylesheet); // Create a transformer using the stylesheet TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(xsl); // Source document is the XML generated from the BugCollection DocumentSource source = new DocumentSource(document); // Write result to output stream StreamResult result = new StreamResult(outputStream); // Do the transformation transformer.transform(source, result); } catch (Exception e) { logError("Could not generate HTML output", e); fatalException = e; if (FindBugs.DEBUG) e.printStackTrace(); } outputStream.close(); }
public Graph importFile(final String parentURI, Document document) throws GrddlTransformException { final DocumentResult result = new DocumentResult(); final DocumentSource source = new DocumentSource(document); try { return xsltTransformerRegistry.transformWithCorrectClassLoader(XSLTTransformerRegistry.XUNIT_NUNIT_TO_JUNIT_XSL, new XSLTTransformerExecutor<Graph>() { @Override public Graph execute(Transformer transformer) throws TransformerException, GrddlTransformException { transformer.transform(source, result); return jUnitRDFizer.importFile(parentURI, result.getDocument()); } }); } catch (TransformerException e) { throw new ShineRuntimeException(e); } }
/** * Transform a dom4j Document into a TinyTree. */ public static DocumentInfo dom4jToTinyTree(Configuration configuration, Document document, boolean location) { final TinyBuilder treeBuilder = new TinyBuilder(); try { final Transformer identity = getIdentityTransformer(configuration); identity.transform(location ? new LocationDocumentSource(document) : new DocumentSource(document), treeBuilder); } catch (TransformerException e) { throw new OXFException(e); } return (DocumentInfo) treeBuilder.getCurrentRoot(); }
/** * Transform a dom4j document into a W3C DOM document * * @param document dom4j document * @return W3C DOM document * @throws TransformerException */ public static org.w3c.dom.Document dom4jToDomDocument(Document document) throws TransformerException { final Transformer identity = getIdentityTransformer(); final DOMResult domResult = new DOMResult(); identity.transform(new DocumentSource(document), domResult); final Node resultNode = domResult.getNode(); return (resultNode instanceof org.w3c.dom.Document) ? ((org.w3c.dom.Document) resultNode) : resultNode.getOwnerDocument(); }
/** * Transform a dom4j document to a String. */ public static String dom4jToString(Document document, boolean location) { try { final Transformer identity = getXMLIdentityTransformer(); identity.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); final StringBuilderWriter writer = new StringBuilderWriter(); identity.transform(location ? new LocationDocumentSource(document) : new DocumentSource(document), new StreamResult(writer)); return writer.toString(); } catch (TransformerException e) { throw new OXFException(e); } }
private void genEnum(TransformerFactory txFactory, Document doc, String basePkgPath) { try { InputStream xlsInputStream = getClass().getClassLoader().getResourceAsStream("xsl/enum.xsl"); Transformer tx = txFactory.newTransformer(new StreamSource(xlsInputStream)); List enumNodes = doc.selectNodes("root/enums/enum"); for (Object n : enumNodes) { Element enumNode = (Element) n; for (Object n2 : enumNode.selectNodes("field")) { Element fieldNode = (Element) n2; fieldNode.addAttribute("name", fieldNode.attributeValue("name").toUpperCase()); // System.out.println(fieldNode.attributeValue("name")); } } // DocumentSource src = new DocumentSource(doc); DocumentResult rzt = new DocumentResult(); tx.transform(src, rzt); Document rztDoc = rzt.getDocument(); String filePath = FileUtil.combinePath(basePkgPath, "constant"); FileUtil.mkdir(filePath); for (Object jn : rztDoc.selectNodes("enums/enum")) { Element jenumNode = (Element) jn; String enumName = jenumNode.attributeValue("name"); String jenumFilePath = FileUtil.combinePath(filePath, enumName + ".java"); Writer writer = null; try { writer = new OutputStreamWriter(new FileOutputStream(jenumFilePath), "utf-8"); String enumCodes = jenumNode.getText(); enumCodes = enumCodes.replace(",;", ";"); writer.write(enumCodes); } finally { if (writer != null) { writer.close(); } } Log.info("gen enum %s at %s", enumName, jenumFilePath); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
@Test public void testShouldTransformFromXSLForNunit2Dot6ToJunitCorrectly() throws Exception { String nunitInputXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!--\n" + "This file represents the results of running a test suite\n" + "-->\n" + "<test-results name=\"C:\\Program Files\\NUnit 2.6\\bin\\tests\\mock-assembly.dll\" total=\"21\" errors=\"1\" failures=\"1\" not-run=\"7\" inconclusive=\"1\" ignored=\"4\" skipped=\"0\" invalid=\"3\" date=\"2012-02-04\" time=\"11:46:05\">\n" + " <environment nunit-version=\"2.6.0.12035\" clr-version=\"2.0.50727.4963\" os-version=\"Microsoft Windows NT 6.1.7600.0\" platform=\"Win32NT\" cwd=\"C:\\Program Files\\NUnit 2.6\\bin\" machine-name=\"CHARLIE-LAPTOP\" user=\"charlie\" user-domain=\"charlie-laptop\" />\n" + " <culture-info current-culture=\"en-US\" current-uiculture=\"en-US\" />\n" + " <test-suite type=\"Assembly\" name=\"C:\\Program Files\\NUnit 2.6\\bin\\tests\\mock-assembly.dll\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.094\" asserts=\"0\">\n" + " <results>\n" + " <test-suite type=\"Namespace\" name=\"NUnit\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.078\" asserts=\"0\">\n" + " <results>\n" + " <test-suite type=\"Namespace\" name=\"Tests\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.078\" asserts=\"0\">\n" + " <results>\n" + " <test-suite type=\"Namespace\" name=\"Assemblies\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.031\" asserts=\"0\">\n" + " <results>\n" + " <test-suite type=\"TestFixture\" name=\"MockTestFixture\" description=\"Fake Test Fixture\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.031\" asserts=\"0\">\n" + " <categories>\n" + " <category name=\"FixtureCategory\" />\n" + " </categories>\n" + " <results>\n" + " <test-case name=\"NUnit.Tests.Assemblies.MockTestFixture.TestWithException\" executed=\"True\" result=\"Error\" success=\"False\" time=\"0.000\" asserts=\"0\">\n" + " <failure>\n" + " <message>Intentional Error</message>\n" + " <stack-trace>Some Stack Trace</stack-trace>\n" + " </failure>\n" + " </test-case>\n" + " <test-case name=\"NUnit.Tests.Assemblies.MockTestFixture.FailingTest\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.016\" asserts=\"0\">\n" + " <failure>\n" + " <message>Intentional failure</message>\n" + " <stack-trace>Some Stack Trace</stack-trace>\n" + " </failure>\n" + " </test-case>\n" + " <test-case name=\"NUnit.Tests.Assemblies.MockTestFixture.MockTest3\" executed=\"True\" result=\"Success\" success=\"True\" time=\"0.016\" asserts=\"0\">\n" + " <categories>\n" + " <category name=\"AnotherCategory\" />\n" + " <category name=\"MockCategory\" />\n" + " </categories>\n" + " <reason>\n" + " <message>Success</message>\n" + " </reason>\n" + " </test-case>\n" + " </results>\n" + " </test-suite>\n" + " </results>\n" + " </test-suite>\n" + " </results>\n" + " </test-suite>\n" + " </results>\n" + " </test-suite>\n" + " </results>\n" + " </test-suite>\n" + "</test-results>"; String expectedResultantJunitFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<testsuites>" + "<testsuite name=\"NUnit.Tests.Assemblies.MockTestFixture\" tests=\"3\" time=\"0.031\" failures=\"1\" errors=\"1\" skipped=\"0\">" + "<testcase classname=\"NUnit.Tests.Assemblies.MockTestFixture\" name=\"TestWithException\" time=\"0.000\">" + "<error message=\"Intentional Error\">Some Stack Trace</error><" + "/testcase><testcase classname=\"NUnit.Tests.Assemblies.MockTestFixture\" name=\"FailingTest\" time=\"0.016\">" + "<failure message=\"Intentional failure\">Some Stack Trace</failure>" + "</testcase><testcase classname=\"NUnit.Tests.Assemblies.MockTestFixture\" name=\"MockTest3\" time=\"0.016\"/>" + "</testsuite>" + "</testsuites>"; try(InputStream xsl = getClass().getClassLoader().getResourceAsStream(XSLTTransformerRegistry.XUNIT_NUNIT_TO_JUNIT_XSL)) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); DocumentSource source = new DocumentSource(new SAXReader().read(new InputSource(new ByteArrayInputStream(nunitInputXml.getBytes("utf-8"))))); DocumentResult result = new DocumentResult(); Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsl)); transformer.transform(source, result); assertThat(result.getDocument().asXML(), isIdenticalTo(expectedResultantJunitFormat)); } }
@Test public void testShouldTransformFromXSLForNunit2Dot5AndEarlierToJunitCorrectly() throws Exception { String nunitInputXml = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<!--This file represents the results of running a test suite-->" + "<test-results name=\"/home/erik/coding/test/nunittests/Tests.dll\" total=\"4\" failures=\"1\" not-run=\"0\" date=\"2007-07-27\" time=\"11:18:43\">" + " <environment nunit-version=\"2.2.8.0\" clr-version=\"2.0.50727.42\" os-version=\"Unix 2.6.18.4\" platform=\"Unix\" cwd=\"/home/erik/coding/test/nunittests\" machine-name=\"akira.ramfelt.se\" user=\"erik\" user-domain=\"akira.ramfelt.se\" />" + " <culture-info current-culture=\"sv-SE\" current-uiculture=\"sv-SE\" />" + " <test-suite name=\"/home/erik/coding/test/nunittests/Tests.dll\" success=\"False\" time=\"0.404\" asserts=\"0\">" + " <results>" + " <test-suite name=\"UnitTests\" success=\"False\" time=\"0.393\" asserts=\"0\">" + " <results>" + " <test-suite name=\"UnitTests.MainClassTest\" success=\"False\" time=\"0.289\" asserts=\"0\">" + " <results>" + " <test-case name=\"UnitTests.MainClassTest.TestPropertyValue\" executed=\"True\" success=\"True\" time=\"0.146\" asserts=\"1\" />" + " <test-case name=\"UnitTests.MainClassTest.TestMethodUpdateValue\" executed=\"True\" success=\"True\" time=\"0.001\" asserts=\"1\" />" + " <test-case name=\"UnitTests.MainClassTest.TestFailure\" executed=\"True\" success=\"False\" time=\"0.092\" asserts=\"1\" result=\"Failure\">" + " <failure>" + " <message><![CDATA[ Expected failure" + " Expected: 30" + " But was: 20" + "]]></message>" + " <stack-trace><![CDATA[ at UnitTests.MainClassTest.TestFailure () [0x00000] " + " at <0x00000> <unknown method>" + " at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[])" + " at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] " + "]]></stack-trace>" + " </failure>" + " </test-case>" + " </results>" + " </test-suite>" + " </results>" + " </test-suite>" + " </results>" + " </test-suite>" + "</test-results>"; String expectedResultantJunitFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<testsuites>" + "<testsuite name=\"UnitTests.MainClassTest\" tests=\"3\" time=\"0.289\" failures=\"1\" errors=\"\" skipped=\"0\">" + "<testcase classname=\"UnitTests.MainClassTest\" name=\"TestPropertyValue\" time=\"0.146\"/>" + "<testcase classname=\"UnitTests.MainClassTest\" name=\"TestMethodUpdateValue\" time=\"0.001\"/>" + "<testcase classname=\"UnitTests.MainClassTest\" name=\"TestFailure\" time=\"0.092\">" + "<failure message=\" Expected failure Expected: 30 But was: 20\"> " + "at UnitTests.MainClassTest.TestFailure () [0x00000] at <0x00000> <unknown method> at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[]) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] " + "</failure>" + "</testcase>" + "</testsuite>" + "</testsuites>"; try (InputStream xsl = getClass().getClassLoader().getResourceAsStream(XSLTTransformerRegistry.XUNIT_NUNIT_TO_JUNIT_XSL)) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); DocumentSource source = new DocumentSource(new SAXReader().read(new InputSource(new ByteArrayInputStream(nunitInputXml.getBytes("utf-8"))))); DocumentResult result = new DocumentResult(); Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsl)); transformer.transform(source, result); assertThat(result.getDocument().asXML(), isIdenticalTo(expectedResultantJunitFormat)); } }
public static DocumentSource getDocumentSource(final Document d) { /* * Saxon's error handler is expensive for the service it provides so we just use our * singleton instead. * * Wrt expensive, delta in heap dump info below is amount of bytes allocated during the * handling of a single request to '/' in the examples app. i.e. The trace below was * responsible for creating 200k of garbage during the handing of a single request to '/'. * * delta: 213408 live: 853632 alloc: 4497984 trace: 380739 class: byte[] * * TRACE 380739: * java.nio.HeapByteBuffer.<init>(HeapByteBuffer.java:39) * java.nio.ByteBuffer.allocate(ByteBuffer.java:312) * sun.nio.cs.StreamEncoder$CharsetSE.<init>(StreamEncoder.java:310) * sun.nio.cs.StreamEncoder$CharsetSE.<init>(StreamEncoder.java:290) * sun.nio.cs.StreamEncoder$CharsetSE.<init>(StreamEncoder.java:274) * sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:69) * java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:93) * java.io.PrintWriter.<init>(PrintWriter.java:109) * java.io.PrintWriter.<init>(PrintWriter.java:92) * org.orbeon.saxon.StandardErrorHandler.<init>(StandardErrorHandler.java:22) * org.orbeon.saxon.event.Sender.sendSAXSource(Sender.java:165) * org.orbeon.saxon.event.Sender.send(Sender.java:94) * org.orbeon.saxon.IdentityTransformer.transform(IdentityTransformer.java:31) * org.orbeon.oxf.xml.XMLUtils.getDigest(XMLUtils.java:453) * org.orbeon.oxf.xml.XMLUtils.getDigest(XMLUtils.java:423) * org.orbeon.oxf.processor.generator.DOMGenerator.<init>(DOMGenerator.java:93) * * Before mod * * 1.4.2_06-b03 P4 2.6 Ghz / 50 th tc 4.1.30 10510 ms ( 150 mb ), 7124 ( 512 mb ) 2.131312472239924 ( 150 mb ), 1.7474380872589803 ( 512 mb ) * * after mod * * 1.4.2_06-b03 P4 2.6 Ghz / 50 th tc 4.1.30 9154 ms ( 150 mb ), 6949 ( 512 mb ) 1.7316203642295738 ( 150 mb ), 1.479365288194895 ( 512 mb ) * */ final LocationDocumentSource lds = new LocationDocumentSource(d); final XMLReader rdr = lds.getXMLReader(); rdr.setErrorHandler(XMLUtils.ERROR_HANDLER); return lds; }
public static byte[] getDigest(Document document) { final DocumentSource ds = getDocumentSource(document); return XMLUtils.getDigest(ds); }
/** * Transform a dom4j document to a SAXStore. */ public static SAXStore dom4jToSAXStore(Document document, boolean location) { final SAXStore saxStore = new SAXStore(); sourceToSAX(location ? new LocationDocumentSource(document) : new DocumentSource(document), saxStore); return saxStore; }
/** * Applies the transform to the Dom4J document * * @param transformer * @param d * the document to transform * * @return an array containing a single XML string representing the * transformed document * @throws TransformerException * thrown if an XSLT runtime error happens during transformation */ public static Document transform(Transformer transformer, Document d) throws TransformerException { DocumentSource source = new DocumentSource(d); DocumentResult result = new DocumentResult(); // TODO: Allow the user to specify stylesheet parameters? transformer.transform(source, result); return result.getDocument(); }
/** * Gets the docment source. * * @return the document source. */ public Source getSource() { return new DocumentSource(dom); }