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

The following examples show how to use javax.xml.xpath.XPathFactory#newInstance() . 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: TrpXPathProcessor.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
public TrpXPathProcessor(final String docBuilderFactoryImpl, final String xPathFactoryImpl) 
		throws XPathFactoryConfigurationException, ParserConfigurationException {
	if(docBuilderFactoryImpl == null || xPathFactoryImpl == null) {
		throw new IllegalArgumentException("Arguments must not be null!");
	}
	classLoader = this.getClass().getClassLoader();
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(
			docBuilderFactoryImpl, 
			classLoader);
	builder = factory.newDocumentBuilder();
	xPathFactory = XPathFactory.newInstance(
			javax.xml.xpath.XPathFactory.DEFAULT_OBJECT_MODEL_URI, 
			xPathFactoryImpl, 
			classLoader
			);
	xPath = xPathFactory.newXPath();
}
 
Example 2
Source File: XmlUtilities.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Get values matching passed XPath expression
 * @param node
 * @param expression XPath expression
 * @return matching values
 * @throws Exception
 */
private static String[] getByXpath( Node node, String expression ) throws Exception {

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression xPathExpression = xPath.compile(expression);

    NodeList nlist = (NodeList) xPathExpression.evaluate(node, XPathConstants.NODESET);

    int nodeListSize = nlist.getLength();
    List<String> values = new ArrayList<String>(nodeListSize);
    for (int index = 0; index < nlist.getLength(); index++) {
        Node aNode = nlist.item(index);
        values.add(aNode.getTextContent());
    }
    return values.toArray(new String[values.size()]);
}
 
Example 3
Source File: ReadXml.java    From opentest with MIT License 6 votes vote down vote up
private List<Node> executeXPath(Node rootNode, String xpathExpression) {
    try {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile(xpathExpression);
        Object nodeObj = expr.evaluate(rootNode, XPathConstants.NODESET);
        List<Node> results = new ArrayList<>();
        if (nodeObj instanceof Node) {
            results.add((Node) nodeObj);
        } else if (nodeObj instanceof NodeList) {
            NodeList nodeList = (NodeList) nodeObj;
            int nodeCount = nodeList.getLength();
            for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) {
                Node resultItem = nodeList.item(nodeIndex);
                results.add(resultItem);
            }
        }
        return results;
    } catch (Exception ex) {
        throw new RuntimeException(String.format(
                "There was an error executing XPath expression %s on node %s",
                xpathExpression,
                rootNode.getLocalName()), ex);
    }
}
 
Example 4
Source File: WebPodsDataSourceConfiguration.java    From diirt with MIT License 6 votes vote down vote up
@Override
public DataSourceConfiguration<WebPodsDataSource> read(InputStream input) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(input);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xPath = xpathFactory.newXPath();

        String ver = xPath.evaluate("/wp/@version", document);
        if (!ver.equals("1")) {
            throw new IllegalArgumentException("Unsupported version " + ver);
        }

        String socketLocationString = xPath.evaluate("/wp/connection/@socketLocation", document);
        socketLocation = URI.create(socketLocationString);
    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
        Logger.getLogger(WebPodsDataSourceConfiguration.class.getName()).log(Level.FINEST, "Couldn't load wp configuration", ex);
        throw new IllegalArgumentException("Couldn't load wp configuration", ex);
    }
    return this;
}
 
Example 5
Source File: MsgNgap.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void decode(byte[] data) throws Exception {
    super.decode(data);

    //Decode the NAS part of the binary message
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr = xpath.compile("//NAS-PDU");
    NodeList nodes = (NodeList) expr.evaluate(element, XPathConstants.NODESET);

    if(nodes.getLength() > 0) {
        for(int i = 0; i < nodes.getLength(); i++){
            XMLFormatWriter formatWriter = new XMLFormatWriter();
            Element nasPDUElement = (Element) nodes.item(i);

            BitInputStream bitInputStream = new BitInputStream(new ByteArrayInputStream(DatatypeConverter.parseHexBinary(nasPDUElement.getTextContent())));
            getNASTranslator().decode(getRegistryNas(),bitInputStream, formatWriter);

            Element xml = formatWriter.getResultElement();
            //delete the existing child of the node
            while (nasPDUElement.hasChildNodes()){
                nasPDUElement.removeChild(nasPDUElement.getFirstChild());
            }
            //replace the current node by the new Element
            nasPDUElement.appendChild(nasPDUElement.getOwnerDocument().adoptNode(xml));
        }
    }
}
 
