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.jboss.seam.forge.shell.util.PluginUtil.java

public static File downloadPlugin(final PluginRef ref, final PipeOut out, final String targetPath)
        throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();

    String[] artifactParts = ref.getArtifact().split(":");

    if (artifactParts.length != 3) {
        throw new RuntimeException("malformed artifact identifier "
                + "(format should be: <maven.group>:<maven.artifact>:<maven.version>) encountered: "
                + ref.getArtifact());// www  .  ja va2s  . c o  m
    }

    String packageLocation = artifactParts[0].replaceAll("\\.", "/");
    String baseUrl;
    if (ref.getHomeRepo().endsWith("/")) {
        baseUrl = ref.getHomeRepo() + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    } else {
        baseUrl = ref.getHomeRepo() + "/" + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    }

    HttpGet httpGetManifest = new HttpGet(baseUrl + "/maven-metadata.xml");
    out.print("Retrieving artifact manifest ... ");

    HttpResponse response = client.execute(httpGetManifest);
    switch (response.getStatusLine().getStatusCode()) {
    case 200:
        out.println("done.");

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getEntity().getContent());

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression checkSnapshotExpr = xpath.compile("//versioning/snapshot");
        XPathExpression findJar = xpath.compile("//snapshotVersion[extension='jar']/value");

        NodeList list = (NodeList) checkSnapshotExpr.evaluate(document, XPathConstants.NODESET);

        out.print("Reading manifest ... ");

        if (list.getLength() != 0) {

            Node n = (Node) findJar.evaluate(document, XPathConstants.NODE);

            if (n == null) {
                out.println("failed: could not determine where to find jar file.");
                return null;
            }

            String version = n.getFirstChild().getTextContent();

            // plugin definition points to a snapshot.
            out.println("good! (maven snapshot found): " + version);

            String fileName = artifactParts[1] + "-" + version + ".jar";

            HttpGet jarGet = new HttpGet(baseUrl + "/" + fileName);

            out.print("Downloading: " + baseUrl + "/" + fileName + " ... ");
            response = client.execute(jarGet);

            try {
                File file = saveFile(targetPath + "/" + fileName, response.getEntity().getContent());
                out.println("done.");
                return file;
            } catch (IOException e) {
                out.println("failed to download: " + e.getMessage());
                return null;
            }

            // do download of snapshot.
        } else {
            out.println("error! (maven snapshot not found)");
            return null;
        }

    case 404:
        String requestUrl = baseUrl + "/" + artifactParts[2] + ".pom";
        httpGetManifest = new HttpGet(requestUrl);
        response = client.execute(httpGetManifest);

        if (response.getStatusLine().getStatusCode() != 200) {
            printError(response.getStatusLine().getStatusCode(), requestUrl, out);
            return null;
        } else {

            // download regular POM here.

        }
        break;
    default:
        out.println("failed! (server returned status code: " + response.getStatusLine().getStatusCode());
        return null;
    }

    return null;

}

From source file:ch.dbs.actions.bestellung.EZBJOP.java

/**
 * This class uses the official EZB/ZDB API from
 * http://services.dnb.de/fize-service/gvr/full.xml.
 *///www  .  ja  v  a 2s  .co  m
