Example usage for javax.xml.xpath XPathExpression evaluate

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

Introduction

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

Prototype

public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:org.openremote.foxycart.resources.FoxyCartResource.java

private String evaluateXPath(Document doc, String xPathExpression) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    String text = null;/*from ww  w.  j av  a 2s . co m*/

    try {
        XPathExpression expr = xpath.compile(xPathExpression);
        text = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
    }

    return text;
}

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

private List<String> getJourids(final String content) {

    final List<String> result = new ArrayList<String>();

    try {//from   ww  w  . j  a v a  2 s  .com

        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();

            final XPathExpression exprJournals = xpath.compile("//journals/journal");
            final NodeList journals = (NodeList) exprJournals.evaluate(doc, XPathConstants.NODESET);

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

                final String id = journal.getAttribute("jourid");

                if (id != null) {
                    result.add(id);
                }

            }
        }

    } 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 result;
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java

/**
 * Evaluates the xpath expression on the document and returns the node it resolves to.
 *
 * @param doc        the doc to search/*ww w  . j av a  2 s.  com*/
 * @param expression the xpath expression
 * @return the node
 * @throws XPathExpressionException if so.
 */
Node xPath(Document doc, String expression) throws XPathExpressionException {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(expression);
    return (Node) expr.evaluate(doc, XPathConstants.NODE);
}

From source file:de.fzi.ALERT.actor.MessageObserver.ComplexEventObserver.JMSMessageParser.java

public Message XMLFileParse(String msgString) {

    Message message = new Message();

    try {/*from   w  w w.  ja v  a 2  s  .  c  om*/

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(new MyErrorHandler());

        InputStream in = new ByteArrayInputStream(msgString.getBytes("UTF-8"));
        org.w3c.dom.Document doc = builder.parse(in);

        XPath xpath = XPathFactory.newInstance().newXPath();
        // XPath Query for showing all nodes value
        javax.xml.xpath.XPathExpression expr = xpath.compile("//patternID/text()");

        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;
        Pattern pattern = new Pattern();
        if (nodes.getLength() > 0) {
            pattern = patternDAO.findById(nodes.item(0).getNodeValue());
        }
        if (pattern != null) {

            message.setPatternId(pattern);
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println(nodes.item(i).getNodeValue());
            }

            javax.xml.xpath.XPathExpression expr1 = xpath.compile("//alertcomplex/*/text()");

            Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes1 = (NodeList) result1;
            String content = "";
            if (nodes.getLength() > 0) {
                for (int i = 0; i < nodes1.getLength(); i++) {
                    System.out.println("modes " + nodes1.item(i).getParentNode().getNodeName());
                    System.out.println(nodes1.item(i).getNodeValue());
                    content += nodes1.item(i).getNodeValue();
                }
            }
            message.setSubject("complex event");
            message.setSummary("default summary");
            message.setContent(content);
            message.setMsgDate(new Date());
            message.setMsgID(1);
        } else {
            message.setContent("ERROR!");
        }
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    }

    return message;

}