Example 6
Source File: Http.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Post the XML document object and return the XML data from the URL.
 */
public Vertex postXMLAuth(String url, String user, String password, Vertex xmlObject, String xpath, Network network) {
	log("POST XML Auth", Level.INFO, url);
	try {
		String data = convertToXML(xmlObject);
		log("POST XML", Level.FINE, data);
		String xml = Utils.httpAuthPOST(url, user, password, "application/xml", data);
		log("XML", Level.FINE, xml);
		InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8"));
		Element element = parseXML(stream);
		if (element == null) {
			return null;
		}
		XPathFactory factory = XPathFactory.newInstance();
		XPath path = factory.newXPath();
		Object node = path.evaluate(xpath, element, XPathConstants.NODE);
		if (node instanceof Element) {
			return convertElement((Element)node, network);
		} else if (node instanceof Attr) {
			return network.createVertex(((Attr)node).getValue());
		}
		return null;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example 7
Source File: CompositeDataSourceConfiguration.java    From diirt with MIT License 5 votes vote down vote up
public CompositeDataSourceConfiguration(InputStream input) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(input);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xPath = xpathFactory.newXPath();

        String ver = xPath.evaluate("/dataSources/@version", document);
        if (!ver.equals("1")) {
            throw new IllegalArgumentException("Unsupported version " + ver);
        }

        String delimiter = xPath.evaluate("/dataSources/compositeDataSource/@delimiter", document);
        if (delimiter != null && !delimiter.isEmpty()) {
            this.delimiter = delimiter;
        }

        String defaultDataSource = xPath.evaluate("/dataSources/compositeDataSource/@defaultDataSource", document);
        if (defaultDataSource != null && !defaultDataSource.isEmpty()) {
            this.defaultDataSource = defaultDataSource;
        }
    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
        Logger.getLogger(CompositeDataSourceConfiguration.class.getName()).log(Level.FINEST, "Couldn't load dataSources configuration", ex);
        throw new IllegalArgumentException("Couldn't load dataSources configuration", ex);
    }
}
 
Example 8
Source File: SAMLMessage.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
/** Get the saml attributes from the saml message which are also in the configured list */
private void buildAttributeMap() {
    // xpath initialization
    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xpath = xFactory.newXPath();
    Set<Attribute> allAttributes = SAMLConfiguration.getInstance().getAvailableAttributes();
    for (Attribute attribute : allAttributes) {
        try {
            XPathExpression expression = xpath.compile(attribute.getxPath());
            Node node = (Node) expression.evaluate(xmlDocument, XPathConstants.NODE);
            if (node != null) { // the attributes that aren't available will be giving null
                // values
                String value;
                if (node instanceof Element) {
                    value = node.getTextContent();
                } else if (node instanceof Attr) {
                    value = ((Attr) node).getValue();
                } else {
                    value = node.getNodeValue();
                }
                if (value != null && !"".equals(value)) {
                    Attribute newAttrib = attribute.createCopy();
                    newAttrib.setValue(value);
                    attributeMap.put(attribute.getName(), newAttrib);
                }
            }
        } catch (XPathExpressionException e) {
            log.warn(attribute.getxPath() + " is not a valid XPath", e);
        }
    }
}
 
