Example usage for javax.xml.xpath XPath evaluate

List of usage examples for javax.xml.xpath XPath evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPath evaluate.

Prototype

public String evaluate(String expression, InputSource source) throws XPathExpressionException;

Source Link

Document

Evaluate an XPath expression in the context of the specified InputSource and return the result as a String .

Usage

From source file:com.orange.ngsi.model.UpdateContextModelTest.java

@Test
public void serializationXML() throws IOException, URISyntaxException, XPathExpressionException {

    String xml = xmlmapper.writeValueAsString(createUpdateContextTempSensor(0));

    String xpathExpr = "/updateContextRequest/contextElementList/contextElement[1]/entityId/id";
    XPath xPath = XPathFactory.newInstance().newXPath();
    String value = xPath.evaluate(xpathExpr, new InputSource(new StringReader(xml)));
    assertEquals("S1", value);
}

From source file:com.orange.ngsi.model.ContextAttributeModelTest.java

@Test
public void serializationXMLContextAttribute() throws IOException, XPathExpressionException {

    ContextAttribute contextAttribute = new ContextAttribute("A", "T", "22");

    ObjectMapper xmlmapper = new XmlMapper();
    String xml = xmlmapper.writeValueAsString(contextAttribute);

    assertTrue(xml.contains("A"));
    assertTrue(xml.contains("T"));
    assertTrue(xml.contains("22"));

    String xpathExpr = "/ContextAttribute/name";
    XPath xPath = XPathFactory.newInstance().newXPath();
    assertEquals("A", xPath.evaluate(xpathExpr, new InputSource(new StringReader(xml))));
}

From source file:hoot.services.review.ReviewTestUtils.java

private static void populateOsmIdMappings(final Document changesetUploadResponse, final ElementType elementType,
        Map<Long, Long> mappings, final int size) throws XPathExpressionException {
    XPath xpath = XmlDocumentBuilder.createXPath();
    mappings.clear();/*from  w w  w  .  j av a 2s .  c  o  m*/

    //there aren't more than 100 elements of any type in the source file
    for (int i = 1; i < size + 1; i++) {
        final long oldId = -1 * i;
        final String newIdStr = xpath.evaluate("//osm/diffResult/" + elementType.toString().toLowerCase()
                + "[@old_id=\"" + oldId + "\"]/@new_id", changesetUploadResponse);
        if (StringUtils.trimToNull(newIdStr) != null) {
            final long newId = Long.parseLong(newIdStr);
            mappings.put(oldId, newId);
        }
    }
}

From source file:pakiet.rt.DelicjaXMLParser.java

private void parse() throws SAXException, IOException, XPathExpressionException, ParserConfigurationException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(new ByteArrayInputStream(xmlInputString.getBytes()));
    XPath xPath = XPathFactory.newInstance().newXPath();
    String userName = xPath.evaluate("//*[1]/@user", xmlDocument);
    resp.setUser(userName);// w ww .j av  a 2 s  .c om
    System.out.println("test: " + userName);

    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

}

From source file:org.orcid.examples.jopmts.mvc.OrcidClientModel.java

public OrcidClientModel(Node partialDocument, XPath xpath) {
    try {// w  w  w  . j a  v a2 s  .c om
        for (String key : getModelStringPaths().keySet()) {
            this.addAttribute(key, xpath.evaluate(getModelStringPaths().get(key), partialDocument));
        }
        for (String key : getModelStringArrayPaths().keySet()) {
            this.addAttribute(key,
                    stringListFromDocument(getModelStringArrayPaths().get(key), xpath, partialDocument));
        }
    } catch (XPathExpressionException e) {
        // Error handling needed?!
    }
}

From source file:br.com.insula.spring.security.janrain.JanrainService.java

private String getStringValue(Document document, XPath xPath, String expression)
        throws XPathExpressionException {
    String value = xPath.evaluate(expression, document).trim();
    return value.isEmpty() ? null : value;
}

From source file:net.javacrumbs.springws.test.common.XPathExpressionEvaluator.java

public String evaluateExpression(Document document, String expression, URI uri,
        NamespaceContext namespaceContext) {
    XPathFactory factory = XPathFactory.newInstance();
    factory.setXPathVariableResolver(new WsTestXPathVariableResolver(uri));
    try {//from   ww  w .  j a  va 2s  .co m
        XPath xpath = factory.newXPath();
        if (namespaceContext != null) {
            xpath.setNamespaceContext(namespaceContext);
        }
        String result = xpath.evaluate(expression, document);
        logger.debug("Expression \"" + expression + "\" resolved to \"" + result + "\"");
        return result;
    } catch (XPathExpressionException e) {
        throw new ExpressionResolverException(
                "Could not evaluate XPath expression \"" + expression + "\" : \"" + e.getMessage() + "\"", e);
    }
}

