Java Code Examples for javax.xml.xpath.XPathFactory#newXPath()

The following examples show how to use javax.xml.xpath.XPathFactory#newXPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JFXProjectUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static boolean isMavenFXProject(@NonNull final Project prj) {
    if (isMavenProject(prj)) {
        try {
            FileObject pomXml = prj.getProjectDirectory().getFileObject("pom.xml"); //NOI18N
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(FileUtil.toFile(pomXml));
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression exprJfxrt = xpath.compile("//bootclasspath[contains(text(),'jfxrt')]"); //NOI18N
            XPathExpression exprFxPackager = xpath.compile("//executable[contains(text(),'javafxpackager')]"); //NOI18N
            XPathExpression exprPackager = xpath.compile("//executable[contains(text(),'javapackager')]"); //NOI18N
            boolean jfxrt = (Boolean) exprJfxrt.evaluate(doc, XPathConstants.BOOLEAN);
            boolean packager = (Boolean) exprPackager.evaluate(doc, XPathConstants.BOOLEAN);
            boolean fxPackager = (Boolean) exprFxPackager.evaluate(doc, XPathConstants.BOOLEAN);
            return jfxrt && (packager || fxPackager);
        } catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException ex) {
            LOGGER.log(Level.INFO, "Error while parsing pom.xml.", ex);  //NOI18N
            return false;
        }
    }
    return false;
}
 
Example 2
Source File: ExistRunnerApp.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
private String getEvaluationResult(String response) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(response)));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/result/value/text()");
    String textValue = expr.evaluate(doc);
    if (!"".equals(textValue)) return textValue;
    expr = xpath.compile("/result/text()");
    String resultingXmlAsText = expr.evaluate(doc);
    if (!"".equals(resultingXmlAsText.trim())) return resultingXmlAsText;
    expr = xpath.compile("/result/child::*");
    Element node = (Element) expr.evaluate(doc, NODE);
    if (node != null) {
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            String nodeName = attribute.getNodeName();
            String nodeValue = attribute.getNodeValue();
            if (XMLNS.equals(nodeName) && SERIALIZED_NAMESPACE.equals(nodeValue)) {
                node.removeAttribute(XMLNS);
            }
        }
        return prettyPrint(node);
    } else {
        return response;
    }
}
 
Example 3
Source File: XPathExFuncTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
void evaluate(boolean enableExt) throws XPathFactoryConfigurationException, XPathExpressionException {
    Document document = getDocument();

    XPathFactory xPathFactory = XPathFactory.newInstance();
    /**
     * Use of the extension function 'http://exslt.org/strings:tokenize' is
     * not allowed when the secure processing feature is set to true.
     * Attempt to use the new property to enable extension function
     */
    if (enableExt) {
        boolean isExtensionSupported = enableExtensionFunction(xPathFactory);
    }

    xPathFactory.setXPathFunctionResolver(new MyXPathFunctionResolver());
    if (System.getSecurityManager() == null) {
        xPathFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
    }

    XPath xPath = xPathFactory.newXPath();
    xPath.setNamespaceContext(new MyNamespaceContext());

    String xPathResult = xPath.evaluate(XPATH_EXPRESSION, document);
    System.out.println(
            "XPath result (enableExtensionFunction == " + enableExt + ") = \""
            + xPathResult
            + "\"");
}
 
Example 4
Source File: XMLEditor.java    From MusicPlayer with MIT License 5 votes vote down vote up
public static void deleteSongFromPlaylist(int selectedPlayListId, int selectedSongId) {
       try {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(Resources.JAR + "library.xml");
		
           XPathFactory xPathfactory = XPathFactory.newInstance();
           XPath xpath = xPathfactory.newXPath();
           
           // Finds the node with the song id for the selected song in the selected play list for removal.
           String query = "/library/playlists/playlist[@id='" + selectedPlayListId + "']/songId[text() = '" + selectedSongId + "']";
           XPathExpression expr = xpath.compile(query);
           Node deleteSongNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
           
           // Removes the node corresponding to the selected song.
           deleteSongNode.getParentNode().removeChild(deleteSongNode);
                   
           TransformerFactory transformerFactory = TransformerFactory.newInstance();
           Transformer transformer = transformerFactory.newTransformer();
           transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
           transformer.setOutputProperty(OutputKeys.INDENT, "yes");
           DOMSource source = new DOMSource(doc);
           File xmlFile = new File(Resources.JAR + "library.xml");
           StreamResult result = new StreamResult(xmlFile);
           transformer.transform(source, result);
           
	} catch (Exception ex) {
		ex.printStackTrace();
	}
}
 
