Search in sources :

Example 11 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project che by eclipse.

the class Launching method serializeDocumentInt.

/**
     * Serializes a XML document into a string - encoded in UTF8 format,
     * with platform line separators.
     *
     * @param doc document to serialize
     * @return the document as a string
     * @throws TransformerException if an unrecoverable error occurs during the serialization
     * @throws IOException if the encoding attempted to be used is not supported
     */
private static String serializeDocumentInt(Document doc) throws TransformerException, IOException {
    ByteArrayOutputStream s = new ByteArrayOutputStream();
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    //$NON-NLS-1$
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    //$NON-NLS-1$
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult outputTarget = new StreamResult(s);
    transformer.transform(source, outputTarget);
    //$NON-NLS-1$
    return s.toString("UTF8");
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 12 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project buck by facebook.

the class TestRunning method writeXmlOutput.

/**
   * Writes the test results in XML format to the supplied writer.
   *
   * This method does NOT close the writer object.
   * @param allResults The test results.
   * @param writer The writer in which the XML data will be written to.
   */
public static void writeXmlOutput(List<TestResults> allResults, Writer writer) throws IOException {
    try {
        // Build the XML output.
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        // Create the <tests> tag. All test data will be within this tag.
        Element testsEl = doc.createElement("tests");
        doc.appendChild(testsEl);
        for (TestResults results : allResults) {
            for (TestCaseSummary testCase : results.getTestCases()) {
                // Create the <test name="..." status="..." time="..."> tag.
                // This records a single test case result in the test suite.
                Element testEl = doc.createElement("test");
                testEl.setAttribute("name", testCase.getTestCaseName());
                testEl.setAttribute("status", testCase.isSuccess() ? "PASS" : "FAIL");
                testEl.setAttribute("time", Long.toString(testCase.getTotalTime()));
                testsEl.appendChild(testEl);
                // Loop through the test case and add XML data (name, message, and
                // stacktrace) for each individual test, if present.
                addExtraXmlInfo(testCase, testEl);
            }
        }
        // Write XML to the writer.
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
    } catch (TransformerException | ParserConfigurationException ex) {
        throw new IOException("Unable to build the XML document!");
    }
}
Also used : 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) Element(org.w3c.dom.Element) TestResults(com.facebook.buck.test.TestResults) IOException(java.io.IOException) Document(org.w3c.dom.Document) DocumentBuilder(javax.xml.parsers.DocumentBuilder) TestCaseSummary(com.facebook.buck.test.TestCaseSummary) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 13 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project buck by facebook.

the class BaseRunner method writeResult.

/**
   * The test result file is written as XML to avoid introducing a dependency on JSON (see class
   * overview).
   */
