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.apache.servicemix.wsn.jms.JmsSubscription.java

protected boolean doFilter(Element content) {
    if (contentFilter != null) {
        if (!contentFilter.getDialect().equals(XPATH1_URI)) {
            throw new IllegalStateException("Unsupported dialect: " + contentFilter.getDialect());
        }/*from  w  ww.j  av  a 2  s .  c om*/
        try {
            XPathFactory xpfactory = XPathFactory.newInstance();
            XPath xpath = xpfactory.newXPath();
            XPathExpression exp = xpath.compile(contentFilter.getContent().get(0).toString());
            Boolean ret = (Boolean) exp.evaluate(content, XPathConstants.BOOLEAN);
            return ret.booleanValue();
        } catch (XPathExpressionException e) {
            log.warn("Could not filter notification", e);
        }
        return false;
    }
    return true;
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

protected List<Node> evaluateXPath(String xpathExpression, Node node) throws XPathExpressionException {
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    final XPathExpression pathExpression = xpath.compile(xpathExpression);
    return wrapNodeList((NodeList) pathExpression.evaluate(node, XPathConstants.NODESET));
}

From source file:com.mnxfst.testing.server.cfg.PTestServerConfigurationParser.java

/**
 * Evaluates the given expression on the referenced document and returns a result object of type {@link NodeList} 
 * @param expression/*from www  . j a v a2  s. c o  m*/
 * @param document
 * @return
 * @throws XPathExpressionException
 */
protected NodeList evaluateNodeList(XPathExpression expression, Object document)
        throws XPathExpressionException {
    if (expression == null)
        throw new XPathExpressionException("Null is not a valid expression");
    if (document == null)
        throw new XPathExpressionException("An xpath expression must not be applied to a NULL document");

    return (NodeList) expression.evaluate(document, XPathConstants.NODESET);
}

From source file:com.sixdimensions.wcm.cq.pack.service.impl.LegacyPackageManagerServiceImpl.java

/**
 * Parses the response from the server using XPath.
 * /*from ww w  . j  a v  a  2 s  . co  m*/
 * @param response
 *            the response to parse
 * @return a response object representing the response data
 * @throws XPathExpressionException
 * @throws SAXException
 * @throws IOException
 * @throws ParserConfigurationException
 */
private Response parseResponse(final byte[] response)
        throws XPathExpressionException, IOException, ParserConfigurationException {
    this.log.debug("parseResponse");

    Response responseObj = null;
    try {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this!
        final Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(response));

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

        // Sample response
        //
        // <crx version="2.0" user="admin" workspace="crx.default">
        // <request>
        // <param name="cmd" value="rm"/>
        // <param name="name" value="myPackage"/>
        // </request>
        // <response>
        // <status code="200">ok</status>
        // </response>
        // </crx>

        this.log.debug("Parsing response code");
        final XPathExpression codeXpr = xpath.compile("/crx/response/status/@code");
        int responseCode = -1;
        try {
            responseCode = Integer.parseInt(
                    ((NodeList) codeXpr.evaluate(doc, XPathConstants.NODESET)).item(0).getNodeValue(), 10);
        } catch (final NumberFormatException nfe) {
            this.log.warn("Unable to parse "
                    + ((NodeList) codeXpr.evaluate(doc, XPathConstants.NODESET)).item(0).getNodeValue()
                    + " as a number");
        }

        this.log.debug("Parsing response message");
        final XPathExpression messageXpr = xpath.compile("/crx/response/status");
        final String responseMessage = ((NodeList) messageXpr.evaluate(doc, XPathConstants.NODESET)).item(0)
                .getChildNodes().item(0).getNodeValue();

        responseObj = new Response(HttpStatus.SC_OK == responseCode, responseCode, responseMessage);
        this.log.debug("Response Code: " + responseCode);
        if (HttpStatus.SC_OK == responseCode) {
            this.log.debug("Response Message: " + responseMessage);
        } else {
            this.log.warn("Error Message: " + responseMessage);
        }
    } catch (final SAXException se) {
        final String message = "Exception parsing XML response, assuming failure.  "
                + "This often occurs when an invalid XML file is uploaded as the error message "
                + "is not properly escaped in the response.";
        this.log.warn(message, se);
        this.log.warn("Response contents: " + new String(response, "utf-8"));
        responseObj = new Response(false, 500, message);
    }

    return responseObj;
}