public EZBForm read(final String content) {

    final EZBForm ezbform = new EZBForm();

    try {

        if (content != null) {

            final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            final DocumentBuilder builder = domFactory.newDocumentBuilder();
            final Document doc = builder.parse(new InputSource(new StringReader(content)));

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

            // references electronic data
            //            final XPathExpression exprRefE = xpath.compile("//ElectronicData/References/Reference");
            //            final NodeList resultListRefE = (NodeList) exprRefE.evaluate(doc, XPathConstants.NODESET);
            //
            //            for (int i = 0; i < resultListRefE.getLength(); i++) {
            //                final Node firstResultNode = resultListRefE.item(i);
            //                final Element result = (Element) firstResultNode;
            //
            //                final EZBReference ref = new EZBReference();
            //
            //                // EZB URLs
            //                final String url = getValue(result.getElementsByTagName("URL"));
            //                ref.setUrl(url);
            //
            //                // Label for URLs
            //                final String label = getValue(result.getElementsByTagName("Label"));
            //                ref.setLabel(label);
            //
            //                ezbform.getReferencesonline().add(ref);
            //            }

            // electronic data
            final XPathExpression exprE = xpath.compile("//ElectronicData/ResultList/Result");
            final NodeList resultListE = (NodeList) exprE.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListE.getLength(); i++) {
                final Node firstResultNode = resultListE.item(i);
                final Element result = (Element) firstResultNode;

                final EZBDataOnline online = new EZBDataOnline();

                // state
                online.setState(Integer.valueOf(result.getAttribute("state")));
                // 0 free accessible
                if (online.getState() == JOPState.FREE.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.free");
                    // 1 partially free accesible
                } else if (online.getState() == JOPState.FREE_PARTIALLY.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.partially_free");
                    // 2 licensed ; 3 partially licensed
                } else if (online.getState() == JOPState.LICENSED.getValue()
                        || online.getState() == JOPState.LICENSED_PARTIALLY.getValue()) {
                    online.setAmpel("yellow");
                    online.setComment("availresult.abonniert");
                    // journal not online for periode
                } else if (online.getState() == JOPState.OUTSIDE_PERIOD.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.timeperiode");
                    // not indexed
                } else if (online.getState() == JOPState.NO_HITS.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.nohits");
                } else {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                }

                // title
                String title = getValue(result.getElementsByTagName("Title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    online.setTitle(Jsoup.parse(title).text());
                }

                online.setUrl(getValue(result.getElementsByTagName("AccessURL")));
                online.setLevel(getValue(result.getElementsByTagName("AccessLevel")));
                online.setReadme(getValue(result.getElementsByTagName("ReadmeURL")));
                // National licenses etc.
                online.setAdditional(getValue(result.getElementsByTagName("Additional")));

                ezbform.getOnline().add(online);
            }

            // Title not found
            if (resultListE.getLength() == 0) {
                final EZBDataOnline online = new EZBDataOnline();
                online.setAmpel("red");
                online.setComment("availresult.nohits");
                online.setState(JOPState.NO_HITS.getValue());

                ezbform.getOnline().add(online);
            }

            // references print data
            final XPathExpression exprRefP = xpath.compile("//PrintData/References/Reference");
            final NodeList resultListRefP = (NodeList) exprRefP.evaluate(doc, XPathConstants.NODESET);

            final EZBReference ref = new EZBReference();

            for (int i = 0; i < resultListRefP.getLength(); i++) {
                final Node firstResultNode = resultListRefP.item(i);
                final Element result = (Element) firstResultNode;

                // EZB URLs
                ref.setUrl(getValue(result.getElementsByTagName("URL")));

                // Label for URLs
                //                final String label = getValue(result.getElementsByTagName("Label"));
                ref.setLabel("availresult.link_title_print");

                ezbform.getReferencesprint().add(ref);
            }

            // print data
            final XPathExpression exprP = xpath.compile("//PrintData/ResultList/Result");
            final NodeList resultListP = (NodeList) exprP.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListP.getLength(); i++) {
                final Node firstResultNode = resultListP.item(i);
                final Element result = (Element) firstResultNode;

                final EZBDataPrint print = new EZBDataPrint();

                // state
                print.setState(Integer.valueOf(result.getAttribute("state")));

                // title
                String title = getValue(result.getElementsByTagName("Title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    print.setTitle(Jsoup.parse(title).text());
                }

                print.setLocation(getValue(result.getElementsByTagName("Location")));
                print.setCallnr(getValue(result.getElementsByTagName("Signature")));
                print.setCoverage(getValue(result.getElementsByTagName("Period")));

                // set previous extracted URL and label
                print.setInfo(ref);

                // in stock ; partially in stock
                if (print.getState() == JOPState.LICENSED.getValue()
                        || print.getState() == JOPState.LICENSED_PARTIALLY.getValue()) {
                    print.setAmpel("yellow");
                    print.setComment("availresult.print");
                    // only return if existing in Print
                    ezbform.getPrint().add(print);
                }
            }
        }

    } catch (final XPathExpressionException e) {
        LOG.error(e.toString());
    } catch (final SAXParseException e) {
        LOG.error(e.toString());
    } catch (final SAXException e) {
        LOG.error(e.toString());
    } catch (final IOException e) {
        LOG.error(e.toString());
    } catch (final ParserConfigurationException e) {
        LOG.error(e.toString());
    } catch (final Exception e) {
        LOG.error(e.toString());
    }

    return ezbform;
}

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

