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.asqatasun.processing.ProcessRemarkServiceImpl.java

/**
 * This methods search the line where the current node is present in
 * the source code//from   www.java 2 s.com
 * @param node
 * @return
 */
private int getNodeIndex(Node node) {
    try {
        XPathExpression xPathExpression = xpath.compile("//" + node.getNodeName().toUpperCase());
        Object result = xPathExpression.evaluate(document, XPathConstants.NODESET);
        NodeList nodeList = (NodeList) result;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node current = nodeList.item(i);
            if (current.equals(node)) {
                return i;
            }
        }
    } catch (XPathExpressionException ex) {
        LOGGER.error("Error occured while searching index of a node " + ex.getMessage());
        throw new RuntimeException(ex);
    }
    return -1;
}

From source file:org.asqatasun.processor.DOMHandlerImpl.java

/**
 * http://www.ibm.com/developerworks/library/x-javaxpathapi.html
 *
 * @param expr/*from   ww  w. j  a  v a  2 s. c  o m*/
 * @return
 */
@Override
public DOMHandler xPathSelectNodeSet(String expr) {
    try {
        XPathExpression xPathExpression = xpath.compile(expr);
        Object result = xPathExpression.evaluate(document, XPathConstants.NODESET);
        NodeList nodeList = (NodeList) result;
        for (int j = 0; j < nodeList.getLength(); j++) {
            selectedElementList.add(nodeList.item(j));
        }
    } catch (XPathExpressionException ex) {
        throw new RuntimeException(ex);
    }
    return this;
}

From source file:org.asqatasun.processor.DOMHandlerImpl.java

/**
 * @deprecated Kept for backward compatibility.
 * @param expr//from   www  .j  av a2 s. co  m
 * @return
 */
@Override
@Deprecated
public TestSolution checkEachWithXpath(String expr) {
    Collection<TestSolution> resultSet = new ArrayList<TestSolution>();
    for (Node node : selectedElementList) {
        TestSolution tempResult = TestSolution.PASSED;
        try {
            XPathExpression xPathExpression = xpath.compile(expr);
            Boolean check = (Boolean) xPathExpression.evaluate(node, XPathConstants.BOOLEAN);
            if (!check.booleanValue()) {
                tempResult = TestSolution.FAILED;
                // addSourceCodeRemark(result, node,
                // "wrong value, does not respect xpath expression : " +
                // expr, node.getNodeValue());
            }
        } catch (XPathExpressionException ex) {
            LOGGER.error(ex.getMessage() + " occured requesting " + expr + " on " + ssp.getURI());
            throw new RuntimeException(ex);
        }
        resultSet.add(tempResult);
    }
    return RuleHelper.synthesizeTestSolutionCollection(resultSet);
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

protected NodeList evaluateXPath(Document doc, String expression) throws SamlR2SignatureException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(getNamespaceContext());

    NodeList nl;//  w w  w  .  j a v a  2  s.c  o  m
    try {
        XPathExpression expr = xpath.compile(expression);

        nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new SamlR2SignatureException(e);
    }

    return nl;
}

From source file:org.automagic.deps.doctor.Utils.java

