Example usage for javax.xml.xpath XPathConstants NODESET

List of usage examples for javax.xml.xpath XPathConstants NODESET

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODESET.

Prototype

QName NODESET

To view the source code for javax.xml.xpath XPathConstants NODESET.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:com.rest4j.generator.DocGeneratorTest.java

@Test
public void testPreprocess() throws Exception {
    Document xml = getDocument("doc-generator-graph.xml");
    gen.preprocess(xml);//from  w w  w.ja v a 2s .c  o m
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    xpath.setNamespaceContext(new Generator.APINamespaceContext());

    assertEquals("patch A,patch B,B,patch C,C",
            modelsToString(xpath.compile("//api:endpoint[api:service/@method='patch']/api:body/api:model")
                    .evaluate(xml, XPathConstants.NODESET)));
    assertEquals("C",
            modelsToString(xpath.compile("//api:endpoint[api:service/@method='patch']/api:response/api:model")
                    .evaluate(xml, XPathConstants.NODESET)));
    assertEquals("B,C", modelsToString(xpath.compile("//api:endpoint[api:route='get']/api:response/api:model")
            .evaluate(xml, XPathConstants.NODESET)));
    assertEquals("B,C", modelsToString(xpath.compile("//api:endpoint[api:route='get']/api:response/api:model")
            .evaluate(xml, XPathConstants.NODESET)));
    assertEquals("", modelsToString(xpath.compile("//api:endpoint[api:route='binary']/api:response/api:model")
            .evaluate(xml, XPathConstants.NODESET)));
}

From source file:cz.incad.kramerius.utils.solr.SolrUtils.java

/**
 * Disects pid paths from given parsed solr document
 * @return pid paths/*from   w  w w  .  java  2s . c om*/
 * @throws XPathExpressionException cannot disect pid paths
 */
public static List<String> disectPidPaths(Document parseDocument) throws XPathExpressionException {
    synchronized (parseDocument) {
        List<String> list = new ArrayList<String>();
        NodeList paths = (org.w3c.dom.NodeList) pidPathExpr().evaluate(parseDocument, XPathConstants.NODESET);
        if (paths != null) {
            for (int i = 0, ll = paths.getLength(); i < ll; i++) {
                Node n = paths.item(i);
                String text = n.getTextContent();
                list.add(text.trim());
            }
            return list;
        }
        return new ArrayList<String>();
    }
}

From source file:net.firejack.platform.core.config.meta.parse.XMLStreamDescriptorParser.java

private void uidValidation(String xml)
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);//from   w ww  . ja va  2  s  . co m
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*/@uid");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    Map<String, Integer> uids = new HashMap<String, Integer>();
    for (int i = 0; i < nodes.getLength(); i++) {
        String uid = nodes.item(i).getNodeValue();
        Integer count = uids.get(uid);
        if (count == null) {
            count = 0;
        }
        count++;
        uids.put(uid, count);
    }
    StringBuilder errorMessage = new StringBuilder();
    for (Map.Entry<String, Integer> entry : uids.entrySet()) {
        if (entry.getValue() > 1) {
            errorMessage.append(" [").append(entry.getKey()).append("]");
        }
    }
    if (errorMessage.length() > 0) {
        throw new BusinessFunctionException(
                "UIDs are not unique in package.xml. Check UIDs:" + errorMessage.toString());
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.QueryTests.java

@Test
public void validEqualsQueryContainsExpectedDefect()
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    //Form the equality query

    String query = getQueryBase() + "oslc.where=" + queryProperty
            + URLEncoder.encode("=\"" + queryPropertyValue + "\"", "UTF-8") + "&oslc.select=" + queryProperty;
    String responseBody = runQuery(query, OSLCConstants.CT_XML);
    //Get XML Doc from response
    Document doc = OSLCUtils.createXMLDocFromResponseBody(responseBody);
    NodeList results = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm_v2:ChangeRequest", doc,
            XPathConstants.NODESET);
    if (results == null)
        results = (NodeList) OSLCUtils.getXPath().evaluate("//rdf:Description", doc, XPathConstants.NODESET);
    assertNotNull(results);/*from   w  ww  .  j  a  v a2s . com*/
    assertTrue("Expected query results > 0", results.getLength() > 0);
    //Check that the property elements are equal to the expected value
    checkEqualityProperty(results, queryProperty, queryPropertyValue, doc);
}

From source file:Main.java

/**
 * Gets the node list from the given xml file and the given xpath expression.
 * //from w w w  .ja  va  2  s .c  om
 * @param xml
 *            the xml file as string.
 * @param xpathExpression
 *            the xpath expression as string.
 * @return the node list
 * @throws XPathExpressionException
 *             the x path expression exception
 * @throws ParserConfigurationException
 *             the parser configuration exception
 * @throws SAXException
 *             the sAX exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static NodeList getNodeList(final String xml, final String xpathExpression)
        throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
    final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    final DocumentBuilder builder = domFactory.newDocumentBuilder();
    final Document doc = builder.parse(xml);
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final XPathExpression expr = xpath.compile(xpathExpression);

    final Object result = expr.evaluate(doc, XPathConstants.NODESET);
    final NodeList nodes = (NodeList) result;
    return nodes;
}

From source file:org.jasig.portlet.calendar.service.RoleService.java

/**
 * Do the real work of reading the role list.
 *
 * @return the set of role names./*from  w ww. j  a v  a 2 s  . co  m*/
 */