From source file:com.redhat.plugin.eap6.EAP6DeploymentStructureMojo.java

protected void fillModuleEntries(Document doc, Element dependencies, Collection<String> modules)
        throws XPathExpressionException {
    for (String module : modules) {
        XPathExpression xp = xpf.newXPath().compile("module [@name=\"" + module + "\"]");
        // getLog().debug(xp.toString());
        Object result = xp.evaluate(dependencies, XPathConstants.NODE);
        if (result == null) {
            getLog().debug("insert module-dependency for " + module);
            Element moduleEl = doc.createElement("module");
            moduleEl.setAttribute("name", module);
            if (defaultSlot != null && !defaultSlot.isEmpty()) {
                moduleEl.setAttribute("slot", defaultSlot);
            }/*w ww.ja v  a  2  s .c o m*/
            if (exportModules) {
                moduleEl.setAttribute("export", "true");
            }
            dependencies.appendChild(moduleEl);
            // if (verbose) {
            // getLog().debug("Module <" + moduleEl.getAttribute("name") + ">:" + moduleEl);
            // }
        } else {
            if (verbose) {
                getLog().debug("unresolved dependency with module-name " + module);
            }
            printXpathResult(result);
        }
    }
}

From source file:eu.europa.esig.dss.XmlDom.java

public long getCountValue(final String xPath, final Object... params) {

    String xpathString = format(xPath, params);
    try {//from  ww w . ja  va  2 s . co m

        XPathExpression xPathExpression = createXPathExpression(xpathString);
        Double number = (Double) xPathExpression.evaluate(rootElement, XPathConstants.NUMBER);
        return number.intValue();
    } catch (XPathExpressionException e) {

        throw new RuntimeException(e);
    }
}

From source file:com.hygenics.parser.ManualReplacement.java