Example 9
Source File: CR6333993Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNodeList() {
    int n = 5;
    while (0 != (n--))
        ;
    System.out.println("n=" + n);
    try {
        String testXML = "<root>" + "  <node/>" + "  <node/>" + "  <node/>" + "  <node/>" + "</root>\n";
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        ByteArrayInputStream bis = new ByteArrayInputStream(testXML.getBytes());
        Document testDoc = builder.parse(bis);
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression expr = xpath.compile("/root/node");
        NodeList testNodes = (NodeList) expr.evaluate(testDoc, XPathConstants.NODESET);
        // Node list appears to work correctly
        System.out.println("testNodes.getLength() = " + testNodes.getLength());
        System.out.println("testNodes[0] = " + testNodes.item(0));
        System.out.println("testNodes[0] = " + testNodes.item(0));
        System.out.println("testNodes.getLength() = " + testNodes.getLength());
        // Access past the end of the NodeList correctly returns null
        System.out.println("testNodes[testNodes.getLength()] = " + testNodes.item(testNodes.getLength()));
        // BUG! First access of valid node after accessing past the end
        // incorrectly returns null
        if (testNodes.item(0) == null) {
            System.out.println("testNodes[0] = null");
            Assert.fail("First access of valid node after accessing past the end incorrectly returns null");
        }
        // Subsequent access of valid node correctly returns the node
        System.out.println("testNodes[0] = " + testNodes.item(0));
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
 
Example 10
Source File: JanrainHelper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private NodeList getNodeList(String xpath_expr, Element root) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    try {
        return (NodeList) xpath.evaluate(xpath_expr, root, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        return null;
    }
}
 
Example 11
Source File: ConfigurationProcessor.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * Reads web app deployment descriptor to extract the locale - encoding mappings
 * 
 * @param in
 *           Input stream for DD
 * @throws Exception
 *            If there is a parsing problem
 */
public void processWebDD(InputStream in) throws Exception {

   // set up document
   DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
   fact.setValidating(false);

   final DocumentBuilder builder = fact.newDocumentBuilder();
   builder.setEntityResolver(new EntityResolver() {
      public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException {
         return new InputSource(new StringReader(""));
      }
   });

   final Document document = builder.parse(in);
   final Element root = document.getDocumentElement();

   // Generate xpath queries
   final XPathFactory xpathFactory = XPathFactory.newInstance();
   final XPath xpath = xpathFactory.newXPath();
   final XPathExpression GET_LIST = xpath.compile("//locale-encoding-mapping-list/locale-encoding-mapping");
   final XPathExpression GET_LOC = xpath.compile("locale/text()");
   final XPathExpression GET_ENC = xpath.compile("encoding/text()");

   // get list of locale - encoding mappings and process them
   NodeList nodes = (NodeList) GET_LIST.evaluate(root, XPathConstants.NODESET);

   int mappings = 0;
   for (int jj = 0; jj < nodes.getLength(); jj++) {
      Node node = nodes.item(jj);
      String locstr = (String) GET_LOC.evaluate(node, XPathConstants.STRING);
      String encstr = (String) GET_ENC.evaluate(node, XPathConstants.STRING);
      Locale locale = deriveLocale(locstr);
      pad.addLocaleEncodingMapping(locale, encstr);
      mappings++;
   }
   LOG.debug("done parsing web DD, # mappings: " + mappings);
}
 
Example 12
Source File: XPathParser.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {
   this.validation = validation;
   this.entityResolver = entityResolver;
   this.variables = variables;
//共通构造函数,除了把参数都设置到实例变量里面去以外,还初始化了XPath
   XPathFactory factory = XPathFactory.newInstance();
   this.xpath = factory.newXPath();
 }
 
Example 13
Source File: SoapMultiSignature.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
private void validateIdAttributes(Document doc) throws Exception {
  String idAttribute = new String(idIdentifier.getText());
  XPathFactory xPathfactory = XPathFactory.newInstance();
  XPath xpath = xPathfactory.newXPath();
  XPathExpression expr = xpath.compile("descendant-or-self::*/@" + idAttribute);
  NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
  if(nodeList != null && nodeList.getLength() > 0) {
    for(int j = 0; j < nodeList.getLength(); j++) {
        Attr attr = (Attr)nodeList.item(j);
        ((Element)attr.getOwnerElement()).setIdAttributeNode(attr,true);
    }
  }
}
 
Example 14
Source File: StaxQueryXML.java    From maven-framework-project with MIT License 5 votes vote down vote up
public void query() throws ParserConfigurationException, SAXException,IOException, XPathExpressionException {
	// Standard of reading a XML file
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(true);
	DocumentBuilder builder;
	Document doc = null;
	XPathExpression expr = null;
	builder = factory.newDocumentBuilder();
	doc = builder.parse(ClassLoader.getSystemResourceAsStream("person.xml"));

	// Create a XPathFactory
	XPathFactory xFactory = XPathFactory.newInstance();

	// Create a XPath object
	XPath xpath = xFactory.newXPath();

	// Compile the XPath expression
	expr = xpath.compile("//person[firstname='Lars']/lastname/text()");
	// Run the query and get a nodeset
	Object result = expr.evaluate(doc, XPathConstants.NODESET);

	// Cast the result to a DOM NodeList
	NodeList nodes = (NodeList) result;
	for (int i = 0; i < nodes.getLength(); i++) {
		System.out.println(nodes.item(i).getNodeValue());
	}

	// New XPath expression to get the number of people with name lars
	expr = xpath.compile("count(//person[firstname='Lars'])");
	// Run the query and get the number of nodes
	Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER);
	System.out.println("Number of objects " + number);

	// Do we have more then 2 people with name lars?
	expr = xpath.compile("count(//person[firstname='Lars']) >2");
	// Run the query and get the number of nodes
	Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);
	System.out.println(check);

}
 
