Search in sources :

Example 61 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder in project buck by facebook.

the class WorkspaceGenerator method writeWorkspace.

public Path writeWorkspace() throws IOException {
    DocumentBuilder docBuilder;
    Transformer transformer;
    try {
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (ParserConfigurationException | TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
    DOMImplementation domImplementation = docBuilder.getDOMImplementation();
    final Document doc = domImplementation.createDocument(/* namespaceURI */
    null, "Workspace", /* docType */
    null);
    doc.setXmlVersion("1.0");
    Element rootElem = doc.getDocumentElement();
    rootElem.setAttribute("version", "1.0");
    final Stack<Element> groups = new Stack<>();
    groups.push(rootElem);
    FileVisitor<Map.Entry<String, WorkspaceNode>> visitor = new FileVisitor<Map.Entry<String, WorkspaceNode>>() {

        @Override
        public FileVisitResult preVisitDirectory(Map.Entry<String, WorkspaceNode> dir, BasicFileAttributes attrs) throws IOException {
            Preconditions.checkArgument(dir.getValue() instanceof WorkspaceGroup);
            Element element = doc.createElement("Group");
            element.setAttribute("location", "container:");
            element.setAttribute("name", dir.getKey());
            groups.peek().appendChild(element);
            groups.push(element);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Map.Entry<String, WorkspaceNode> file, BasicFileAttributes attrs) throws IOException {
            Preconditions.checkArgument(file.getValue() instanceof WorkspaceFileRef);
            WorkspaceFileRef fileRef = (WorkspaceFileRef) file.getValue();
            Element element = doc.createElement("FileRef");
            element.setAttribute("location", "container:" + MorePaths.relativize(MorePaths.normalize(outputDirectory), fileRef.getPath()).toString());
            groups.peek().appendChild(element);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Map.Entry<String, WorkspaceNode> file, IOException exc) throws IOException {
            return FileVisitResult.TERMINATE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Map.Entry<String, WorkspaceNode> dir, IOException exc) throws IOException {
            groups.pop();
            return FileVisitResult.CONTINUE;
        }
    };
    walkNodeTree(visitor);
    Path projectWorkspaceDir = getWorkspaceDir();
    projectFilesystem.mkdirs(projectWorkspaceDir);
    Path serializedWorkspace = projectWorkspaceDir.resolve("contents.xcworkspacedata");
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(outputStream);
        transformer.transform(source, result);
        String contentsToWrite = outputStream.toString();
        if (MoreProjectFilesystems.fileContentsDiffer(new ByteArrayInputStream(contentsToWrite.getBytes(Charsets.UTF_8)), serializedWorkspace, projectFilesystem)) {
            projectFilesystem.writeContentsToPath(contentsToWrite, serializedWorkspace);
        }
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    Path xcshareddata = projectWorkspaceDir.resolve("xcshareddata");
    projectFilesystem.mkdirs(xcshareddata);
    Path workspaceSettingsPath = xcshareddata.resolve("WorkspaceSettings.xcsettings");
    String workspaceSettings = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\"" + " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" + "<plist version=\"1.0\">\n" + "<dict>\n" + "\t<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>\n" + "\t<false/>\n" + "</dict>\n" + "</plist>";
    projectFilesystem.writeContentsToPath(workspaceSettings, workspaceSettingsPath);
    return projectWorkspaceDir;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Element(org.w3c.dom.Element) DOMImplementation(org.w3c.dom.DOMImplementation) Document(org.w3c.dom.Document) FileVisitor(java.nio.file.FileVisitor) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) TransformerException(javax.xml.transform.TransformerException) Path(java.nio.file.Path) StreamResult(javax.xml.transform.stream.StreamResult) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Stack(java.util.Stack) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) SortedMap(java.util.SortedMap)

Example 62 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder 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 63 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder 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 64 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder 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 65 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder in project buck by facebook.

the class SchemeGeneratorTest method schemeWithMultipleTargetsBuildsInCorrectOrder.

@Test
public void schemeWithMultipleTargetsBuildsInCorrectOrder() throws Exception {
    ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();
    PBXTarget rootTarget = new PBXNativeTarget("rootRule");
    rootTarget.setGlobalID("rootGID");
    rootTarget.setProductReference(new PBXFileReference("root.a", "root.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
    rootTarget.setProductType(ProductType.STATIC_LIBRARY);
    PBXTarget leftTarget = new PBXNativeTarget("leftRule");
    leftTarget.setGlobalID("leftGID");
    leftTarget.setProductReference(new PBXFileReference("left.a", "left.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
    leftTarget.setProductType(ProductType.STATIC_LIBRARY);
    PBXTarget rightTarget = new PBXNativeTarget("rightRule");
    rightTarget.setGlobalID("rightGID");
    rightTarget.setProductReference(new PBXFileReference("right.a", "right.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
    rightTarget.setProductType(ProductType.STATIC_LIBRARY);
    PBXTarget childTarget = new PBXNativeTarget("childRule");
    childTarget.setGlobalID("childGID");
    childTarget.setProductReference(new PBXFileReference("child.a", "child.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
    childTarget.setProductType(ProductType.STATIC_LIBRARY);
    Path pbxprojectPath = Paths.get("foo/Foo.xcodeproj/project.pbxproj");
    targetToProjectPathMapBuilder.put(rootTarget, pbxprojectPath);
    targetToProjectPathMapBuilder.put(leftTarget, pbxprojectPath);
    targetToProjectPathMapBuilder.put(rightTarget, pbxprojectPath);
    targetToProjectPathMapBuilder.put(childTarget, pbxprojectPath);
    SchemeGenerator schemeGenerator = new SchemeGenerator(projectFilesystem, Optional.of(childTarget), ImmutableSet.of(rootTarget, leftTarget, rightTarget, childTarget), ImmutableSet.of(), ImmutableSet.of(), "TestScheme", Paths.get("_gen/Foo.xcworkspace/scshareddata/xcshemes"), false, /* primaryTargetIsBuildWithBuck */
    false, /* parallelizeBuild */
    Optional.empty(), /* runnablePath */
    Optional.empty(), /* remoteRunnablePath */
    SchemeActionType.DEFAULT_CONFIG_NAMES, targetToProjectPathMapBuilder.build(), XCScheme.LaunchAction.LaunchStyle.AUTO);
    Path schemePath = schemeGenerator.writeScheme();
    String schemeXml = projectFilesystem.readFileIfItExists(schemePath).get();
    System.out.println(schemeXml);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document scheme = dBuilder.parse(projectFilesystem.newFileInputStream(schemePath));
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    XPathExpression expr = xpath.compile("//BuildAction//BuildableReference/@BlueprintIdentifier");
    NodeList nodes = (NodeList) expr.evaluate(scheme, XPathConstants.NODESET);
    List<String> expectedOrdering = ImmutableList.of("rootGID", "leftGID", "rightGID", "childGID");
    List<String> actualOrdering = Lists.newArrayList();
    for (int i = 0; i < nodes.getLength(); i++) {
        actualOrdering.add(nodes.item(i).getNodeValue());
    }
    assertThat(actualOrdering, equalTo(expectedOrdering));
}
Also used : PBXTarget(com.facebook.buck.apple.xcode.xcodeproj.PBXTarget) XPath(javax.xml.xpath.XPath) Path(java.nio.file.Path) XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) PBXNativeTarget(com.facebook.buck.apple.xcode.xcodeproj.PBXNativeTarget) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) ImmutableMap(com.google.common.collect.ImmutableMap) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) PBXFileReference(com.facebook.buck.apple.xcode.xcodeproj.PBXFileReference) Test(org.junit.Test)

Aggregations

DocumentBuilder (javax.xml.parsers.DocumentBuilder)883 Document (org.w3c.dom.Document)694 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)622 Element (org.w3c.dom.Element)339 IOException (java.io.IOException)276 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)276 NodeList (org.w3c.dom.NodeList)267 InputSource (org.xml.sax.InputSource)238 SAXException (org.xml.sax.SAXException)235 Node (org.w3c.dom.Node)199 StringReader (java.io.StringReader)167 Test (org.junit.Test)127 DOMSource (javax.xml.transform.dom.DOMSource)102 File (java.io.File)99 ByteArrayInputStream (java.io.ByteArrayInputStream)86 InputStream (java.io.InputStream)73 ArrayList (java.util.ArrayList)72 StreamResult (javax.xml.transform.stream.StreamResult)65 Transformer (javax.xml.transform.Transformer)59 SAXParseException (org.xml.sax.SAXParseException)56