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:org.eclipse.lyo.testsuite.server.oslcv1tests.CreationAndUpdateTests.java

public static Collection<Object[]> getReferencedUrls(String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML + ", " + OSLCConstants.CT_DISC_DESC_XML);

    //If our 'base' is a ServiceDescription, find and add the factory service url
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));
        Node factoryUrl = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:factory/oslc_cm:url", baseDoc,
                XPathConstants.NODE);
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { factoryUrl.getTextContent() });
        return data;
    }/*w  w w  .  ja va  2 s .c o  m*/

    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

    //ArrayList to contain the urls from all of the SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();

    //Get all the ServiceDescriptionDocuments from this ServiceProviderCatalog
    NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:services/@rdf:resource", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < sDescs.getLength(); i++) {
        Collection<Object[]> subCollection = getReferencedUrls(sDescs.item(i).getNodeValue());
        Iterator<Object[]> iter = subCollection.iterator();
        while (iter.hasNext()) {
            data.add(iter.next());
        }
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //simple query services from the eventual service description documents from them as well.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        if (!spcs.item(i).getNodeValue().equals(base)) {
            Collection<Object[]> subCollection = getReferencedUrls(spcs.item(i).getNodeValue());
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:de.ingrid.iplug.dscmapclient.index.producer.PlugDescriptionConfiguredWmsRecordSetProducer.java

/**
 * this private method does all the dirty work, read the file, parse it into
 * a document and find the desired ids, through the xpath expression
 * //from   ww w.ja  v  a 2 s.c  om
 * @param filePath
 * @param expression
 * @return NodeList
 */
private NodeList readXmlFile(String filePath, String expression) {
    XPath xPath = XPathFactory.newInstance().newXPath();
    File fXmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        return (NodeList) xPath.evaluate(expression, doc, XPathConstants.NODESET);
    } catch (ParserConfigurationException e) {
        log.error("Error creating record ids.", e);
        e.printStackTrace();
    } catch (SAXException e) {
        log.error("Error creating record ids.", e);
        e.printStackTrace();
    } catch (IOException e) {
        log.error("Error creating record ids.", e);
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        log.error("Error creating record ids.", e);
        e.printStackTrace();
    }
    return null;

}

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

/**
 * Disect models path from given solr document
 * @param parseDocument Parsed solr document
 * @return model paths// w  w  w . j a va  2s.  co  m
 * @throws XPathExpressionException cannot disect models path
 */
public static List<String> disectModelPaths(Document parseDocument) throws XPathExpressionException {
    synchronized (parseDocument) {
        List<String> list = new ArrayList<String>();
        NodeList pathNodes = (NodeList) modelPathExpr().evaluate(parseDocument, XPathConstants.NODESET);
        if (pathNodes != null) {
            for (int i = 0, ll = pathNodes.getLength(); i < ll; i++) {
                Node n = pathNodes.item(i);
                String text = n.getTextContent();
                list.add(text.trim());
            }
            return list;
        }
        return new ArrayList<String>();
    }
}

From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java

public static Document replaceTokens(Document doc, Policy configTokens)
        throws XPathExpressionException, TransformerConfigurationException {

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(configTokens);
    logger.info("============= to apply the following config tokens ================\n{}", json);

    try {//from   w  w  w. j ava2s . com
        for (int i = 0; i < configTokens.tokens.size(); i++) {

            logger.debug("=============Checking for Xpath Expressions {}  ================\n",
                    configTokens.tokens.get(i).xpath);
            XPathExpression expression = xpath.compile(configTokens.tokens.get(i).xpath);

            NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);

            for (int j = 0; j < nodes.getLength(); j++) {

                if (nodes.item(j).hasChildNodes()) {
                    logger.debug("=============Updated existing value {} to new value {} ================\n",
                            nodes.item(j).getTextContent(), configTokens.tokens.get(i).value);
                    nodes.item(j).setTextContent(configTokens.tokens.get(i).value);
                }
            }

        }

        return doc;
    } catch (XPathExpressionException e) {

        logger.error(String.format(
                "\n\n=============The Xpath Expressions in config.json are incorrect. Please check. ================\n\n%s",
                e.getMessage()), e);
        throw e;
    }

}

From source file:eu.smartfp7.terrier.sensor.ParserUtility.java

