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:com.alvexcore.repo.masterdata.getConstraintWork.java

protected List<Map<String, String>> getRestXmlMasterData(NodeRef source) throws Exception {
    NodeService nodeService = serviceRegistry.getNodeService();
    String url = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_REST_URL);
    String rootXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_ROOT_QUERY);
    String labelXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_LABEL);
    String valueXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_VALUE);
    String caching = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_REST_CACHE_MODE);

    // Standard of reading a XML file
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*  w  w  w.ja v  a2s. co  m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(url);

    // Create a XPathFactory
    XPathFactory xFactory = XPathFactory.newInstance();

    // Create a XPath object
    XPath xpath = xFactory.newXPath();

    // Compile the XPath expression
    XPathExpression setExpr = xpath.compile(rootXPath);
    XPathExpression valueExpr = xpath.compile(valueXPath);
    XPathExpression labelExpr = xpath.compile(labelXPath);

    // Run the query and get a nodeset
    Object result = setExpr.evaluate(doc, XPathConstants.NODESET);

    // Cast the result to a list
    NodeList nodes = (NodeList) result;
    List<Map<String, String>> res = new ArrayList<Map<String, String>>();
    for (int i = 0; i < nodes.getLength(); i++) {
        String value = (String) valueExpr.evaluate(nodes.item(i), XPathConstants.STRING);
        String label = (String) labelExpr.evaluate(nodes.item(i), XPathConstants.STRING);
        HashMap<String, String> resItem = new HashMap<String, String>();
        resItem.put("ref", "");
        resItem.put("value", value);
        resItem.put("label", label);
        res.add(resItem);
    }
    return res;
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

private String getValue(String response, String xPathString)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    try (InputStream xmlStream = new ByteArrayInputStream(response.getBytes())) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlStream);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile(xPathString);
        Node tokenNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
        if (tokenNode != null) {
            return tokenNode.getTextContent();
        }/*  ww  w .  j a v a2 s  . com*/
    }
    return null;
}

From source file:cc.siara.csv_ml_demo.MultiLevelCSVSwingDemo.java

/**
 * Evaluates given XPath from Input box against Document generated by
 * parsing csv_ml in input box and sets value or node list to output box.
 *///  ww w  .  ja  va  2  s  . com
private void processXPath() {
    XPath xpath = XPathFactory.newInstance().newXPath();
    Document doc = parseInputToDOM();
    if (doc == null)
        return;
    StringBuffer out_str = new StringBuffer();
    try {
        XPathExpression expr = xpath.compile(tfXPath.getText());
        try {
            Document outDoc = Util.parseXMLToDOM("<output></output>");
            Element rootElement = outDoc.getDocumentElement();
            NodeList ret = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < ret.getLength(); i++) {
                Object o = ret.item(i);
                if (o instanceof String) {
                    out_str.append(o);
                } else if (o instanceof Node) {
                    Node n = (Node) o;
                    short nt = n.getNodeType();
                    switch (nt) {
                    case Node.TEXT_NODE:
                    case Node.ATTRIBUTE_NODE:
                    case Node.CDATA_SECTION_NODE: // Only one value gets
                                                  // evaluated?
                        if (out_str.length() > 0)
                            out_str.append(',');
                        if (nt == Node.ATTRIBUTE_NODE)
                            out_str.append(n.getNodeValue());
                        else
                            out_str.append(n.getTextContent());
                        break;
                    case Node.ELEMENT_NODE:
                        rootElement.appendChild(outDoc.importNode(n, true));
                        break;
                    }
                }
            }
            if (out_str.length() > 0) {
                rootElement.setTextContent(out_str.toString());
                out_str.setLength(0);
            }
            out_str.append(Util.docToString(outDoc, true));
        } catch (Exception e) {
            // Thrown most likely because the given XPath evaluates to a
            // string
            out_str.append(expr.evaluate(doc));
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    taOutput.setText(out_str.toString());
    tfOutputSize.setText(String.valueOf(out_str.length()));
}

From source file:com.connexta.arbitro.ctx.xacml3.XACML3EvaluationCtx.java

private Set<String> getChildXPaths(Node root, String xPath) {

    Set<String> xPaths = new HashSet<String>();
    NamespaceContext namespaceContext = null;

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

    if (namespaceContext == null) {

        //see if the request root is in a namespace
        String namespace = null;//ww w. j  a v a 2s  . co  m
        if (root != null) {
            namespace = root.getNamespaceURI();
        }
        // name spaces are used, so we need to lookup the correct
        // prefix to use in the search string
        NamedNodeMap namedNodeMap = root.getAttributes();

        Map<String, String> nsMap = new HashMap<String, String>();
        if (namedNodeMap != null) {
            for (int i = 0; i < namedNodeMap.getLength(); i++) {
                Node n = namedNodeMap.item(i);
                // we found the matching namespace, so get the prefix
                // and then break out
                String prefix = DOMHelper.getLocalName(n);
                String nodeValue = n.getNodeValue();
                nsMap.put(prefix, nodeValue);
            }
        }

        // if there is not any namespace is defined for content element, default XACML request
        //  name space would be there.
        if (XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace)
                || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace)
                || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)) {
            nsMap.put("xacml", namespace);
        }

        namespaceContext = new DefaultNamespaceContext(nsMap);
    }

    xpath.setNamespaceContext(namespaceContext);

    try {
        XPathExpression expression = xpath.compile(xPath);
        NodeList matches = (NodeList) expression.evaluate(root, XPathConstants.NODESET);
        if (matches != null && matches.getLength() > 0) {

            for (int i = 0; i < matches.getLength(); i++) {
                String text = null;
                Node node = matches.item(i);
                short nodeType = node.getNodeType();

                // see if this is straight text, or a node with data under
                // it and then get the values accordingly
                if ((nodeType == Node.CDATA_SECTION_NODE) || (nodeType == Node.COMMENT_NODE)
                        || (nodeType == Node.TEXT_NODE) || (nodeType == Node.ATTRIBUTE_NODE)) {
                    // there is no child to this node
                    text = node.getNodeValue();
                } else {

                    // the data is in a child node
                    text = "/" + DOMHelper.getLocalName(node);
                }
                String newXPath = '(' + xPath + ")[" + (i + 1) + ']';
                xPaths.add(newXPath);
            }
        }
    } catch (Exception e) {
        // TODO
    }

    return xPaths;
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