From source file:cz.fi.muni.xkremser.editor.server.AuthenticationServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    String url = (String) session.getAttribute(HttpCookies.TARGET_URL);
    String root = (URLS.LOCALHOST() ? "http://" : "https://") + req.getServerName() + (URLS.LOCALHOST()
            ? (req.getServerPort() == 80 || req.getServerPort() == 443 ? "" : (":" + req.getServerPort()))
            : "") + URLS.ROOT() + (URLS.LOCALHOST() ? "?gwt.codesvr=127.0.0.1:9997" : "");
    String authHeader = req.getHeader("Authorization");
    if (authHeader != null) {
        String decodedHeader = decode(req, authHeader);
        String pass = configuration.getHttpBasicPass();
        if (pass == null || "".equals(pass.trim()) || pass.length() < 4) {
            requrireAuthentication(resp);
        }// w w  w.ja v a  2  s . c o  m
        if (decodedHeader.equals(ALLOWED_PREFIX + pass)) {
            session.setAttribute(HttpCookies.TARGET_URL, null);
            session.setAttribute(HttpCookies.SESSION_ID_KEY,
                    "https://www.google.com/profiles/109255519115168093543");
            session.setAttribute(HttpCookies.NAME_KEY, "admin");
            session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES);
            ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User "
                    + decodedHeader.substring(0, decodedHeader.indexOf(":")) + " with openID BASIC_AUTH and IP "
                    + req.getRemoteAddr());
            URLS.redirect(resp, url == null ? root : url);
            return;
        } else {
            requrireAuthentication(resp);
            return;
        }
    }
    session.setAttribute(HttpCookies.TARGET_URL, null);
    String token = req.getParameter("token");

    String appID = configuration.getOpenIDApiKey();
    String openIdurl = configuration.getOpenIDApiURL();
    RPX rpx = new RPX(appID, openIdurl);
    Element e = null;
    try {
        e = rpx.authInfo(token);
    } catch (ConnectionException connEx) {
        requrireAuthentication(resp);
        return;
    }
    String idXPath = "//identifier";
    String nameXPath = "//displayName";
    XPathFactory xpfactory = XPathFactory.newInstance();
    XPath xpath = xpfactory.newXPath();
    String identifier = null;
    String name = null;
    try {
        XPathExpression expr1 = xpath.compile(idXPath);
        XPathExpression expr2 = xpath.compile(nameXPath);
        NodeList nodes1 = (NodeList) expr1.evaluate(e.getOwnerDocument(), XPathConstants.NODESET);
        NodeList nodes2 = (NodeList) expr2.evaluate(e.getOwnerDocument(), XPathConstants.NODESET);
        Element el = null;
        if (nodes1.getLength() != 0) {
            el = (Element) nodes1.item(0);
        }
        if (el != null) {
            identifier = el.getTextContent();
        }
        if (nodes2.getLength() != 0) {
            el = (Element) nodes2.item(0);
        }
        if (el != null) {
            name = el.getTextContent();
        }
    } catch (XPathExpressionException e1) {
        e1.printStackTrace();
    }
    if (identifier != null && !"".equals(identifier)) {
        ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User " + name + " with openID "
                + identifier + " and IP " + req.getRemoteAddr());
        int userStatus = UserDAO.UNKNOWN;
        try {
            userStatus = userDAO.isSupported(identifier);
        } catch (DatabaseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        switch (userStatus) {
        case UserDAO.UNKNOWN:
            // TODO handle DB error (inform user)
            break;
        case UserDAO.USER:
            // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY,
            // identifier);
            session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            URLS.redirect(resp, url == null ? root : url);
            break;
        case UserDAO.ADMIN:
            // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY,
            // identifier);
            // HttpCookies.setCookie(req, resp, HttpCookies.ADMIN,
            // HttpCookies.ADMIN_YES);
            session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES);
            URLS.redirect(resp, url == null ? root : url);
            break;
        case UserDAO.NOT_PRESENT:
        default:
            session.setAttribute(HttpCookies.UNKNOWN_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            URLS.redirect(resp, root + URLS.INFO_PAGE);
            break;
        }
    } else {
        URLS.redirect(resp, root + (URLS.LOCALHOST() ? URLS.LOGIN_LOCAL_PAGE : URLS.LOGIN_PAGE));
    }

    // System.out.println("ID:" + identifier);

    // if user is supported redirect to homepage else show him a page that he
    // has to be added to system first by admin

}

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

/**
 * This class uses the EZB API from//from   ww w .j  av  a  2s. c om
 * http://ezb.uni-regensburg.de/ezeit/vascoda/openURL?pid=format%3Dxml. This
 * API differs from the EZB/ZDB API (http://services.dnb.de). It brings back
 * no print information and other information for electronic holdings. It
 * seems to be more stable.
 */
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();

            // issns
            final XPathExpression exprRefE = xpath.compile("//OpenURLResponse");
            final NodeList resultListRefE = (NodeList) exprRefE.evaluate(doc, XPathConstants.NODESET);

            String title = null;
            String levelAvailable = null;

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

                // First ISSN
                //                    final String issn = getValue(result.getElementsByTagName("issn"));
                //                    System.out.println(issn);

                // title
                // unfortunately this will bring back the title sent by OpenURL, unless if not
                // specified in the OpenURL request. It then brings back the title form the EZB...!
                title = getValue(result.getElementsByTagName("title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    title = Jsoup.parse(title).text();
                }

                // this is the overall level of the best match and not the level of each individual result
                final NodeList levelNode = result.getElementsByTagName("available");
                final Element levelElement = (Element) levelNode.item(0);
                if (levelElement != null) {
                    levelAvailable = levelElement.getAttribute("level");
                }

            }

            // electronic data
            final XPathExpression exprE = xpath.compile("//OpenURLResponse/OpenURLResult/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 NodeList state = result.getElementsByTagName("access");
                final Element stateElement = (Element) state.item(0);
                int color = 0;
                if (stateElement != null) {
                    color = Integer.valueOf(stateElement.getAttribute("color"));
                }

                final EZBDataOnline online = new EZBDataOnline();

                // state
                // 1 free accessible
                if (color == EZBState.FREE.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.free");
                    online.setState(JOPState.FREE.getValue()); // translate state to EZB/ZDB-API
                    // 2 licensed ; 3 partially licensed
                } else if (color == EZBState.LICENSED.getValue()
                        || color == EZBState.LICENSED_PARTIALLY.getValue()) {
                    online.setAmpel("yellow");
                    online.setComment("availresult.abonniert");
                    online.setState(JOPState.LICENSED.getValue()); // translate state to EZB/ZDB-API
                    // not licensed
                } else if (color == EZBState.NOT_LICENSED.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                    online.setState(JOPState.NOT_LICENSED.getValue()); // translate state to EZB/ZDB-API
                } else {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                    online.setState(JOPState.NOT_LICENSED.getValue()); // translate state to EZB/ZDB-API
                }

                // LinkToArticle not always present
                String url = getValue(result.getElementsByTagName("LinkToArticle"));
                // LinkToJournal always present
                if (url == null) {
                    url = getValue(result.getElementsByTagName("LinkToJournal"));
                }
                online.setUrl(url);

                // try to get level from link
                String levelLinkToArticle = null;
                final NodeList levelNode = result.getElementsByTagName("LinkToArticle");
                final Element levelElement = (Element) levelNode.item(0);
                if (levelElement != null) {
                    levelLinkToArticle = levelElement.getAttribute("level");
                }

                if (levelLinkToArticle != null) {
                    online.setLevel(levelLinkToArticle); // specific level of each result
                } else {
                    online.setLevel(levelAvailable); // overall level of best match
                }

                if (title != null) {
                    online.setTitle(title);
                } else {
                    online.setTitle(url);
                }
                online.setReadme(getValue(result.getElementsByTagName("LinkToReadme")));

                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()); // translate state to EZB/ZDB-API

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

        }

    } 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:com.provenance.cloudprovenance.policyhandler.ws.support.PolicyRequestProcessor.java

