Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:com.intel.hadoop.graphbuilder.demoapps.wikipedia.linkgraph.LinkGraphTokenizer.java

public LinkGraphTokenizer() throws ParserConfigurationException {
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w w w .j a v  a 2s  .  co m*/
    builder = factory.newDocumentBuilder();
    XPathFactory xfactory = XPathFactory.newInstance();
    xpath = xfactory.newXPath();

    vlist = new ArrayList<Vertex<StringType, EmptyType>>();
    elist = new ArrayList<Edge<StringType, EmptyType>>();
    links = new ArrayList<String>();
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Gets all nodes matching an XPath/* w  w w  .  ja v  a  2 s  .c  om*/
 */
public static NodeList getNodesFromXP(Node n, String xpath) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xp = factory.newXPath();
    XPathExpression expr = xp.compile(xpath);
    return (NodeList) expr.evaluate(n, XPathConstants.NODESET);
}

From source file:com.esri.geoportal.commons.csw.client.impl.ProfilesLoader.java

/**
 * Loads profiles.//w ww. j ava  2  s.c o m
 * @return profiles
 * @throws IOException if loading profiles from configuration fails
 * @throws ParserConfigurationException if unable to obtain XML parser
 * @throws SAXException if unable to parse XML document
 * @throws XPathExpressionException if invalid XPath expression
 */
public Profiles load()
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    LOG.info(String.format("Loading CSW profiles"));
    Profiles profiles = new Profiles();
    try (InputStream profilesXml = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(CONFIG_FILE_PATH);) {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        Document profilesDom = builder.parse(new InputSource(profilesXml));

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

        NodeList profilesNodeList = (NodeList) xpath.evaluate("/CSWProfiles/Profile", profilesDom,
                XPathConstants.NODESET);
        for (int pidx = 0; pidx < profilesNodeList.getLength(); pidx++) {
            Node profileNode = profilesNodeList.item(pidx);
            String id = StringUtils
                    .trimToEmpty((String) xpath.evaluate("ID", profileNode, XPathConstants.STRING));
            String name = StringUtils
                    .trimToEmpty((String) xpath.evaluate("Name", profileNode, XPathConstants.STRING));
            String namespace = StringUtils
                    .trimToEmpty((String) xpath.evaluate("CswNamespace", profileNode, XPathConstants.STRING));
            String description = StringUtils
                    .trimToEmpty((String) xpath.evaluate("Description", profileNode, XPathConstants.STRING));

            String getRecordsReqXslt = StringUtils.trimToEmpty((String) xpath
                    .evaluate("GetRecords/XSLTransformations/Request", profileNode, XPathConstants.STRING));
            String getRecordsRspXslt = StringUtils.trimToEmpty((String) xpath
                    .evaluate("GetRecords/XSLTransformations/Response", profileNode, XPathConstants.STRING));

            String getRecordByIdReqKVP = StringUtils.trimToEmpty(
                    (String) xpath.evaluate("GetRecordByID/RequestKVPs", profileNode, XPathConstants.STRING));
            String getRecordByIdRspXslt = StringUtils.trimToEmpty((String) xpath
                    .evaluate("GetRecordByID/XSLTransformations/Response", profileNode, XPathConstants.STRING));

            Profile prof = new Profile();
            prof.setId(id);
            prof.setName(name);
            prof.setDescription(description);
            prof.setGetRecordsReqXslt(getRecordsReqXslt);
            prof.setGetRecordsRspXslt(getRecordsRspXslt);
            prof.setKvp(getRecordByIdReqKVP);
            prof.setGetRecordByIdRspXslt(getRecordByIdRspXslt);

            profiles.add(prof);
        }
    }
    LOG.info(String.format("CSW profiles loaded."));
    return profiles;
}

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 {/* www.  j  a va 2 s  .  c o 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//from w w  w .jav a2  s. co m
        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:com.seajas.search.utilities.web.WebPages.java

private XPath getXPathEngine() {
    XPath engine = xPathEngine;/*from  ww w  .  j a  v  a 2 s. com*/
    if (engine == null) {
        XPathFactory factory = XPathFactory.newInstance();
        engine = factory.newXPath();
        SimpleNamespaceContext namespaces = new SimpleNamespaceContext();
        namespaces.bindNamespaceUri("ht", "http://www.w3.org/1999/xhtml");
        engine.setNamespaceContext(namespaces);
        xPathEngine = engine;
    }
    return engine;
}

From source file:org.ow2.chameleon.fuchsia.push.base.subscriber.tool.HubDiscovery.java

public String hasHub(Document doc) {
    String hub = null;/*from   ww  w  .  j a v a2  s  . co  m*/

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    XPathExpression xPathExpression;

    try {
        xPathExpression = xPath.compile("/feed/link[@rel='hub']/@href");
        hub = xPathExpression.evaluate(doc);
        if ((hub == null) || (hub.length() == 0)) {
            xPathExpression = xPath.compile("//link[@rel='hub']/@href");
            hub = xPathExpression.evaluate(doc);
        }

        if (hub.length() == 0) {
            return null;
        }

        return hub;

    } catch (XPathExpressionException e) {
        LOGGER.error("XPathExpression invalid", e);
        return null;
    }
}

From source file:org.ow2.chameleon.fuchsia.push.base.subscriber.tool.HubDiscovery.java

public String hasTopic(Document doc) {
    String topic;//w  w w. j a v  a2 s  . c o  m

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    XPathExpression xPathExpression;

    try {
        xPathExpression = xPath.compile("/feed/link[@rel='self']/@href");
        topic = xPathExpression.evaluate(doc);
        if ((topic == null) || (topic.length() == 0)) {
            xPathExpression = xPath.compile("//link[@rel='self']/@href");
            topic = xPathExpression.evaluate(doc);
        }

        if (topic.length() == 0) {
            return null;
        }
        return topic;

    } catch (XPathExpressionException e) {
        LOGGER.error("Invalid XpathExpression", e);
        return null;
    }

}

From source file:com.fortysevendeg.lab.WeatherTask.java

/**
 * Performs work in the background invoking the weather remote service and parses the xml results into temp values
 * @param strings the place params to search form
 * @return the temperature in celsius/*  w w w.  jav  a  2s  .  co m*/
 */
@Override
protected final Integer doInBackground(String... strings) {
    int temp = ERROR;
    try {
        String xml = fetchWeatherData(strings[0]);
        if (xml != null) {
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(context.getString(R.string.xpath_weather_service_temperature));
            Object result = expr.evaluate(new InputSource(new StringReader(xml)), XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            if (nodes.getLength() > 0) {
                temp = Integer.valueOf(nodes.item(0).getAttributes().getNamedItem("data").getNodeValue());
            }
        }
    } catch (XPathExpressionException e) {
        Log.wtf(WeatherTask.class.toString(), e);
    } catch (IOException e) {
        Log.wtf(WeatherTask.class.toString(), e);
    }
    return temp;
}

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  ww  .j  ava 2s  .  co  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)));
}