public List<UniverseQueryPrompt> getParameters(String token, String queryId) throws UniverseException {
    HttpGet httpGet = new HttpGet(String.format("%s%s%s%s", apiUrl, "/sl/v1/queries/", queryId, "/parameters"));
    setHeaders(httpGet, token);/*from   ww w . j  a v a 2s.c  om*/
    HttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get parameters): Request failed\n",
                    EntityUtils.toString(response.getEntity())));
        }
    } catch (IOException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get parameters): Request failed", ExceptionUtils.getStackTrace(e)));
    }

    try (InputStream xmlStream = response.getEntity().getContent()) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlStream);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("//parameters/parameter");
        NodeList parametersNodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        if (parametersNodes != null) {
            return parseParameters(parametersNodes);
        } else {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get parameters): Response processing failed"));
        }
    } catch (IOException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get parameters): Response processing failed",
                ExceptionUtils.getStackTrace(e)));
    } catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get parameters): Response processing failed",
                ExceptionUtils.getStackTrace(e)));
    }
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

public List<List<String>> getResults(String token, String queryId) throws UniverseException {
    HttpGet httpGet = new HttpGet(
            String.format("%s%s%s%s", apiUrl, "/sl/v1/queries/", queryId, "/data.svc/Flows0"));
    setHeaders(httpGet, token);/*w w  w  .  ja va 2s  .co m*/
    HttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new UniverseException(
                    String.format(errorMessageTemplate, "UniverseClient " + "(get results): Request failed\n",
                            EntityUtils.toString(response.getEntity())));
        }
    } catch (IOException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get results): Request failed", ExceptionUtils.getStackTrace(e)));
    }

    try (InputStream xmlStream = response.getEntity().getContent()) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlStream);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("//feed/entry/content/properties");
        NodeList resultsNodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        if (resultsNodes != null) {
            return parseResults(resultsNodes);
        } else {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get results): Response processing failed"));
        }
    } catch (IOException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get results): Request failed", ExceptionUtils.getStackTrace(e)));
    } catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get results): Response processing failed",
                ExceptionUtils.getStackTrace(e)));
    }
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

private void loadUniverses(String token, int offset, Map<String, UniverseInfo> universesMap)
        throws UniverseException {
    int limit = 50;
    HttpGet httpGet = new HttpGet(
            String.format("%s%s?offset=%s&limit=%s", apiUrl, "/sl/v1/universes", offset, limit));
    setHeaders(httpGet, token);/* ww w .  jav a  2s.  co m*/
    HttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
    } catch (Exception e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get universes): Request failed", ExceptionUtils.getStackTrace(e)));
    }
    if (response != null && response.getStatusLine().getStatusCode() == 200) {
        try (InputStream xmlStream = response.getEntity().getContent()) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(xmlStream);
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("//universe");
            NodeList universesNodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            if (universesNodes != null) {
                int count = universesNodes.getLength();
                for (int i = 0; i < count; i++) {
                    Node universe = universesNodes.item(i);
                    if (universe.hasChildNodes()) {
                        NodeList universeParameters = universe.getChildNodes();
                        int parapetersCount = universeParameters.getLength();
                        String id = null;
                        String name = null;
                        String type = null;
                        for (int j = 0; j < parapetersCount; j++) {
                            Node parameterNode = universeParameters.item(j);
                            parameterNode.getNodeName();
                            if (parameterNode.getNodeType() == Node.ELEMENT_NODE) {
                                if (parameterNode.getNodeName().equalsIgnoreCase("id")) {
                                    id = parameterNode.getTextContent();
                                    continue;
                                }
                                if (parameterNode.getNodeName().equalsIgnoreCase("name")) {
                                    name = parameterNode.getTextContent();
                                    continue;
                                }
                                if (parameterNode.getNodeName().equalsIgnoreCase("type")) {
                                    type = parameterNode.getTextContent();
                                    continue;
                                }
                            }
                        }
                        if (StringUtils.isNotBlank(type)) {
                            name = name.replaceAll(String.format("\\.%s$", type), StringUtils.EMPTY);
                        }
                        universesMap.put(name, new UniverseInfo(id, name, type));
                    }
                }
                if (count == limit) {
                    offset += limit;
                    loadUniverses(token, offset, universesMap);
                }
            }
        } catch (IOException e) {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get universes): Response processing failed",
                    ExceptionUtils.getStackTrace(e)));
        } catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get universes): Response processing failed",
                    ExceptionUtils.getStackTrace(e)));
        }
    }
}