public static Optional<Node> getNode(String xpath, Node parent) {
    try {/*  ww w  .  j  a  va 2 s.  co  m*/
        XPath xPath = XPATH_FACTORY.get().newXPath();
        XPathExpression expression = xPath.compile(xpath);
        Node node = (Node) expression.evaluate(parent, XPathConstants.NODE);
        if (node == null) {
            return Optional.absent();
        }
        return Optional.of(node);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.bbaw.telota.ediarum.ReadRegister.java

/**
 * Der Konstruktor liest das Dokument der URL mit den benannten Knoten aus und konstruiert den Eintrag und die Id fr jeden Knoten.
 * @param indexURI Die URL zur Registerdatei
 * @param node Der X-Path-Ausdruck fr die Knoten der einzelnen Registereintrge
 * @param eintragExp Der Ausdruck um einen Registereintrag zu konstruieren. Er setzt sich aus Strings in "", Attributen beginnend mit @,
 *  Elementen mit / oder // und aus X-Path-Ausdrcken beginnend mit . zusammen. Die einzelnen Teile werden mit + verbunden.
 * @param idExp Der Ausdruck um die ID fr einen Registereintrag zu konstruieren. Er setzt sich wie eintragExp zusammen.
 * @throws AuthorOperationException// w w  w  . j  av  a2  s  . c  o m
 */
public ReadRegister(String indexURI, String node, String eintragExp, String idExp) {

    try {
        // Das neue Dokument wird vorbereitet.
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        // Wenn es sich um eine URL mit Authentifizierung handelt, ..
        InputStream is;
        if (indexURI.indexOf('@') > -1) {
            // .. werden die Verbindungsdaten gelesen ..
            String authString = indexURI.substring(indexURI.indexOf("://") + 3, indexURI.indexOf('@'));
            String webPage = indexURI.substring(0, indexURI.indexOf("://") + 3)
                    + indexURI.substring(indexURI.indexOf('@') + 1);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);

            // .. und eine Verbindung mit Login geffnet.
            URL url = new URL(webPage);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            is = urlConnection.getInputStream();
        } else {
            // Im anderen Fall wird direkt eine Verbindung geffnet.
            URL url = new URL(indexURI);
            URLConnection urlConnection = url.openConnection();
            is = urlConnection.getInputStream();
        }

        // Dann wird die Datei gelesen.
        InputSource inputSource = new InputSource(is);
        Document indexDoc = builder.parse(inputSource);
        // Die xPath-Routinen werden vorbereitet.
        XPath xpath = XPathFactory.newInstance().newXPath();
        // Das XPath-Query wird definiert.
        XPathExpression expr = xpath.compile(node);

        // Die Resultate werden ausgelesen..
        Object result = expr.evaluate(indexDoc, XPathConstants.NODESET);
        NodeList registerNodes = (NodeList) result;

        // .. dann werden fr die Eintrge und IDs entsprechend lange Arrays angelegt.
        eintrag = new String[registerNodes.getLength()];
        id = new String[registerNodes.getLength()];

        // Die Ausdrcke fr die Eintrge ..
        String[] eintragExpression = (eintragExp).split("[+]");
        for (int i = 0; i < eintragExpression.length; i++) {
            eintragExpression[i] = eintragExpression[i].trim();
        }
        // .. und IDs werden in einzelne Glieder geteilt. 
        String[] idExpression = (idExp).split("[+]");
        for (int i = 0; i < idExpression.length; i++) {
            idExpression[i] = idExpression[i].trim();
        }

        // Fr jeden Knoten ..
        for (int i = 0; i < registerNodes.getLength(); i++) {
            Element currentElement = (Element) registerNodes.item(i);
            // .. wird der Eintrag konstruiert.
            eintrag[i] = "";
            // Dazu werden die Glieder des entsprechenden Ausdrucks interpretiert.
            for (int j = 0; j < eintragExpression.length; j++) {
                try {
                    // Jedes Glied kann entweder als Attribut, ..
                    if (eintragExpression[j].startsWith("@")) {
                        String attributeName = eintragExpression[j].substring(1);
                        eintrag[i] += currentElement.getAttribute(attributeName);
                    }
                    // .. als String, ..
                    if (eintragExpression[j].startsWith("\"") && eintragExpression[j].endsWith("\"")) {
                        String stringexpression = eintragExpression[j].substring(1,
                                eintragExpression[j].length() - 1);
                        eintrag[i] += stringexpression;
                    }
                    // .. als spter zu verarbeitetende Variable, ..
                    if (eintragExpression[j].startsWith("$")) {
                        String stringexpression = eintragExpression[j];
                        eintrag[i] += stringexpression;
                    }
                    // **
                    // .. als nachkommendes Element ..
                    if (eintragExpression[j].startsWith("//")) {
                        // .. (was direkt gelesen werden kann und schnell geht, ..
                        String elementName = eintragExpression[j].substring(2);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            eintrag[i] += currentElement.getElementsByTagName(elementName).item(0)
                                    .getTextContent();
                        } else {
                            // .. oder welches ber eine X-Path-Abfrage gelesen werden kann und lange dauert), ..
                            XPathExpression queryExpr = xpath.compile("." + eintragExpression[j]);
                            NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                    XPathConstants.NODESET);
                            if (elementNodes.getLength() > 0
                                    && elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                                eintrag[i] += elementNodes.item(0).getTextContent();
                            }
                        }
                        // .. als direktes Kindelement (was schnell geht) ..
                    } else if (eintragExpression[j].startsWith("/")) {
                        String elementName = eintragExpression[j].substring(1);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            eintrag[i] += currentElement.getElementsByTagName(elementName).item(0)
                                    .getTextContent();
                        }
                    }
                    // .. oder als X-Path-Ausdruck (was sehr lange dauert) verstanden werden.
                    if (eintragExpression[j].startsWith(".")) {
                        XPathExpression queryExpr = xpath.compile(eintragExpression[j]);
                        NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                XPathConstants.NODESET);
                        if (elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                            eintrag[i] += elementNodes.item(0).getTextContent();
                        }
                    }
                } catch (ArrayIndexOutOfBoundsException e) {
                }
            }

            // Genauso wird die ID konstruiert.
            id[i] = "";
            // Dazu werden die Glieder des entsprechenden Ausdrucks interpretiert.
            for (int j = 0; j < idExpression.length; j++) {
                try {
                    // Jedes Glied kann entweder als Attribut, ..
                    if (idExpression[j].startsWith("@")) {
                        String attributeName = idExpression[j].substring(1);
                        id[i] += currentElement.getAttribute(attributeName);
                    }
                    // .. als String, ..
                    if (idExpression[j].startsWith("\"") && idExpression[j].endsWith("\"")) {
                        String stringexpression = idExpression[j].substring(1, idExpression[j].length() - 1);
                        id[i] += stringexpression;
                    }
                    // .. als spter zu verarbeitetende Variable, ..
                    if (idExpression[j].startsWith("$")) {
                        String stringexpression = idExpression[j];
                        id[i] += stringexpression;
                    }
                    // .. als nachkommendes Element ..
                    if (idExpression[j].startsWith("//")) {
                        // .. (was direkt gelesen werden kann und schnell geht, ..
                        String elementName = idExpression[j].substring(2);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            id[i] += currentElement.getElementsByTagName(elementName).item(0).getTextContent();
                        } else {
                            // .. oder welches ber eine X-Path-Abfrage gelesen werden kann und lange dauert), ..
                            XPathExpression queryExpr = xpath.compile("." + idExpression[j]);
                            NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                    XPathConstants.NODESET);
                            if (elementNodes.getLength() > 0
                                    && elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                                id[i] += elementNodes.item(0).getTextContent();
                            }
                        }
                        // .. als direktes Kindelement (was schnell geht) ..
                    } else if (idExpression[j].startsWith("/")) {
                        String elementName = idExpression[j].substring(1);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            id[i] += currentElement.getElementsByTagName(elementName).item(0).getTextContent();
                        }
                    }
                    // .. oder als X-Path-Ausdruck (was sehr lange dauert) verstanden werden.
                    if (idExpression[j].startsWith(".")) {
                        XPathExpression queryExpr = xpath.compile(idExpression[j]);
                        NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                XPathConstants.NODESET);
                        if (elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                            id[i] += elementNodes.item(0).getTextContent();
                        }
                    }
                } catch (ArrayIndexOutOfBoundsException e) {
                }
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (DOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:org.codice.alliance.catalog.transformer.mgmp.MgmpTransformer.java

private void addMetacardDataQuality(MetacardImpl metacard) {

    try (InputStream inputStream = getSourceInputStream()) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false);
        try {//from   w w w  . jav a 2s.  c  o m
            domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        } catch (ParserConfigurationException e) {
            LOGGER.debug("Unable to set features on document builder.", e);
        }
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(inputStream);

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

        List<String> dataQualityList = new ArrayList<>();
        for (String string : MgmpConstants.DATA_QUALITY_LIST) {

            XPathExpression dataExpression = xPath.compile(string);
            NodeList dataList = (NodeList) dataExpression.evaluate(document, XPathConstants.NODESET);

            for (int i = 0; i < dataList.getLength(); i++) {
                String dataQualityName = null;
                String resultValue = null;

                NodeList children = dataList.item(i).getChildNodes();
                for (int c = 0; c < children.getLength(); c++) {
                    Node node = children.item(c);
                    String name = node.getNodeName();

                    switch (name) {
                    case MgmpConstants.RESULT:
                        NodeList childNodes = node.getChildNodes();
                        for (int x = 0; x < childNodes.getLength(); x++) {
                            Node resultNode = childNodes.item(x);
                            if (StringUtils.isEmpty(resultValue)) {
                                resultValue = getDataQualityResultValue(resultNode);
                            }
                        }
                        break;
                    case MgmpConstants.NAME_OF_MEASURE:
                        if (StringUtils.isEmpty(dataQualityName)) {
                            dataQualityName = node.getTextContent().trim();
                        }
                        break;

                    default:
                        break;
                    }
                }

                if (StringUtils.isNotEmpty(dataQualityName) && StringUtils.isNotEmpty(resultValue)) {
                    dataQualityList.add(dataQualityName + " : " + resultValue);
                }
            }
        }

        if (CollectionUtils.isNotEmpty(dataQualityList)) {
            metacard.setAttribute(Isr.DATA_QUALITY, (Serializable) dataQualityList);
        }
    } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
        LOGGER.debug("Unable to parse Data Quality elements.  Metacard Data Quality will not be set.", e);
        return;
    }
}