protected void writeResult(String testClassName, List<TestResult> results) throws IOException, ParserConfigurationException, TransformerException {
    // XML writer logic taken from:
    // http://www.genedavis.com/library/xml/java_dom_xml_creation.jsp
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    doc.setXmlVersion("1.1");
    Element root = doc.createElement("testcase");
    root.setAttribute("name", testClassName);
    root.setAttribute("runner_capabilities", getRunnerCapabilities());
    doc.appendChild(root);
    for (TestResult result : results) {
        Element test = doc.createElement("test");
        // suite attribute
        test.setAttribute("suite", result.testClassName);
        // name attribute
        test.setAttribute("name", result.testMethodName);
        // success attribute
        boolean isSuccess = result.isSuccess();
        test.setAttribute("success", Boolean.toString(isSuccess));
        // type attribute
        test.setAttribute("type", result.type.toString());
        // time attribute
        long runTime = result.runTime;
        test.setAttribute("time", String.valueOf(runTime));
        // Include failure details, if appropriate.
        Throwable failure = result.failure;
        if (failure != null) {
            String message = failure.getMessage();
            test.setAttribute("message", message);
            String stacktrace = stackTraceToString(failure);
            test.setAttribute("stacktrace", stacktrace);
        }
        // stdout, if non-empty.
        if (result.stdOut != null) {
            Element stdOutEl = doc.createElement("stdout");
            stdOutEl.appendChild(doc.createTextNode(result.stdOut));
            test.appendChild(stdOutEl);
        }
        // stderr, if non-empty.
        if (result.stdErr != null) {
            Element stdErrEl = doc.createElement("stderr");
            stdErrEl.appendChild(doc.createTextNode(result.stdErr));
            test.appendChild(stdErrEl);
        }
        root.appendChild(test);
    }
    // Create an XML transformer that pretty-prints with a 2-space indent.
    // The transformer factory uses a system property to find the class to use. We need to default
    // to the system default since we have the user's classpath and they may not have everything set
    // up for the XSLT transform to work.
    String vendor = System.getProperty("java.vm.vendor");
    String factoryClass;
    if ("IBM Corporation".equals(vendor)) {
        // Used in the IBM JDK --- from
        // https://www.ibm.com/support/knowledgecenter/SSYKE2_8.0.0/com.ibm.java.aix.80.doc/user/xml/using_xml.html
        factoryClass = "com.ibm.xtq.xslt.jaxp.compiler.TransformerFactoryImpl";
    } else {
        // Used in the OpenJDK and the Oracle JDK.
        factoryClass = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
    }
    // When we get this far, we're exiting, so no need to reset the property.
    System.setProperty("javax.xml.transform.TransformerFactory", factoryClass);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer trans = transformerFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    // Write the result to a file.
    String testSelectorSuffix = "";
    if (!testSelectorList.isEmpty()) {
        testSelectorSuffix += ".test_selectors";
    }
    if (isDryRun) {
        testSelectorSuffix += ".dry_run";
    }
    OutputStream output;
    if (outputDirectory != null) {
        File outputFile = new File(outputDirectory, testClassName + testSelectorSuffix + ".xml");
        output = new BufferedOutputStream(new FileOutputStream(outputFile));
    } else {
        output = System.out;
    }
    StreamResult streamResult = new StreamResult(output);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, streamResult);
    if (outputDirectory != null) {
        output.close();
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Element(org.w3c.dom.Element) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) Document(org.w3c.dom.Document) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 14 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project buck by facebook.

the class BuckXmlTestRunListener method addMainTestResult.

/**
   * Adds one more XML element to the test_result.xml tracking the
   * result of the whole process.
   */
private void addMainTestResult() {
    try {
        File resultFile = getResultFile(mReportDir);
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(resultFile);
        Node testsuite = doc.getElementsByTagName("testsuite").item(0);
        if (mRunFailureMessage != null) {
            Element failureNode = doc.createElement("failure");
            failureNode.setTextContent(mRunFailureMessage);
            testsuite.appendChild(failureNode);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(resultFile);
            transformer.transform(source, result);
        }
    } catch (IOException | ParserConfigurationException | SAXException | TransformerException e) {
        throw new RuntimeException(e);
    }
}
Also used : 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) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) File(java.io.File) TransformerException(javax.xml.transform.TransformerException)

Example 15 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project tinker by Tencent.

the class JavaXmlUtil method saveDocument.

/**
     * save document
     *
     * @param document
     * @param outputFullFilename
     */
public static void saveDocument(final Document document, final String outputFullFilename) {
    OutputStream outputStream = null;
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, Constant.Encoding.UTF8);
        outputStream = new FileOutputStream(outputFullFilename);
        StreamResult result = new StreamResult(outputStream);
        transformer.transform(domSource, result);
    } catch (Exception e) {
        throw new JavaXmlUtilException(e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (Exception e) {
                throw new JavaXmlUtilException(e);
            }
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream)

Aggregations

TransformerFactory (javax.xml.transform.TransformerFactory)188 Transformer (javax.xml.transform.Transformer)158 StreamResult (javax.xml.transform.stream.StreamResult)137 DOMSource (javax.xml.transform.dom.DOMSource)113 TransformerException (javax.xml.transform.TransformerException)63 StreamSource (javax.xml.transform.stream.StreamSource)60 StringWriter (java.io.StringWriter)58 Document (org.w3c.dom.Document)53 IOException (java.io.IOException)42 Source (javax.xml.transform.Source)41 DocumentBuilder (javax.xml.parsers.DocumentBuilder)37 File (java.io.File)36 Element (org.w3c.dom.Element)31 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)29 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)27 Result (javax.xml.transform.Result)24 SAXException (org.xml.sax.SAXException)24 StringReader (java.io.StringReader)23 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)23 ByteArrayOutputStream (java.io.ByteArrayOutputStream)20