From source file:fmiquerytest.Coordinates.java

private static List<String> getValueList(Document doc, XPath xpath, String expression) {
    List<String> list = new ArrayList<>();
    try {//w w w  . j  a  va 2 s  .  c  o  m
        //create XPathExpression object
        XPathExpression expr = xpath.compile(expression);
        //evaluate expression result on XML document
        NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

        //            NodeList nodeList = doc.getElementsByTagName("*");
        //            for (int i = 0; i < nodeList.getLength(); i++) {
        //                Node node = nodeList.item(i);
        //                if (node.getNodeType() == Node.ELEMENT_NODE) {
        //                    // do something with the current element
        //                    System.out.println(node.getNodeName());
        //                }
        //            }

        for (int i = 0; i < nodes.getLength(); i++) {
            //System.out.println(nodes.item(i).getTextContent().trim());
            list.add(nodes.item(i).getTextContent().trim());
        }
    } catch (XPathExpressionException ex) {
        Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return list;
}

From source file:eu.fbk.dh.tint.tokenizer.ItalianTokenizer.java

public ItalianTokenizer(@Nullable File settingFile) {
        Trie.TrieBuilder builder = Trie.builder().removeOverlaps();

        InputStream stream = null;
        if (settingFile != null) {
            try {
                stream = new FileInputStream(settingFile);
            } catch (FileNotFoundException e) {
                // continue
            }//w  w w .ja  va 2s  .  co  m
        }
        if (stream == null) {
            stream = this.getClass().getResourceAsStream("/token-settings.xml");
        }

        logger.trace("Loading model");
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();

            XPathExpression expr;
            NodeList nl;
            int count;

            Document doc = dBuilder.parse(stream);
            doc.getDocumentElement().normalize();

            // Normalization rules
            expr = xpath.compile("/settings/normalization/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String hexCode = element.getAttribute("hexcode");
                String content = element.getTextContent();

                // Bad: need fix
                if (content.equals("`")) {
                    content = "'";
                }

                int num = Integer.parseInt(hexCode, 16);
                if (content.length() == 0) {
                    continue;
                }
                normalizedChars.put(num, content);
            }
            logger.info("Loaded {} normalization rules", normalizedChars.size());

            // end sentence chars
            expr = xpath.compile("/settings/sentenceSplitting/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String charID = element.getAttribute("id");
                sentenceChars.add(Integer.parseInt(charID));
            }
            logger.info("Loaded {} sentence splitting rules", sentenceChars.size());

            // splitting rules
            expr = xpath.compile("/settings/tokenSplitting/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String charID = element.getAttribute("id");
                splittingChars.add(Integer.parseInt(charID));
            }
            logger.info("Loaded {} token splitting rules", splittingChars.size());

            // expressions
            expr = xpath.compile("/settings/expressions/expression");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            StringBuilder b = new StringBuilder();
            b.append("(");
            boolean first = true;
            count = 0;
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String regExp = element.getAttribute("find");
                boolean merge = PropertiesUtils.getBoolean(element.getAttribute("merge"), true);
                Integer group = PropertiesUtils.getInteger(element.getAttribute("get"), 1);
                if (merge) {
                    if (!first) {
                        b.append("|");
                    }
                    b.append(regExp);
                    count++;
                    first = false;
                } else {
                    expressions.put(Pattern.compile(regExp), group);
                    count++;
                }
            }
            b.append(")");
            expressions.put(Pattern.compile(b.toString()), 1);
            logger.info("Loaded {} regular expressions", count);

            // abbreviations
            expr = xpath.compile("/settings/abbreviations/abbreviation");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            count = 0;
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                String abbr = item.getTextContent();
                abbr = getString(tokenArray(abbr));
                builder.addKeyword(" " + abbr + " ");
                count++;
            }
            logger.info("Loaded {} abbreviations", count);

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

        trie = builder.build();
    }

From source file:betullam.xmlmodifier.XMLmodifier.java

private boolean isModsMets(Document xmlDoc) {
    boolean isMets = true;
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression;

    // Check for the goobi mods extension. If we find it, the XML document is not a classical MODS/METS document:
    try {//www  .  j av a 2s  . co m
        xPathExpression = xPath.compile("/mets/dmdSec/mdWrap/xmlData/mods/extension/goobi");
        NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDoc, XPathConstants.NODESET);
        if (nodeList.getLength() > 0) {
            isMets = false;
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return isMets;
}