Example 5
Source File: XmlRowAttribute.java    From link-move with Apache License 2.0 5 votes vote down vote up
public XmlRowAttribute(RowAttribute attribute, XPathFactory xPathFactory, NamespaceContext namespaceContext) {
    this.attribute = attribute;
    try {
        XPath xPath = xPathFactory.newXPath();
        if (namespaceContext != null) {
            xPath.setNamespaceContext(namespaceContext);
        }
        this.sourceExpression = xPath.compile(attribute.getSourceName());
    } catch (XPathExpressionException e) {
        throw new LmRuntimeException("Invalid xPath expression: " + attribute.getSourceName(), e);
    }
}
 
Example 6
Source File: MCRXMLFunctions.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * The method return a org.w3c.dom.NodeList as subpath of the doc input
 * NodeList selected by a path as String.
 *
 * @param doc
 *            the input org.w3c.dom.Nodelist
 * @param path
 *            the path of doc as String
 * @return a subpath of doc selected by path as org.w3c.dom.NodeList
 */
public static NodeList getTreeByPath(NodeList doc, String path) {
    NodeList n = null;
    DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
    try {
        // build path selection
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(path);
        // select part
        Document document = documentBuilder.newDocument();
        if (doc.item(0).getNodeName().equals("#document")) {
            // LOGGER.debug("NodeList is a document.");
            Node child = doc.item(0).getFirstChild();
            if (child != null) {
                Node node = doc.item(0).getFirstChild();
                Node imp = document.importNode(node, true);
                document.appendChild(imp);
            } else {
                document.appendChild(doc.item(0));
            }
        }
        n = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    } catch (Exception e) {
        LOGGER.error("Error while getting tree by path {}", path, e);
    } finally {
        MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
    }
    return n;
}
 
Example 7
Source File: CFDFactory.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
protected static String getVersion(byte[] data) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(data));
    XPathFactory xfactory = XPathFactory.newInstance();
    XPath xpath = xfactory.newXPath();
    String v = (String) xpath.evaluate("/Comprobante/@version", doc);
    if (v.equals("")) {
        return (String) xpath.evaluate("/Comprobante/@Version", doc);
    } else {
        return v;
    }
}
 
Example 8
Source File: KetLogicImpl.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<ResultInfo> getInfos(Document doc, boolean full, String language, List<String> enckeys) throws IOException {
	try {
		org.w3c.dom.Document xml = getXmlDocument(doc, enckeys);

		XPathFactory xPathfactory = XPathFactory.newInstance();
		XPath xpath = xPathfactory.newXPath();
		XPathExpression expr = xpath.compile("/Record/Body/Patient/Person");

		NodeList nl = (NodeList)expr.evaluate(xml, XPathConstants.NODESET);
		return getStream(nl).map(this::getResultInfo).collect(Collectors.toList());
	} catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
		return new ArrayList<>();
	}
}
 
Example 9
Source File: EpubBook.java    From BookyMcBookface with GNU General Public License v3.0 5 votes vote down vote up
private static Map<String,?> processToc(BufferedReader tocReader) {
    Map<String,Object> bookdat = new LinkedHashMap<>();

    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    XPathFactory factory = XPathFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = dfactory.newDocumentBuilder();

        tocReader.mark(4);
        if ('\ufeff' != tocReader.read()) tocReader.reset(); // not the BOM marker

        Document doc = builder.parse(new InputSource(tocReader));

        XPath tocPath = factory.newXPath();
        tocPath.setNamespaceContext(tocnsc);

        Node nav = (Node)tocPath.evaluate("/ncx/navMap", doc, XPathConstants.NODE);

        int total = readNavPoint(nav, tocPath, bookdat, 0);
        bookdat.put(TOCCOUNT, total);

    } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
        Log.e("BMBF", "Error parsing xml " + e.getMessage(), e);
    }
    return bookdat;
}
 