Example 15
Source File: DOMAndXPath.java    From citygml4j with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	SimpleDateFormat df = new SimpleDateFormat("[HH:mm:ss] "); 

	System.out.println(df.format(new Date()) + "setting up citygml4j context and CityGML builder");
	CityGMLContext ctx = CityGMLContext.getInstance();
	CityGMLBuilder builder = ctx.createCityGMLBuilder();

	System.out.println(df.format(new Date()) + "creating citygml4j JAXBUnmarshaller and JAXBMarshaller instances");
	JAXBUnmarshaller unmarshaller = builder.createJAXBUnmarshaller();
	JAXBMarshaller marshaller = builder.createJAXBMarshaller();
	marshaller.setModuleContext(new ModuleContext(CityGMLVersion.v2_0_0));
	
	// create DOM model from CityGML document
	System.out.println(df.format(new Date()) + "reading CityGML file LOD2_Building_with_Placeholder_v200.gml as DOM tree");
	DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	docFactory.setNamespaceAware(true);		
	DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	Document document = docBuilder.parse("datasets/LOD2_Building_with_Placeholder_v200.gml");

	// create XPath factory
	System.out.println(df.format(new Date()) + "creating XPath factory");
	XPathFactory xpathFactory = XPathFactory.newInstance();
	XPath xpath = xpathFactory.newXPath();

	// get CityGML namespace context
	CityGMLNamespaceContext nsContext = new CityGMLNamespaceContext();
	nsContext.setPrefixes(CityGMLVersion.v2_0_0);
	xpath.setNamespaceContext(nsContext);

	// first: retrieve building node using XPath
	System.out.println(df.format(new Date()) + "searching for bldg:Building node in DOM tree using an XPath expression");
	Node buildingNode = (Node)xpath.evaluate("//bldg:Building", document, XPathConstants.NODE);

	// unmarshal DOM node to citygml4j
	System.out.println(df.format(new Date()) + "unmarshalling DOM node to citygml4j");
	Building building = (Building)unmarshaller.unmarshal(buildingNode);

	// add gml:id and gml:description to building
	System.out.println(df.format(new Date()) + "processing content using citygml4j");
	building.setId(DefaultGMLIdManager.getInstance().generateUUID());
	StringOrRef description = new StringOrRef();
	description.setValue("processed by citygml4j using DOM and XPath");
	building.setDescription(description);

	// marshal to DOM and put into document
	System.out.println(df.format(new Date()) + "marshalling back to DOM");
	Element newBuildingNode = marshaller.marshalDOMElement(building, document);
	buildingNode.getParentNode().replaceChild(newBuildingNode, buildingNode);
	
	// second: get placeholder using XPath
	System.out.println(df.format(new Date()) + "searching for 'Placeholder' in DOM tree using an XPath expression");
	Node memberNode = (Node)xpath.evaluate("//core:cityObjectMember[comment()='Placeholder']", document, XPathConstants.NODE);

	// create simple citygml4j object to insert into placeholder
	System.out.println(df.format(new Date()) + "inserting CityFurniture instance at placeholder using citygml4j");
	CityFurniture cityFurniture = new CityFurniture();
	cityFurniture.setDescription(description);		
	CityObjectMember member = new CityObjectMember(cityFurniture);

	// marshal to DOM and put into document
	System.out.println(df.format(new Date()) + "marshalling back to DOM");
	Element newMemberNode = marshaller.marshalDOMElement(member, document);
	memberNode.getParentNode().replaceChild(newMemberNode, memberNode);
	
	// write DOM to file
	System.out.println(df.format(new Date()) + "writing DOM tree");
	Files.createDirectories(Paths.get("output"));

	TransformerFactory transFactory = TransformerFactory.newInstance();
	Transformer trans = transFactory.newTransformer();
	DOMSource source = new DOMSource(document);

	try (SAXWriter saxWriter = new SAXWriter(new FileOutputStream("output/LOD2_DOM_result_v200.gml"), "UTF-8")) {
		saxWriter.setIndentString("  ");
		saxWriter.setNamespaceContext(nsContext);
		trans.transform(source, new SAXResult(saxWriter));
	}

	System.out.println(df.format(new Date()) + "CityGML file LOD2_DOM_result_v200.gml written");
	System.out.println(df.format(new Date()) + "sample citygml4j application successfully finished");
}
 