private Set<String> readRolesFromPortletXml() {
    try {
        URL portletXmlUrl = context.getResource(PORTLET_XML_PATH);
        InputSource is = new InputSource(portletXmlUrl.openStream());

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = builder.parse(is);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression xPathExpression = xpath.compile(ROLES_XPATH);

        NodeList nodeList = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);

        Set<String> roles = new LinkedHashSet<String>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            String role = nodeList.item(i).getNodeValue();
            roles.add(role);
        }

        return roles;

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException("Error reading roles from portlet.xml", e);
    }
}

From source file:io.wcm.testing.mock.osgi.OsgiMetadataUtil.java

public static Set<String> getServiceInterfaces(Document document) {
    Set<String> serviceInterfaces = new HashSet<>();

    if (document != null) {
        try {/*from ww w .ja  v  a2  s.co m*/
            XPath xpath = XPATH_FACTORY.newXPath();
            xpath.setNamespaceContext(NAMESPACE_CONTEXT);
            NodeList nodes = (NodeList) xpath.evaluate(
                    "/components/component[1]/service/provide[@interface!='']", document,
                    XPathConstants.NODESET);
            if (nodes != null) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    String serviceInterface = node.getAttributes().getNamedItem("interface").getNodeValue();
                    if (StringUtils.isNotBlank(serviceInterface)) {
                        serviceInterfaces.add(serviceInterface);
                    }
                }
            }
        } catch (XPathExpressionException ex) {
            throw new RuntimeException("Error evaluating XPath.", ex);
        }
    }

    return serviceInterfaces;
}

From source file:org.trustedanalytics.hadoop.admin.tools.HadoopClientParamsImporter.java

static Optional<Map<String, String>> scanConfigZipArchive(InputStream source)
        throws IOException, XPathExpressionException {

    InputStream zipInputStream = new ZipInputStream(new BufferedInputStream(source));
    ZipEntry zipFileEntry;//from  w w  w  .j  a va  2s.c o  m
    Map<String, String> ret = new HashMap<>();
    while ((zipFileEntry = ((ZipInputStream) zipInputStream).getNextEntry()) != null) {
        if (!zipFileEntry.getName().endsWith("-site.xml")) {
            continue;
        }
        byte[] bytes = IOUtils.toByteArray(zipInputStream);
        InputSource is = new InputSource(new ByteArrayInputStream(bytes));
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate(CONF_PROPERTY_XPATH, is, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node propNode = nodeList.item(i);
            String key = (String) xPath.evaluate("name/text()", propNode, XPathConstants.STRING);
            String value = (String) xPath.evaluate("value/text()", propNode, XPathConstants.STRING);
            ret.put(key, value);
        }
    }
    return Optional.of(ret);
}

From source file:org.alloy.metal.xml.merge.ImportProcessor.java

public List<ResourceInputStream> extract(List<ResourceInputStream> sources) throws MergeException {
    try {/*w ww.  j a  v a2  s  .  c o  m*/
        DynamicResourceIterator resourceList = new DynamicResourceIterator();
        resourceList.addAll(sources);

        while (resourceList.hasNext()) {
            ResourceInputStream myStream = resourceList.nextResource();
            Document doc = builder.parse(myStream);
            NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET);
            int length = nodeList.getLength();
            for (int j = 0; j < length; j++) {
                Element element = (Element) nodeList.item(j);
                Resource resource = loader.getResource(element.getAttribute("resource"));
                ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(),
                        resource.getURL().toString());
                resourceList.addEmbeddedResource(ris);
                element.getParentNode().removeChild(element);
            }
            if (length > 0) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer xmlTransformer = tFactory.newTransformer();
                xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
                xmlTransformer.setOutputProperty(OutputKeys.ENCODING, _String.CHARACTER_ENCODING.toString());
                xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

                DOMSource source = new DOMSource(doc);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));
                StreamResult result = new StreamResult(writer);
                xmlTransformer.transform(source, result);

                byte[] itemArray = baos.toByteArray();

                resourceList.set(resourceList.getPosition() - 1, new ResourceInputStream(
                        new ByteArrayInputStream(itemArray), null, myStream.getNames()));
            } else {
                myStream.reset();
            }
        }

        return resourceList;
    } catch (Exception e) {
        throw new MergeException(e);
    }
}

From source file:com.oracle.tutorial.jdbc.ProductInformationTable.java

public void populateTable(String fileName)
        throws SQLException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    // factory.setNamespaceAware(true);
    factory.setNamespaceAware(true);/* w  w  w. j ava  2s  .c o m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    NodeList nodes = (NodeList) xPath.evaluate("/coffee-product-information/item[coffee = 'Columbian']", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node currentNode = nodes.item(i);
        // Retrieve the description element

        currentNode.normalize();

        if (currentNode == null) {
            System.out.println("Current node is null");
        }

        //      System.out.println(currentNode.getTextContent());

        Node descriptionNode = (Node) xPath.evaluate("description", currentNode, XPathConstants.NODE);

        if (descriptionNode == null) {
            System.out.println("DescriptionNode is null");
        } else {

            System.out.println(descriptionNode.getTextContent());

            NodeList descriptionNodeChildren = descriptionNode.getChildNodes();
            System.out.println("Description node has " + descriptionNodeChildren.getLength() + " child nodes");
            Node descNodeChild = descriptionNode.getFirstChild();
            System.out.println("Only child node type: " + descNodeChild.getNodeType());
        }

        //      System.out.println("Description: " + descriptionNode.getNodeValue());

        // System.out.println(nodes.item(i).getNodeValue());
    }

}