Example 10
Source File: XMLUtil.java    From sagacity-sqltoy with Apache License 2.0 5 votes vote down vote up
/**
 * @todo 获取qName对应的内容
 * @param xmlFile
 * @param xmlQuery
 * @param qName
 * @return
 * @throws Exception
 */
public static Object getXPathContent(File xmlFile, String xmlQuery, QName qName) throws Exception {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(true);
	DocumentBuilder builder = factory.newDocumentBuilder();
	Document doc = builder.parse(xmlFile);
	XPathFactory pathFactory = XPathFactory.newInstance();
	XPath xpath = pathFactory.newXPath();
	XPathExpression pathExpression = xpath.compile(xmlQuery);
	return pathExpression.evaluate(doc, qName);
}
 
Example 11
Source File: XMLMergeUtil.java    From MeituanLintDemo with Apache License 2.0 5 votes vote down vote up
public static Document merge(String expression,
                              InputStream... inputStreams) throws Exception {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();
    XPathExpression compiledExpression = xpath
            .compile(expression);
    return merge(compiledExpression, inputStreams);
}
 
Example 12
Source File: GradleBuild.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private String evaluateExpression(String expression) {
	try {
		XPathFactory xPathFactory = XPathFactory.newInstance();
		XPath xpath = xPathFactory.newXPath();
		XPathExpression expr = xpath.compile(expression);
		String version = expr.evaluate(new InputSource(new FileReader("pom.xml")));
		return version;
	}
	catch (Exception ex) {
		throw new IllegalStateException("Failed to evaluate expression", ex);
	}
}
 
Example 13
Source File: XMLUtil.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
public static NodeList evaluateExpressionForItem(Object item, String expression) throws XPathExpressionException {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    return (NodeList) xpath.compile(expression).evaluate(item, XPathConstants.NODESET);
}
 
Example 14
Source File: PolicyBasedWSS4JInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Check SignedParts, EncryptedParts, SignedElements, EncryptedElements, RequiredParts, etc.
 */
private boolean checkSignedEncryptedCoverage(
    AssertionInfoMap aim,
    SoapMessage msg,
    Element soapHeader,
    Element soapBody,
    Collection<WSDataRef> signed, 
    Collection<WSDataRef> encrypted
) throws SOAPException {
    CryptoCoverageUtil.reconcileEncryptedSignedRefs(signed, encrypted);
    //
    // SIGNED_PARTS and ENCRYPTED_PARTS only apply to non-Transport bindings
    //
    boolean check = true;
    if (!isTransportBinding(aim)) {
        check &= assertTokens(
            aim, SP12Constants.SIGNED_PARTS, signed, msg, soapHeader, soapBody, CoverageType.SIGNED
        );
        check &= assertTokens(
            aim, SP12Constants.ENCRYPTED_PARTS, encrypted, msg, soapHeader, soapBody, 
            CoverageType.ENCRYPTED
        );
    }
    Element soapEnvelope = soapHeader.getOwnerDocument().getDocumentElement();
    if (containsXPathPolicy(aim)) {
        // XPathFactory and XPath are not thread-safe so we must recreate them
        // each request.
        final XPathFactory factory = XPathFactory.newInstance();
        final XPath xpath = factory.newXPath();
        
        check &= assertXPathTokens(aim, SP12Constants.SIGNED_ELEMENTS, signed, soapEnvelope,
                CoverageType.SIGNED, CoverageScope.ELEMENT, xpath);
        check &= assertXPathTokens(aim, SP12Constants.ENCRYPTED_ELEMENTS, encrypted, soapEnvelope,
                CoverageType.ENCRYPTED, CoverageScope.ELEMENT, xpath);
        check &= assertXPathTokens(aim, SP12Constants.CONTENT_ENCRYPTED_ELEMENTS, encrypted, 
                soapEnvelope, CoverageType.ENCRYPTED, CoverageScope.CONTENT, xpath);
    }
    
    check &= assertHeadersExists(aim, msg, soapHeader);
    return check;
}
 