Example 16
Source File: LegacyAbstractAnalyticsFacetTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void beforeClassAbstractAnalysis() {
  xPathFact = XPathFactory.newInstance();
}
 
Example 17
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Check a particular XPath result
 */
private boolean checkXPathResult(
    Element soapEnvelope,
    String xPath,
    Map<String, String> namespaces,
    List<WSSecurityEngineResult> protResults,
    List<WSSecurityEngineResult> tokenResults
) {
    // XPathFactory and XPath are not thread-safe so we must recreate them
    // each request.
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    
    if (namespaces != null) {
        xpath.setNamespaceContext(new MapNamespaceContext(namespaces));
    }
    
    // For each XPath
    for (String xpathString : Arrays.asList(xPath)) {
        // Get the matching nodes
        NodeList list;
        try {
            list = (NodeList)xpath.evaluate(
                    xpathString, 
                    soapEnvelope,
                    XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            LOG.log(Level.FINE, e.getMessage(), e);
            return false;
        }
        
        // If we found nodes then we need to do the check.
        if (list.getLength() != 0) {
            // For each matching element, check for a ref that
            // covers it.
            for (int x = 0; x < list.getLength(); x++) {
                final Element el = (Element)list.item(x);
                
                if (!checkProtectionResult(el, false, protResults, tokenResults)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example 18
Source File: SchemeGeneratorTest.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Exclude `wasCreatedForAppExtension` when null or false.
 *
 * @throws Exception
 */
@Test
public void excludesWasCreatedForAppExtension() 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);

  ImmutableList<Optional<Boolean>> testValues =
      ImmutableList.of(Optional.empty(), Optional.of(false));

  for (Optional<Boolean> wasCreatedForAppExtension : testValues) {
    SchemeGenerator schemeGenerator =
        new SchemeGenerator(
            projectFilesystem,
            Optional.of(rootTarget),
            ImmutableSet.of(rootTarget),
            ImmutableSet.of(),
            ImmutableSet.of(),
            "TestScheme",
            Paths.get("_gen/Foo.xcworkspace/xcshareddata/xcshemes"),
            true /* parallelizeBuild */,
            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();

    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("//Scheme");
    NodeList schemeElements = (NodeList) buildActionExpr.evaluate(scheme, XPathConstants.NODESET);

    assertThat(schemeElements.getLength(), is(1));
    Node schemeNode = schemeElements.item(0);
    assertNull(schemeNode.getAttributes().getNamedItem("wasCreatedForAppExtension"));
  }
}
 
Example 19
Source File: SchemeGeneratorTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void launchActionShouldNotContainRemoteRunnableWhenNotProvided() 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.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();

  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(0));
}
 
Example 20
Source File: XPathFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Test for XPathFactory.newInstance(java.lang.String uri, java.lang.String
 * factoryClassName, java.lang.ClassLoader classLoader) uri is null , should
 * throw NPE
 *
 * @throws XPathFactoryConfigurationException
 */
@Test(expectedExceptions = NullPointerException.class)
public void testNewInstanceWithNullUri() throws XPathFactoryConfigurationException {
    XPathFactory.newInstance(null, XPATH_FACTORY_CLASSNAME, this.getClass().getClassLoader());
}