Search in sources :

Example 61 with XPathExpression

use of javax.xml.xpath.XPathExpression in project camel by apache.

the class DependencyResolver method xpath.

private static String xpath(File pom, String expression) throws Exception {
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(pom);
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(expression);
    String res = expr.evaluate(doc);
    if (res != null && res.trim().length() == 0) {
        res = null;
    }
    return res;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Document(org.w3c.dom.Document)

Example 62 with XPathExpression

use of javax.xml.xpath.XPathExpression in project camel by apache.

the class DependencyResolver method getDependencies.

/**
     * Retrieves a list of dependencies of the given scope
     */
public static List<String> getDependencies(String pom, String scope) throws Exception {
    String expression = "/project/dependencies/dependency[scope='" + scope + "']";
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(pom);
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(expression);
    List<String> dependencies = new LinkedList<>();
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        try (StringWriter writer = new StringWriter()) {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(node), new StreamResult(writer));
            String xml = writer.toString();
            dependencies.add(xml);
        }
    }
    return dependencies;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) LinkedList(java.util.LinkedList) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Example 63 with XPathExpression

use of javax.xml.xpath.XPathExpression in project camel by apache.

the class BomGeneratorMojo method writePom.

private void writePom(Document pom) throws Exception {
    XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyNodes = (NodeList) xpath.evaluate(pom, XPathConstants.NODESET);
    // Remove empty text nodes
    for (int i = 0; i < emptyNodes.getLength(); i++) {
        Node emptyNode = emptyNodes.item(i);
        emptyNode.getParentNode().removeChild(emptyNode);
    }
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DOMSource source = new DOMSource(pom);
    targetPom.getParentFile().mkdirs();
    String content;
    try (StringWriter out = new StringWriter()) {
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        content = out.toString();
    }
    // Fix header formatting problem
    content = content.replaceFirst("-->", "-->\n");
    writeFileIfChanged(content, targetPom);
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node)

Example 64 with XPathExpression

use of javax.xml.xpath.XPathExpression in project bazel by bazelbuild.

the class ResourceUsageAnalyzer method createStubIds.

/**
   * Write stub values for IDs to values.xml to match those available in public.xml.
   */
private void createStubIds(File values, Map<File, String> rewritten, File publicXml) throws IOException, ParserConfigurationException, SAXException {
    if (values.exists()) {
        String xml = rewritten.get(values);
        if (xml == null) {
            xml = Files.toString(values, UTF_8);
        }
        List<String> stubbed = Lists.newArrayList();
        Document document = XmlUtils.parseDocument(xml, true);
        Element root = document.getDocumentElement();
        for (Resource resource : model.getResources()) {
            boolean inPublicXml = resource.declarations != null && resource.declarations.contains(publicXml);
            NodeList existing = null;
            try {
                XPathExpression expr = XPathFactory.newInstance().newXPath().compile(String.format("//item[@type=\"id\"][@name=\"%s\"]", resource.name));
                existing = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
            } catch (XPathException e) {
            // Failed to retrieve any existing declarations for resource.
            }
            if (resource.type == ResourceType.ID && inPublicXml && (existing == null || existing.getLength() == 0)) {
                Element item = document.createElement(TAG_ITEM);
                item.setAttribute(ATTR_TYPE, resource.type.getName());
                item.setAttribute(ATTR_NAME, resource.name);
                root.appendChild(item);
                stubbed.add(resource.getUrl());
            }
        }
        logger.fine("Created " + stubbed.size() + " stub IDs for:\n  " + Joiner.on(", ").join(stubbed));
        String formatted = XmlPrettyPrinter.prettyPrint(document, xml.endsWith("\n"));
        rewritten.put(values, formatted);
    }
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) XPathException(javax.xml.xpath.XPathException) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Resource(com.android.tools.lint.checks.ResourceUsageModel.Resource) Document(org.w3c.dom.Document)

Example 65 with XPathExpression

use of javax.xml.xpath.XPathExpression in project buck by facebook.