public String getIdforPolicyMatch(String responseContent, String xpathToDocumentId)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
        XPathFactoryConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from   ww  w.j  a va2  s.c om*/
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(responseContent));
    Document doc = builder.parse(is);

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();
    xpath.setNamespaceContext(cProvMapper);

    XPathExpression xPathExpr;
    xPathExpr = xpath.compile(xpathToDocumentId);

    logger.debug("XpathExpression to match: " + xpathToDocumentId);
    logger.debug("Document to match is: " + responseContent);

    return (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
}

From source file:edu.cornell.mannlib.vitro.utilities.containerneutral.CheckContainerNeutrality.java

/**
 * Search for an Xpath within a node of web.xml, returning a handy list.
 *//*from   ww w . j  av a2s .  c om*/
private List<Node> findNodes(String pattern, Node context) {
    try {
        XPathExpression xpe = xpath.compile(pattern);
        NodeList nodes = (NodeList) xpe.evaluate(context, XPathConstants.NODESET);
        List<Node> list = new ArrayList<Node>();
        for (int i = 0; i < nodes.getLength(); i++) {
            list.add(nodes.item(i));
        }
        return list;
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.camel.component.social.providers.twitter.AbstractTwitterPath.java

protected Iterable<SocialData> convertToSocialDataList(String body) throws Exception {
    DocumentBuilder db = getDomFac().newDocumentBuilder();

    InputSource source = new InputSource();
    source.setCharacterStream(new StringReader(body));
    Document doc = db.parse(source);

    XPathExpression expr = getXpath().compile("/statuses/status");

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

    List<SocialData> socialDataList = new ArrayList<SocialData>(nodes.getLength());
    for (int index = 0; index < nodes.getLength(); index++) {
        Node aNode = nodes.item(index);

        DefaultSocialData socialData = parseStatus(aNode);
        socialDataList.add(socialData);/*from   ww w  .java2s.  co m*/
    }

    return socialDataList;
}

From source file:cz.strmik.cmmitool.cmmi.DefaultRatingScalesProvider.java

private List<RatingScale> readScales(String id, String lang) {
    List<RatingScale> scales = new ArrayList<RatingScale>();
    try {/*from   w  w w. j  ava 2 s  .co  m*/
        Document document = getScalesDocument();

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

        SimpleNamespaceContext ns = new SimpleNamespaceContext();
        ns.bindNamespaceUri("s", SCALES_XML_NS);
        xPath.setNamespaceContext(ns);

        XPathExpression exprScales = xPath.compile("/s:ratings/s:rating[@id='" + id + "']/s:scale");
        XPathExpression exprName = xPath.compile("s:name[@lang='" + lang + "']");
        XPathExpression exprColor = xPath.compile("s:color[@type='html']");

        NodeList nodes = (NodeList) exprScales.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            int score = Integer.parseInt(node.getAttributes().getNamedItem("score").getTextContent());

            String name = exprName.evaluate(node);
            String color = exprColor.evaluate(node);
            RatingScale rs = new RatingScale(name, i, score, color);
            if (i == 0) {
                rs.setDefaultRating(true);
            }
            scales.add(rs);
        }
    } catch (Exception ex) {
        _log.warn(
                "Unable to load default scales for id=" + id + ",lang=" + lang + " ratings from " + SCALES_XML,
                ex);
    }
    return scales;
}