@Test
public void validNotEqualQueryContainsExpectedDefect()
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
    //Form the inequality 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);
    assertTrue(results != null);/*from w  ww .  j  a v a 2s.c  o m*/
    assertTrue(results.getLength() > 0);
    //Check that the property elements are not equal to the value in the previous test
    checkInequalityProperty(results, queryProperty, queryPropertyValue, doc);
}

From source file:XMLBody.java

public String getContent(String xpath) throws Exception {
    XPath path = XPathFactory.newInstance().newXPath();
    NodeList childNodes;//from  w ww.  ja v a 2s . co  m
    try {
        childNodes = (NodeList) path.evaluate(xpath, xmlDocument, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new Exception("Error evaluate xpath", e);
    }
    return serializeNodes(childNodes);
}

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

private void parseConnections(Document doc, XPath path) throws XPathExpressionException {
    NodeList databaseList = (NodeList) path.evaluate("configuration/connections/database", doc,
            XPathConstants.NODESET);
    if (databaseList != null) {
        for (int i = 0; i < databaseList.getLength(); i++) {
            parseDatabase(databaseList.item(i), path);
        }/*from  w w w. j a v a2 s . c o m*/
    }
}

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

public static Map<String, Object> getProperties(Document document) {
    Map<String, Object> props = new HashMap<>();

    if (document != null) {
        try {/*ww w . j a  va 2s .  co  m*/
            XPath xpath = XPATH_FACTORY.newXPath();
            xpath.setNamespaceContext(NAMESPACE_CONTEXT);
            NodeList nodes = (NodeList) xpath.evaluate(
                    "/components/component[1]/property[@name!='' and @value!='']", document,
                    XPathConstants.NODESET);
            if (nodes != null) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    String name = node.getAttributes().getNamedItem("name").getNodeValue();
                    String value = node.getAttributes().getNamedItem("value").getNodeValue();
                    String type = null;
                    Node typeAttribute = node.getAttributes().getNamedItem("type");
                    if (typeAttribute != null) {
                        type = typeAttribute.getNodeValue();
                    }
                    if (StringUtils.equals("Integer", type)) {
                        props.put(name, Integer.parseInt(value));
                    } else {
                        props.put(name, value);
                    }
                }
            }
        } catch (XPathExpressionException ex) {
            throw new RuntimeException("Error evaluating XPath.", ex);
        }
    }

    return props;
}

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

public static Collection<Object[]> getReferencedCatalogUrlsUsingXML(String base)
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    staticSetup();/*  w  w  w .ja v  a2s.  c o m*/
    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, basicCreds, OSLCConstants.CT_XML, headers);

    int statusCode = resp.getStatusLine().getStatusCode();
    if (HttpStatus.SC_OK != statusCode) {
        EntityUtils.consume(resp.getEntity());
        throw new IOException("Response code: " + statusCode + " for " + base);
    }

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

    // ArrayList to contain the urls from all SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();
    Node rootElement = (Node) OSLCUtils.getXPath().evaluate("/rdf:RDF/*", baseDoc, XPathConstants.NODE);
    if (rootElement.getNamespaceURI().equals(OSLCConstants.OSLC_V2)
            && rootElement.getLocalName().equals("ServiceProviderCatalog")) {
        data.add(new Object[] { base });
    }

    // Get all ServiceProviderCatalog urls from the base document in order
    // to test them as well,
    // recursively checking them for other ServiceProviderCatalogs further
    // down.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_v2:serviceProviderCatalog/oslc_v2:ServiceProviderCatalog/@rdf:about", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        if (!spcs.item(i).getNodeValue().equals(base)) {
            Collection<Object[]> subCollection = getReferencedCatalogUrlsUsingXML(spcs.item(i).getNodeValue());
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:it.jnrpe.plugin.tomcat.TomcatDataProvider.java