Example 15
Source File: SchemeGeneratorTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void prePostActionsSerializedWithRootBuildable() throws Exception {
  ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();

  PBXTarget rootTarget =
      new PBXNativeTarget("rootRule", AbstractPBXObjectFactory.DefaultFactory());
  rootTarget.setGlobalID("rootGID");
  rootTarget.setProductReference(
      new PBXFileReference(
          "root.a", "root.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
  rootTarget.setProductType(ProductTypes.STATIC_LIBRARY);

  Path pbxprojectPath = Paths.get("foo/Foo.xcodeproj/project.pbxproj");
  targetToProjectPathMapBuilder.put(rootTarget, pbxprojectPath);

  ImmutableMap<SchemeActionType, ImmutableMap<XCScheme.AdditionalActions, ImmutableList<String>>>
      schemeActions =
          ImmutableMap.of(
              SchemeActionType.LAUNCH,
              ImmutableMap.of(
                  XCScheme.AdditionalActions.PRE_SCHEME_ACTIONS,
                  ImmutableList.of("echo takeoff")));

  SchemeGenerator schemeGenerator =
      new SchemeGenerator(
          projectFilesystem,
          Optional.of(rootTarget),
          ImmutableSet.of(rootTarget),
          ImmutableSet.of(),
          ImmutableSet.of(),
          "TestScheme",
          Paths.get("_gen/Foo.xcworkspace/scshareddata/xcshemes"),
          false /* parallelizeBuild */,
          Optional.empty() /* wasCreatedForAppExtension */,
          Optional.empty() /* runnablePath */,
          Optional.empty() /* remoteRunnablePath */,
          SchemeActionType.DEFAULT_CONFIG_NAMES,
          targetToProjectPathMapBuilder.build(),
          Optional.empty(),
          Optional.empty(),
          Optional.of(schemeActions),
          XCScheme.LaunchAction.LaunchStyle.AUTO,
          Optional.empty(), /* watchAdapter */
          Optional.empty() /* notificationPayloadFile */);

  Path schemePath = schemeGenerator.writeScheme();

  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document scheme = dBuilder.parse(projectFilesystem.newFileInputStream(schemePath));

  XPathFactory xpathFactory = XPathFactory.newInstance();

  XPath preLaunchActionXPath = xpathFactory.newXPath();
  XPathExpression preLaunchActionExpr = preLaunchActionXPath.compile("//LaunchAction/PreActions");
  NodeList preActions = (NodeList) preLaunchActionExpr.evaluate(scheme, XPathConstants.NODESET);

  assertThat(preActions.getLength(), equalTo(1));

  Node executionAction = preActions.item(0).getFirstChild();
  assertThat(
      executionAction.getAttributes().getNamedItem("ActionType").getNodeValue(),
      equalTo("Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction"));

  Node actionContent = executionAction.getFirstChild();
  assertThat(
      actionContent.getAttributes().getNamedItem("title").getNodeValue(), equalTo("Run Script"));
  assertThat(
      actionContent.getAttributes().getNamedItem("scriptText").getNodeValue(),
      equalTo("echo takeoff"));
  assertThat(
      actionContent.getAttributes().getNamedItem("shellToInvoke").getNodeValue(),
      equalTo("/bin/bash"));

  XPath buildXpath = xpathFactory.newXPath();
  XPathExpression buildableExpr =
      buildXpath.compile(
          "//LaunchAction//PreActions//ExecutionAction//EnvironmentBuildable//BuildableReference/@BlueprintIdentifier");
  NodeList buildableNodes = (NodeList) buildableExpr.evaluate(scheme, XPathConstants.NODESET);

  // Make sure both copies of the BuildableReference are present.
  assertThat(buildableNodes.getLength(), equalTo(1));
  assertThat(buildableNodes.item(0).getNodeValue(), equalTo("rootGID"));
}
 
Example 16
Source File: AbstractPolicySecurityTest.java    From steady with Apache License 2.0 4 votes vote down vote up
protected void verifySignatureAlgorithms(Document signedDoc, AssertionInfoMap aim) throws Exception { 
    final AssertionInfo assertInfo = aim.get(SP12Constants.ASYMMETRIC_BINDING).iterator().next();
    assertNotNull(assertInfo);
    
    final AsymmetricBinding binding = (AsymmetricBinding) assertInfo.getAssertion();
    final String expectedSignatureMethod = binding.getAlgorithmSuite().getAsymmetricSignature();
    final String expectedDigestAlgorithm = binding.getAlgorithmSuite().getDigest();
    final String expectedCanonAlgorithm  = binding.getAlgorithmSuite().getInclusiveC14n();
        
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    final NamespaceContext nsContext = this.getNamespaceContext();
    xpath.setNamespaceContext(nsContext);
    
    // Signature Algorithm
    final XPathExpression sigAlgoExpr = 
        xpath.compile("/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo" 
                          + "/ds:SignatureMethod/@Algorithm");
    
    final String sigMethod =  (String) sigAlgoExpr.evaluate(signedDoc, XPathConstants.STRING);
    assertEquals(expectedSignatureMethod, sigMethod);
    
    // Digest Method Algorithm
    final XPathExpression digestAlgoExpr = xpath.compile(
        "/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestMethod");
    
    final NodeList digestMethodNodes = 
        (NodeList) digestAlgoExpr.evaluate(signedDoc, XPathConstants.NODESET);
    
    for (int i = 0; i < digestMethodNodes.getLength(); i++) {
        Node node = (Node)digestMethodNodes.item(i);
        String digestAlgorithm = node.getAttributes().getNamedItem("Algorithm").getNodeValue();
        assertEquals(expectedDigestAlgorithm, digestAlgorithm);
    }
    
    // Canonicalization Algorithm
    final XPathExpression canonAlgoExpr =
        xpath.compile("/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo" 
                          + "/ds:CanonicalizationMethod/@Algorithm");
    final String canonMethod =  (String) canonAlgoExpr.evaluate(signedDoc, XPathConstants.STRING);
    assertEquals(expectedCanonAlgorithm, canonMethod);
}
 
Example 17
Source File: SchemeGeneratorTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void schemeWithMultipleTargetsBuildsInCorrectOrder() throws Exception {
  ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();

  PBXTarget rootTarget =
      new PBXNativeTarget("rootRule", AbstractPBXObjectFactory.DefaultFactory());
  rootTarget.setGlobalID("rootGID");
  rootTarget.setProductReference(
      new PBXFileReference(
          "root.a", "root.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
  rootTarget.setProductType(ProductTypes.STATIC_LIBRARY);

  PBXTarget leftTarget =
      new PBXNativeTarget("leftRule", AbstractPBXObjectFactory.DefaultFactory());
  leftTarget.setGlobalID("leftGID");
  leftTarget.setProductReference(
      new PBXFileReference(
          "left.a", "left.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
  leftTarget.setProductType(ProductTypes.STATIC_LIBRARY);

  PBXTarget rightTarget =
      new PBXNativeTarget("rightRule", AbstractPBXObjectFactory.DefaultFactory());
  rightTarget.setGlobalID("rightGID");
  rightTarget.setProductReference(
      new PBXFileReference(
          "right.a", "right.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
  rightTarget.setProductType(ProductTypes.STATIC_LIBRARY);

  PBXTarget childTarget =
      new PBXNativeTarget("childRule", AbstractPBXObjectFactory.DefaultFactory());
  childTarget.setGlobalID("childGID");
  childTarget.setProductReference(
      new PBXFileReference(
          "child.a", "child.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
  childTarget.setProductType(ProductTypes.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 /* parallelizeBuild */,
          Optional.empty() /* wasCreatedForAppExtension */,
          Optional.empty() /* runnablePath */,
          Optional.empty() /* remoteRunnablePath */,
          SchemeActionType.DEFAULT_CONFIG_NAMES,
          targetToProjectPathMapBuilder.build(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          XCScheme.LaunchAction.LaunchStyle.AUTO,
          Optional.empty(), /* watchAdapter */
          Optional.empty() /* notificationPayloadFile */);

  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 = new ArrayList<>();
  for (int i = 0; i < nodes.getLength(); i++) {
    actualOrdering.add(nodes.item(i).getNodeValue());
  }
  assertThat(actualOrdering, equalTo(expectedOrdering));
}
 
Example 18
Source File: SchemeGeneratorTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void launchActionShouldContainRemoteRunnableWhenProvided() throws Exception {
  ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();

  PBXTarget rootTarget =
      new PBXNativeTarget("rootRule", AbstractPBXObjectFactory.DefaultFactory());
  rootTarget.setGlobalID("rootGID");
  rootTarget.setProductReference(
      new PBXFileReference(
          "root.a", "root.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
  rootTarget.setProductType(ProductTypes.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 /* parallelizeBuild */,
          Optional.empty() /* wasCreatedForAppExtension */,
          Optional.empty() /* runnablePath */,
          Optional.of("/RemoteApp") /* remoteRunnablePath */,
          SchemeActionType.DEFAULT_CONFIG_NAMES,
          targetToProjectPathMapBuilder.build(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          XCScheme.LaunchAction.LaunchStyle.AUTO,
          Optional.empty(), /* watchAdapter */
          Optional.empty() /* payloadNotificationFile */);

  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"));
}
 
Example 19
Source File: SchemeGeneratorTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void expandVariablesBasedOnSetIfPresent() throws Exception {
  ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();

  PBXTarget rootTarget =
    new PBXNativeTarget("rootRule", AbstractPBXObjectFactory.DefaultFactory());
  rootTarget.setGlobalID("rootGID");
  rootTarget.setProductReference(
    new PBXFileReference(
      "root.a", "root.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
  rootTarget.setProductType(ProductTypes.STATIC_LIBRARY);

  Path pbxprojectPath = Paths.get("foo/Foo.xcodeproj/project.pbxproj");
  targetToProjectPathMapBuilder.put(rootTarget, pbxprojectPath);

  ImmutableMap<SchemeActionType, ImmutableMap<String, String>> environmentVariables =
    ImmutableMap.of(SchemeActionType.TEST, ImmutableMap.of("ENV_VARIABLE", "IS_SET"));
  ImmutableMap<SchemeActionType, PBXTarget> expandVariablesBasedOn =
    ImmutableMap.of(SchemeActionType.TEST, rootTarget);

  SchemeGenerator schemeGenerator =
    new SchemeGenerator(
      projectFilesystem,
      Optional.of(rootTarget),
      ImmutableSet.of(rootTarget),
      ImmutableSet.of(),
      ImmutableSet.of(),
      "TestScheme",
      Paths.get("_gen/Foo.xcworkspace/scshareddata/xcshemes"),
      true /* parallelizeBuild */,
      Optional.empty() /* wasCreatedForAppExtension */,
      Optional.empty() /* runnablePath */,
      Optional.empty() /* remoteRunnablePath */,
      SchemeActionType.DEFAULT_CONFIG_NAMES,
      targetToProjectPathMapBuilder.build(),
      Optional.of(environmentVariables),
      Optional.of(expandVariablesBasedOn),
      Optional.empty(),
      XCScheme.LaunchAction.LaunchStyle.AUTO,
      Optional.empty(), /* watchAdapter */
      Optional.empty() /* notificationPayloadFile */);

  Path schemePath = schemeGenerator.writeScheme();

  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document scheme = dBuilder.parse(projectFilesystem.newFileInputStream(schemePath));

  XPathFactory xpathFactory = XPathFactory.newInstance();
  XPath buildActionXpath = xpathFactory.newXPath();
  XPathExpression buildActionExpr =
    buildActionXpath.compile("//TestAction/MacroExpansion/BuildableReference");
  NodeList referncesVariableList = (NodeList) buildActionExpr.evaluate(scheme, XPathConstants.NODESET);

  assertThat(referncesVariableList.getLength(), is(1));
  Node reference = referncesVariableList.item(0);
  assertThat(reference.getAttributes().getNamedItem("BuildableIdentifier").getNodeValue(), equalTo("primary"));
  assertThat(reference.getAttributes().getNamedItem("BlueprintIdentifier").getNodeValue(), equalTo("rootGID"));
  assertThat(reference.getAttributes().getNamedItem("BuildableName").getNodeValue(), equalTo("root.a"));
  assertThat(reference.getAttributes().getNamedItem("BlueprintName").getNodeValue(), equalTo("rootRule"));
  assertThat(reference.getAttributes().getNamedItem("ReferencedContainer").getNodeValue(), equalTo("container:../../../foo/Foo.xcodeproj/project.pbxproj"));
}
 
Example 20
Source File: XMLConverter.java    From development with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the node list in the given document at the specified XPath.
 * 
 * @param node
 *            The document to be checked.
 * @param xpathString
 *            The xpath to look at.
 * @return The node list at the given XPath.
 * @throws XPathExpressionException
 */
public static NodeList getNodeListByXPath(Node node, String xpathString)
        throws XPathExpressionException {
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new XmlNamespaceResolver(
            getOwningDocument(node)));
    final XPathExpression expr = xpath.compile(xpathString);
    return (NodeList) expr.evaluate(node, XPathConstants.NODESET);
}