the class SchemeGeneratorTest method launchActionShouldContainRemoteRunnableWhenProvided.

@Test
public void launchActionShouldContainRemoteRunnableWhenProvided() 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);
    Path pbxprojectPath = Paths.get("foo/Foo.xcodeproj/project.pbxproj");
    targetToProjectPathMapBuilder.put(rootTarget, pbxprojectPath);
    SchemeGenerator schemeGenerator = new SchemeGenerator(projectFilesystem, Optional.of(rootTarget), ImmutableSet.of(rootTarget), ImmutableSet.of(), ImmutableSet.of(), "TestScheme", Paths.get("_gen/Foo.xcworkspace/scshareddata/xcshemes"), false, /* primaryTargetIsBuildWithBuck */
    false, /* parallelizeBuild */
    Optional.empty(), /* runnablePath */
    Optional.of("/RemoteApp"), /* remoteRunnablePath */
    SchemeActionType.DEFAULT_CONFIG_NAMES, targetToProjectPathMapBuilder.build(), XCScheme.LaunchAction.LaunchStyle.AUTO);
    Path schemePath = schemeGenerator.writeScheme();
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document scheme = dBuilder.parse(projectFilesystem.newFileInputStream(schemePath));
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath remoteRunnableLaunchActionXPath = xpathFactory.newXPath();
    XPathExpression remoteRunnableLaunchActionExpr = remoteRunnableLaunchActionXPath.compile("//LaunchAction/RemoteRunnable");
    NodeList remoteRunnables = (NodeList) remoteRunnableLaunchActionExpr.evaluate(scheme, XPathConstants.NODESET);
    assertThat(remoteRunnables.getLength(), equalTo(1));
    Node remoteRunnable = remoteRunnables.item(0);
    assertThat(remoteRunnable.getAttributes().getNamedItem("runnableDebuggingMode").getNodeValue(), equalTo("2"));
    assertThat(remoteRunnable.getAttributes().getNamedItem("BundleIdentifier").getNodeValue(), equalTo("com.apple.springboard"));
    assertThat(remoteRunnable.getAttributes().getNamedItem("RemotePath").getNodeValue(), equalTo("/RemoteApp"));
    XPath buildXpath = xpathFactory.newXPath();
    XPathExpression buildExpr = buildXpath.compile("//LaunchAction//BuildableReference/@BlueprintIdentifier");
    NodeList buildNodes = (NodeList) buildExpr.evaluate(scheme, XPathConstants.NODESET);
    // Make sure both copies of the BuildableReference are present.
    assertThat(buildNodes.getLength(), equalTo(2));
    assertThat(buildNodes.item(0).getNodeValue(), equalTo("rootGID"));
    assertThat(buildNodes.item(1).getNodeValue(), equalTo("rootGID"));
}
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) Node(org.w3c.dom.Node) 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

XPathExpression (javax.xml.xpath.XPathExpression)98 XPath (javax.xml.xpath.XPath)69 NodeList (org.w3c.dom.NodeList)56 Document (org.w3c.dom.Document)48 XPathExpressionException (javax.xml.xpath.XPathExpressionException)40 XPathFactory (javax.xml.xpath.XPathFactory)40 Node (org.w3c.dom.Node)38 DocumentBuilder (javax.xml.parsers.DocumentBuilder)24 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)19 Test (org.junit.Test)15 ArrayList (java.util.ArrayList)13 HashMap (java.util.HashMap)13 Element (org.w3c.dom.Element)12 PBXNativeTarget (com.facebook.buck.apple.xcode.xcodeproj.PBXNativeTarget)11 PBXTarget (com.facebook.buck.apple.xcode.xcodeproj.PBXTarget)11 ImmutableMap (com.google.common.collect.ImmutableMap)11 IOException (java.io.IOException)11 Path (java.nio.file.Path)11 PBXFileReference (com.facebook.buck.apple.xcode.xcodeproj.PBXFileReference)10 InputSource (org.xml.sax.InputSource)9