private void parseMemoryPools() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(tomcatXML));

    Document doc = builder.parse(is);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();

    NodeList memoryPoolList = (NodeList) xpath.compile("//status/jvm/memorypool")
            .evaluate(doc.getDocumentElement(), XPathConstants.NODESET);

    for (int i = 0; i < memoryPoolList.getLength(); i++) {
        Node poolNode = memoryPoolList.item(i);
        NamedNodeMap atts = poolNode.getAttributes();
        final String poolName = atts.getNamedItem("name").getNodeValue();
        long usageInit = Long.parseLong(atts.getNamedItem("usageInit").getNodeValue());
        long usageCommitted = Long.parseLong(atts.getNamedItem("usageCommitted").getNodeValue());
        long usageMax = Long.parseLong(atts.getNamedItem("usageMax").getNodeValue());
        long usageUsed = Long.parseLong(atts.getNamedItem("usageUsed").getNodeValue());

        memoryPoolData.put(poolName,//from w  w  w .j a v  a  2 s .  c om
                new MemoryPoolData(poolName, usageInit, usageCommitted, usageMax, usageUsed));
    }
}

From source file:de.ingrid.iplug.opensearch.converter.IngridRSSConverter.java

/**
 * Return the hits coming from the response of an OS-Interface.
 * //w  ww  . j a  v  a2s .  c om
 * @param doc
 *            is the converted response into a document structure
 * @param plugId
 * @param totalResults
 * @param groupedBy
 * @return
 * @throws XPathExpressionException
 */
private IngridHit[] getHits(Document doc, String plugId, int totalResults, String groupedBy)
        throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate("/rss/channel/item", doc, XPathConstants.NODESET);
    IngridHit[] hits = new IngridHit[nodes.getLength()];

    for (int i = 0; i < nodes.getLength(); i++) {
        IngridHit hit = new IngridHit(plugId, "0", 0, (float) 1.0);
        Node node = nodes.item(i);
        hit.put("title", getTitle(node));
        hit.put("url", getLink(node));
        hit.put("abstract", getAbstract(node));
        hit.put("no_of_hits", String.valueOf(totalResults));
        hit.setScore(getScore(node));

        // ingrid specific data
        setIngridHitDetail(hit, node, groupedBy);

        hits[i] = hit;
    }

    // now we have all original hits, let's manipulate the score
    normalizeRanking(hits);

    return hits;
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.aspect.AspectLexiconFactory.java

protected AspectLexiconFactory addXmlAspect(AspectLexicon lexicon, Node aspectNode)
        throws XPathExpressionException {

    Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon");
    Validate.notNull(aspectNode, CannedMessages.NULL_ARGUMENT, "node");

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

    // if the node is called "lexicon" then we're at the root, so we won't need to add an aspect and its expressions.
    AspectLexicon aspect = lexicon;/*from   www .j a  v  a  2  s.  co  m*/
    if (!"aspect-lexicon".equalsIgnoreCase(aspectNode.getLocalName())) {
        String title = Validate.notEmpty(
                (String) xpath.compile("./@title").evaluate(aspectNode, XPathConstants.STRING),
                CannedMessages.EMPTY_ARGUMENT, "./aspect/@title");
        ;

        // fetch or create aspect.
        aspect = lexicon.findAspect(title);
        if (aspect == null) {
            aspect = lexicon.addAspect(title);
        }

        // get all expressions or keywords, whatever they're called.
        NodeList expressionNodes = (NodeList) xpath.compile("./expressions/expression").evaluate(aspectNode,
                XPathConstants.NODESET);
        if (expressionNodes == null || expressionNodes.getLength() == 0) {
            expressionNodes = (NodeList) xpath.compile("./keywords/keyword").evaluate(aspectNode,
                    XPathConstants.NODESET);
        }

        // add each of them if they don't exist.
        if (expressionNodes != null) {
            for (int index = 0; index < expressionNodes.getLength(); index++) {
                String expression = expressionNodes.item(index).getTextContent().trim();
                if (!aspect.hasExpression(expression)) {
                    aspect.addExpression(expression);
                }
            }
        }
    }

    // get all sub-aspects and add them recursively.
    NodeList subAspectNodes = (NodeList) xpath.compile("./aspects/aspect").evaluate(aspectNode,
            XPathConstants.NODESET);
    if (subAspectNodes != null) {
        for (int index = 0; index < subAspectNodes.getLength(); index++) {
            this.addXmlAspect(aspect, subAspectNodes.item(index));
        }
    }

    return this;
}