From source file:com.synclio.hawk.TutorialRouteBuilder.java

@Override
public void configure() throws Exception {
    from("ghttp:///weather").process(new RequestProcessor()).marshal().serialization().to("gtask://default")
            .unmarshal().serialization().process(new ResponseProcessor());

    from("gtask://default").unmarshal().serialization().process(new Processor() {
        @Override//  w  w w . j  av  a  2  s. c om
        public void process(Exchange exchange) throws Exception {
            ReportData data = exchange.getIn().getBody(ReportData.class);

            URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
            HTTPRequest req = new HTTPRequest(new URL("http://where.yahooapis.com/v1/places.q(" + data.getCity()
                    + ")?appid=0b4twNzV34GzaTHevW1SzEcnzG4Nyuhq6pvnSKZS.28kCqUw31jPRApe6_niElSL_waLc2M-"),
                    HTTPMethod.GET);
            HTTPResponse resp = urlFetch.fetch(req);

            Document doc = toDocument(IOUtils.toInputStream(new String(resp.getContent())));
            XPathFactory xpfactory = XPathFactory.newInstance();
            XPath xpath = xpfactory.newXPath();
            try {
                System.out.print(xpath.evaluate("//places/place[1]/woeid/text()", doc));
                System.out.print(new String(resp.getContent()));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    });
    //         .setHeader(Exchange.HTTP_METHOD,constant("GET"))
    //         .enrich("ghttp://where.yahooapis.com/v1/places.q(Chennai)?appid=0b4twNzV34GzaTHevW1SzEcnzG4Nyuhq6pvnSKZS.28kCqUw31jPRApe6_niElSL_waLc2M-")         .setHeader(GMailBinding.GMAIL_SUBJECT, constant("Weather report"))
    //         .setHeader(GMailBinding.GMAIL_SENDER, ReportData.requestor())
    //         .setHeader(GMailBinding.GMAIL_TO, ReportData.recipient())
    //         .process(new ReportGenerator())
    //         .to("gmail://default");
}

From source file:org.ambraproject.solr.SolrMostViewedArticleService.java

@Override
public List<Pair<String, String>> getMostViewedArticles(String journal, int limit, Integer numDays)
        throws SolrException {
    //check if we still have valid results in the cache
    MostViewedCache cache = cachedMostViewedResults.get(journal);
    if (cache != null && cache.isValid()) {
        return cache.getArticles();
    }//from   w ww. jav a 2s. c om

    Map<String, String> params = new HashMap<String, String>();
    params.put("fl", DOI_ATTR + "," + TITLE_ATTR);
    params.put("fq",
            "doc_type:full AND !article_type_facet:\"Issue Image\" AND cross_published_journal_key:" + journal);
    params.put("start", "0");
    params.put("rows", String.valueOf(limit));
    params.put("indent", "off");
    String sortField = (numDays != null) ? solrFieldConverter.getViewCountingFieldName(numDays)
            : solrFieldConverter.getAllTimeViewsField();
    params.put("sort", sortField + " desc");

    Document doc = solrHttpService.makeSolrRequest(params);

    List<Pair<String, String>> articles = new ArrayList<Pair<String, String>>(limit);

    //get the children of the "result" node
    XPath xPath = XPathFactory.newInstance().newXPath();
    try {
        Integer count = Integer.valueOf(xPath.evaluate("count(//result/doc)", doc));
        for (int i = 1; i <= count; i++) {
            String doi = xPath.evaluate("//result/doc[" + i + "]/str[@name = '" + DOI_ATTR + "']/text()", doc);
            String title = xPath.evaluate("//result/doc[" + i + "]/str[@name = '" + TITLE_ATTR + "']/text()",
                    doc);
            articles.add(new Pair<String, String>(doi, title));
        }
    } catch (XPathExpressionException e) {
        throw new SolrException("Error parsing solr xml response", e);
    }

    //cache the results
    cachedMostViewedResults.put(journal, new MostViewedCache(articles));
    return articles;
}

From source file:org.openmrs.module.dhisreport.api.dxf2.DataValueSetTest.java

protected String xpathTest(String xpathString, String xml) throws XPathExpressionException {
    InputSource source = new InputSource(new StringReader(xml));
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new Dxf2NamespaceResolver());

    return (String) xpath.evaluate(xpathString, source);
}