From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java

private String retrieveXmlValue(String xml, String xpathStmt) {
    String result = null;//from w  w w.j a v a 2 s  .co  m
    Document document = createDocument(xml);
    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xpath = xFactory.newXPath();

    try {
        XPathExpression expr = xpath.compile(xpathStmt);
        result = (String) expr.evaluate(document, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        LOGGER.warn("Error processing XPath statement on policy XML.");
    }
    return result;
}

From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java

private boolean evaluateExpression(String xml, String xpathStmt) {
    Boolean result = false;// w  ww .j a v  a 2  s. c o m
    Document document = createDocument(xml);

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

    try {
        XPathExpression expr = xpath.compile("boolean(" + xpathStmt + ")");
        result = (Boolean) expr.evaluate(document, XPathConstants.BOOLEAN);
    } catch (XPathExpressionException e) {
        LOGGER.warn("Error processing XPath statement on policy XML.", e);
    }
    return result;
}

From source file:org.craftercms.cstudio.share.forms.impl.FormServiceBaseImpl.java

/**
 * merge the instance data with the document
 * // w  w  w .jav a 2 s.c o  m
 * @param xformDocument
 * @param model
 * @return
 */
protected Document mergeInstanceDataWithForm(Document xformDocument, Map<String, Document> model,
        final String namespace) {

    Document retDocument = xformDocument;

    if (model != null) {

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

        try {

            NamespaceContext cstudio = new NamespaceContext() {

                public String getNamespaceURI(String prefix) {

                    String uri = "";
                    if (prefix.equals(namespace))
                        uri = "http://www.w3.org/2002/xforms";

                    return uri;
                }

                @SuppressWarnings("unchecked")
                public Iterator getPrefixes(String val) {

                    return null;
                }

                public String getPrefix(String uri) {

                    return null;
                }

            };

            xPath.setNamespaceContext(cstudio);
            XPathExpression xPathExpression = xPath.compile("//" + namespace + ":instance");

            // DOMSource source = new DOMSource(xformDocument);
            // StringWriter xmlAsWriter = new StringWriter();
            // StreamResult result = new StreamResult(xmlAsWriter);
            // TransformerFactory.newInstance().newTransformer().transform(source,
            // result);
            StringReader xmlReader = new StringReader(DomUtils.xmlToString(xformDocument));
            InputSource documentAsInputSource = new InputSource(xmlReader);

            // using implementation here, see article
            // http://onjava.com/pub/a/onjava/2005/01/12/xpath.html
            DTMNodeList nodes = (DTMNodeList) xPathExpression.evaluate(documentAsInputSource,
                    XPathConstants.NODESET);

            int nodeCount = nodes.getLength();

            for (int i = 0; i < nodeCount; i++) {
                Element currentNode = (Element) nodes.item(i);
                String modelId = currentNode.getAttribute("id");

                Document documentToInsert = model.get(modelId);

                if (documentToInsert != null) {

                    Element importedModelRoot = documentToInsert.getDocumentElement();

                    retDocument = currentNode.getOwnerDocument();
                    Node importedModel = retDocument.importNode(importedModelRoot, true);

                    currentNode.appendChild(importedModel);
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    return retDocument;
}