Search in sources :

Example 1 with Element

use of org.w3c.dom.Element in project buck by facebook.

the class SchemeGenerator method serializeBuildableReference.

public static Element serializeBuildableReference(Document doc, XCScheme.BuildableReference buildableReference) {
    Element refElem = doc.createElement("BuildableReference");
    refElem.setAttribute("BuildableIdentifier", "primary");
    refElem.setAttribute("BlueprintIdentifier", buildableReference.getBlueprintIdentifier());
    refElem.setAttribute("BuildableName", buildableReference.getBuildableName());
    refElem.setAttribute("BlueprintName", buildableReference.getBlueprintName());
    String referencedContainer = "container:" + buildableReference.getContainerRelativePath();
    refElem.setAttribute("ReferencedContainer", referencedContainer);
    return refElem;
}
Also used : Element(org.w3c.dom.Element)

Example 2 with Element

use of org.w3c.dom.Element 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 3 with Element

use of org.w3c.dom.Element 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 4 with Element

use of org.w3c.dom.Element in project buck by facebook.

the class TestRunning method addExtraXmlInfo.

/**
   * A helper method that adds extra XML.
   *
   * This includes a test name, time (in ms), message, and stack trace, when
   * present.
   * Example:
   *
   * <pre>
   * &lt;testresult name="failed_test" time="200">
   *   &lt;message>Reason for test failure&lt;/message>
   *   &lt;stacktrace>Stacktrace here&lt;/stacktrace>
   * &lt;/testresult>
   * </pre>
   *
   * @param testCase The test case summary containing one or more tests.
   * @param testEl The XML element object for the <test> tag, in which extra
   *     information tags will be added.
   */
@VisibleForTesting
static void addExtraXmlInfo(TestCaseSummary testCase, Element testEl) {
    Document doc = testEl.getOwnerDocument();
    // Loop through the test case and extract test data.
    for (TestResultSummary testResult : testCase.getTestResults()) {
        // Extract the test name and time.
        String name = Strings.nullToEmpty(testResult.getTestName());
        String time = Long.toString(testResult.getTime());
        // Create the tag: <testresult name="..." time="...">
        Element testResultEl = doc.createElement("testresult");
        testResultEl.setAttribute("name", name);
        testResultEl.setAttribute("time", time);
        testEl.appendChild(testResultEl);
        // Create the tag: <message>(Error message here)</message>
        Element messageEl = doc.createElement("message");
        String message = Strings.nullToEmpty(testResult.getMessage());
        messageEl.appendChild(doc.createTextNode(message));
        testResultEl.appendChild(messageEl);
        // Create the tag: <stacktrace>(Stacktrace here)</stacktrace>
        Element stacktraceEl = doc.createElement("stacktrace");
        String stacktrace = Strings.nullToEmpty(testResult.getStacktrace());
        stacktraceEl.appendChild(doc.createTextNode(stacktrace));
        testResultEl.appendChild(stacktraceEl);
    }
}
Also used : Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) TestResultSummary(com.facebook.buck.test.TestResultSummary) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 5 with Element

use of org.w3c.dom.Element in project sharding-jdbc by dangdangdotcom.

the class ShardingJdbcDataSourceBeanDefinitionParser method parseTableRuleConfig.

private BeanDefinition parseTableRuleConfig(final Element tableElement) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(TableRuleConfig.class);
    String dynamic = tableElement.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.DYNAMIC_TABLE_ATTRIBUTE);
    if (!Strings.isNullOrEmpty(dynamic)) {
        factory.addPropertyValue("dynamic", dynamic);
    }
    String actualTables = tableElement.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.ACTUAL_TABLES_ATTRIBUTE);
    if (!Strings.isNullOrEmpty(actualTables)) {
        factory.addPropertyValue("actualTables", actualTables);
    }
    String dataSourceNames = tableElement.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.DATA_SOURCE_NAMES_ATTRIBUTE);
    if (!Strings.isNullOrEmpty(dataSourceNames)) {
        factory.addPropertyValue("dataSourceNames", dataSourceNames);
    }
    String databaseStrategy = tableElement.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.DATABASE_STRATEGY_ATTRIBUTE);
    if (!Strings.isNullOrEmpty(databaseStrategy)) {
        factory.addPropertyReference("databaseStrategy", databaseStrategy);
    }
    String tableStrategy = tableElement.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.TABLE_STRATEGY_ATTRIBUTE);
    if (!Strings.isNullOrEmpty(tableStrategy)) {
        factory.addPropertyReference("tableStrategy", tableStrategy);
    }
    List<Element> autoIncrementColumns = DomUtils.getChildElementsByTagName(tableElement, ShardingJdbcDataSourceBeanDefinitionParserTag.AUTO_INCREMENT_COLUMN);
    if (null == autoIncrementColumns || autoIncrementColumns.isEmpty()) {
        return factory.getBeanDefinition();
    }
    factory.addPropertyValue("autoIncrementColumns", Lists.transform(autoIncrementColumns, new Function<Element, AutoIncrementColumnConfig>() {

        @Override
        public AutoIncrementColumnConfig apply(final Element input) {
            AutoIncrementColumnConfig result = new AutoIncrementColumnConfig();
            result.setColumnName(input.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.COLUMN_NAME));
            result.setColumnIdGeneratorClass(input.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.COLUMN_ID_GENERATOR_CLASS));
            return result;
        }
    }));
    return factory.getBeanDefinition();
}
Also used : Function(com.google.common.base.Function) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) AutoIncrementColumnConfig(com.dangdang.ddframe.rdb.sharding.config.common.api.config.AutoIncrementColumnConfig) Element(org.w3c.dom.Element)

Aggregations

Element (org.w3c.dom.Element)9071 Document (org.w3c.dom.Document)2650 NodeList (org.w3c.dom.NodeList)2102 Node (org.w3c.dom.Node)1854 ArrayList (java.util.ArrayList)957 DocumentBuilder (javax.xml.parsers.DocumentBuilder)792 IOException (java.io.IOException)731 Test (org.junit.Test)693 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)590 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)488 HashMap (java.util.HashMap)434 SAXException (org.xml.sax.SAXException)405 File (java.io.File)358 Attr (org.w3c.dom.Attr)332 InputStream (java.io.InputStream)308 QName (javax.xml.namespace.QName)292 Map (java.util.Map)285 JAXBElement (javax.xml.bind.JAXBElement)285 NamedNodeMap (org.w3c.dom.NamedNodeMap)266 List (java.util.List)264