public static EdgeNodeSnapShot parseShort(InputStream is) throws Exception {

    DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance();
    xmlfact.setNamespaceAware(true);//w  w  w  . j  ava  2 s  .com
    Document document = xmlfact.newDocumentBuilder().parse(is);

    XPath xpath = XPathFactory.newInstance().newXPath();

    String time = (String) xpath.compile("//crowd/time/text()").evaluate(document, XPathConstants.STRING);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar c = Calendar.getInstance();
    ;
    c.setTime(df.parse(time));

    String density = (String) xpath.compile("//crowd/density/text()").evaluate(document, XPathConstants.STRING);

    NodeList list = (NodeList) xpath.compile("//crowd/colour").evaluate(document, XPathConstants.NODESET);
    double[] colors = new double[list.getLength()];
    for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node colorNode = list.item(i);
        String v = colorNode.getFirstChild().getTextContent();
        colors[i] = new Double(v);
    }

    String activity = (String) xpath.compile("//activity/name/text()").evaluate(document,
            XPathConstants.STRING);

    CrowdReport crowdReport = new CrowdReport(null, new Double(density), 0.0, colors);

    EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(null, null, c, crowdReport);
    snapShot.setText((activity != null ? activity : StringUtils.EMPTY));

    return snapShot;

}

From source file:com.jaeksoft.searchlib.util.XPathParser.java

public final NodeList getNodeList(Node parentNode, String query) throws XPathExpressionException {
    return (NodeList) xPath.evaluate(query, parentNode, XPathConstants.NODESET);
}

From source file:org.joy.config.Configuration.java

private void parseTemplates(Document doc, XPath path) throws XPathExpressionException {
    NodeList templateList = (NodeList) path.evaluate("configuration/templates/template", doc,
            XPathConstants.NODESET);
    if (templateList != null) {
        for (int i = 0; i < templateList.getLength(); i++) {
            parseTemplate(templateList.item(i), path);
        }//  w  ww  .j  a v  a 2s. c  om
    }
}

From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java

public HashMap<String, String> extractValues(Document xml, String path) {
    try {//  w w w .j a v  a2 s  .  c  o  m
        HashMap<String, String> resultMap = new HashMap<String, String>();

        XPathFactory factory = XPathFactory.newInstance();

        XPath xpath = factory.newXPath();
        xpath.setNamespaceContext(namespaceContext);
        XPathExpression expr = xpath.compile(path);

        NodeList list = (NodeList) expr.evaluate(xml, XPathConstants.NODESET);
        if (list != null) {
            for (int i = 0; i < list.getLength(); i++) {
                Node n = list.item(i);
                String content = n.getTextContent();
                if (content != null) {
                    resultMap.put(n.getLocalName(), content);
                }
            }
        }
        return resultMap;
    } catch (Exception e) {
        log.error("Could not parse XML " + " searching for path " + path + ": " + e.getMessage(), e);
        return null;
    }
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.QueryTests.java

public static Collection<Object[]> getReferencedUrls(String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML + ", " + OSLCConstants.CT_DISC_DESC_XML);

    //If our 'base' is a ServiceDescription, find and add the simpleQuery service url
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));
        Node simpleQueryUrl = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:simpleQuery/oslc_cm:url", baseDoc,
                XPathConstants.NODE);
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { simpleQueryUrl.getTextContent() });
        return data;
    }//ww w . j  a  va2  s. c  o m

    String respBody = EntityUtils.toString(resp.getEntity());
    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(respBody);

    //ArrayList to contain the urls from all of the SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();

    //Get all the ServiceDescriptionDocuments from this ServiceProviderCatalog
    NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:services/@rdf:resource", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < sDescs.getLength(); i++) {
        String serviceUrl = OSLCUtils.absoluteUrlFromRelative(base, sDescs.item(i).getNodeValue());
        Collection<Object[]> subCollection = getReferencedUrls(serviceUrl);
        Iterator<Object[]> iter = subCollection.iterator();
        while (iter.hasNext()) {
            data.add(iter.next());
        }
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //simple query services from the eventual service description documents from them as well.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        String uri = spcs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        if (!uri.equals(base)) {
            Collection<Object[]> subCollection = getReferencedUrls(uri);
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:net.bulletin.pdi.xero.step.support.XMLChunkerTest.java

/**
 * <p>This test is checking to see that, without any container elements, the chunking will produce one
 * document and that single document should be the whole of the input.</p>
 *///from   ww w.  ja  v a  2s.  c om

@Test
public void testPullNextXmlChunk_withoutContainerElements() throws Exception {
    byte[] sampleXml = readSampleXml();

    XMLChunker chunker = new XMLChunkerImpl(
            XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(sampleXml)), // all in-memory
            new Stack<String>());

    // ---------------------------------
    String actuals[] = new String[] { chunker.pullNextXmlChunk(), chunker.pullNextXmlChunk() };
    // ---------------------------------

    // This will work through the chunks and check specific information it knows in the sample.

    {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        XPath xPath = XPathFactory.newInstance().newXPath();

        org.w3c.dom.Document doc = documentBuilder
                .parse(new ByteArrayInputStream(actuals[0].getBytes(CharEncoding.UTF_8)));
        NodeList artistNodeList = (NodeList) xPath.evaluate("/Response/Artists/Artist", doc,
                XPathConstants.NODESET);

        Assert.assertEquals(3, artistNodeList.getLength());
    }

    Assert.assertNull("expected the last chunk to be null", actuals[1]);

}