private void transform() {
    log.info("Transforming");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    for (String fpath : fpaths) {
        log.info("FILE: " + fpath);
        try {/*from  w  w  w. ja  v  a  2s  . co  m*/
            // TRANSFORM
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(fpath));
            Node root = doc.getFirstChild();
            XPathFactory xfactory = XPathFactory.newInstance();
            XPath xpath = xfactory.newXPath();
            String database = null;
            String path = "//transformation/connection";

            log.info("Removing");
            for (String dbname : remove) {
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                if (conn != null) {
                    root.removeChild(conn);
                }
            }

            log.info("Transforming");
            for (String key : databaseAttributes.keySet()) {
                database = key;
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);

                if (conn != null) {
                    if (remove.contains(key)) {
                        root.removeChild(conn);
                    } else {
                        Map<String, String> attrs = databaseAttributes.get(database);
                        NodeList nl = conn.getChildNodes();
                        Set<String> keys = databaseAttributes.get(key).keySet();

                        for (int i = 0; i < nl.getLength(); i++) {
                            org.w3c.dom.Node n = nl.item(i);

                            if (keys.contains(n.getNodeName().trim())) {
                                n.setNodeValue(attrs.get(n.getNodeName()));
                            }
                        }
                    }
                }

                if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) {
                    log.info("Logging Manipulation");
                    log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null
                            ? "Removing Logging Data"
                            : "Adding Logging data");
                    String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table",
                            "step-log-table", "metrics-log-table" };
                    for (String section : sections) {
                        log.info("Changing Settings for " + section);
                        xepr = xpath.compile("//" + section + "/field/enabled");
                        NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET);
                        log.info("Nodes Found: " + Integer.toString(nodes.getLength()));
                        for (int i = 0; i < nodes.getLength(); i++) {
                            if (!this.log_to_table) {
                                nodes.item(i).setNodeValue("N");
                            } else {
                                nodes.item(i).setNodeValue("Y");
                            }
                        }

                        for (String nodeName : new String[] { "schema", "connection", "table",
                                "size_limit_lines", "interval", "timeout_days" }) {
                            if (!this.log_to_table) {
                                log.info("Changing Settings for Node: " + nodeName);
                                xepr = xpath.compile("//" + section + "/" + nodeName);
                                Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                                if (node != null) {
                                    if (!this.log_to_table) {
                                        node.setNodeValue(null);
                                    } else if (this.loggingTables.containsKey(section)
                                            && this.loggingTables.get(section).containsKey(nodeName)) {
                                        node.setNodeValue(this.loggingTables.get(section).get(nodeName));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // SET MAIN CONNECTION
            if (mainConnection != null) {
                XPathExpression xepr = xpath.compile(path);
                NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of
                // org.w3c it is
                // actually a NodeList
                for (int i = 0; i < conns.getLength(); i++) {
                    if (!conns.item(i).hasChildNodes()) {// only connection
                        // elements
                        // without child
                        // nodes have
                        // text content
                        conns.item(i).setNodeValue(mainConnection);
                    }
                }
            }

            if (this.replacements != null) {
                for (String key : this.replacements.keySet()) {
                    XPathExpression xepr = xpath.compile(key);
                    Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                    if (node != null) {
                        for (String attrVal : this.replacements.get(key).keySet()) {
                            log.info("Replacing Information at " + key + "at " + attrVal);
                            log.info("Replacement Will Be: "
                                    + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));

                            if (attrVal.toLowerCase().trim().equals("text")) {
                                node.setNodeValue(
                                        StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));
                                if (node.getNodeValue() == null) {
                                    node.setTextContent(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                }

                            } else {
                                NamedNodeMap nattrs = node.getAttributes();
                                Node n = nattrs.getNamedItem(attrVal);
                                if (n != null) {
                                    n.setNodeValue(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                } else {
                                    log.warn("Attribute Not Found " + attrVal);
                                }
                            }
                        }
                    } else {
                        log.warn("Node not found for " + key);
                    }
                }
            }

            // WRITE TO FILE
            log.info("Writing to File");
            TransformerFactory tfact = TransformerFactory.newInstance();
            Transformer transformer = tfact.newTransformer();
            DOMSource source = new DOMSource(doc);
            try (FileOutputStream stream = new FileOutputStream(new File(fpath))) {
                StreamResult result = new StreamResult(stream);
                transformer.transform(source, result);
                stream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:android.databinding.tool.store.LayoutFileParser.java

private File stripFileAndGetOriginal(File xml, String binderId)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    L.d("parsing resource file %s", xml.getAbsolutePath());
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(xml);
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    final XPathExpression commentElementExpr = xPath
            .compile("//comment()[starts-with(., \" From: file:\")][last()]");
    final NodeList commentElementNodes = (NodeList) commentElementExpr.evaluate(doc, XPathConstants.NODESET);
    L.d("comment element nodes count %s", commentElementNodes.getLength());
    if (commentElementNodes.getLength() == 0) {
        L.d("cannot find comment element to find the actual file");
        return null;
    }/*from www .  j  a va  2  s  . c o m*/
    final Node first = commentElementNodes.item(0);
    String actualFilePath = first.getNodeValue().substring(" From:".length()).trim();
    L.d("actual file to parse: %s", actualFilePath);
    File actualFile = urlToFile(new java.net.URL(actualFilePath));
    if (!actualFile.canRead()) {
        L.d("cannot find original, skipping. %s", actualFile.getAbsolutePath());
        return null;
    }

    // now if file has any binding expressions, find and delete them
    // TODO we should rely on namespace to avoid parsing file twice
    boolean changed = isBindingLayout(doc, xPath);
    if (changed) {
        stripBindingTags(xml, binderId);
    }
    return actualFile;
}

From source file:de.codesourcery.jasm16.ide.ProjectConfiguration.java

private Element getElement(XPathExpression expr, Document doc) throws XPathExpressionException {
    return (Element) expr.evaluate(doc, XPathConstants.NODE);
}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Returns abbreviated journal name/*  w  ww  . ja  v a  2 s  . com*/
 * @param doc article xml
 * @return abbreviated journal name
 */
public String getJournalAbbreviation(Document doc) {
    String journalAbbrev = "";

    if (doc == null) {
        return journalAbbrev;
    }

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

        XPathExpression expr = xpath.compile("//journal-meta/journal-id[@journal-id-type='nlm-ta']");
        Object resultObj = expr.evaluate(doc, XPathConstants.NODE);
        Node resultNode = (Node) resultObj;
        if (resultNode != null) {
            journalAbbrev = resultNode.getTextContent();
        }
    } catch (Exception e) {
        log.error("Error occurred while getting abbreviated journal name.", e);
    }

    return journalAbbrev;
}