Example usage for javax.xml.xpath XPath evaluate

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java

/**
 * Returns the query result as a <code>Node</code> or <code>null</code> if the
 * xpath expression doesn't yield a resulting node.
 * //from w ww.  j  av a2 s.co  m
 * @param node
 *          the context node
 * @param xpathExpression
 *          the xpath expression
 * @param processor
 *          the xpath processor
 * @return the selected node
 */
public static Node select(Node node, String xpathExpression, XPath processor) {
    if (node == null || processor == null) {
        return null;
    }
    try {
        Node result = (Node) processor.evaluate(xpathExpression, node, XPathConstants.NODE);

        // If we are running in test mode, we may neglect namespaces
        if (result == null) {
            NamespaceContext ctx = processor.getNamespaceContext();
            if (ctx instanceof XPathNamespaceContext && ((XPathNamespaceContext) ctx).isTest()) {
                if (xpathExpression.matches("(.*)[a-zA-Z0-9]+\\:[a-zA-Z0-9]+(.*)")) {
                    String xpNs = xpathExpression.replaceAll("[a-zA-Z0-9]+\\:", "");
                    result = (Node) processor.evaluate(xpNs, node, XPathConstants.NODE);
                }
            }
        }
        return result;
    } catch (XPathExpressionException e) {
        logger.warn("Error when selecting '{}' from {}", new Object[] { xpathExpression, node, e });
        return null;
    }
}

From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java

/**
 * Returns the query result as a <code>NodeList</code> or <code>null</code> if
 * the xpath expression doesn't yield a result set.
 * //from w  w  w  . j  ava  2s  . com
 * @param node
 *          the context node
 * @param xpathExpression
 *          the xpath expression
 * @param processor
 *          the xpath processor
 * @return the selected node
 */
public static NodeList selectList(Node node, String xpathExpression, XPath processor) {
    if (node == null || processor == null) {
        return null;
    }
    try {
        NodeList result = (NodeList) processor.evaluate(xpathExpression, node, XPathConstants.NODESET);

        // If we are running in test mode, we may neglect namespaces
        if (result == null || result.getLength() == 0) {
            NamespaceContext ctx = processor.getNamespaceContext();
            if (ctx instanceof XPathNamespaceContext && ((XPathNamespaceContext) ctx).isTest()) {
                if (xpathExpression.matches("(.*)[a-zA-Z0-9]+\\:[a-zA-Z0-9]+(.*)")) {
                    String xpNs = xpathExpression.replaceAll("[a-zA-Z0-9]+\\:", "");
                    result = (NodeList) processor.evaluate(xpNs, node, XPathConstants.NODESET);
                }
            }
        }
        return result;

    } catch (XPathExpressionException e) {
        logger.warn("Error when selecting '{}' from {}", new Object[] { xpathExpression, node, e });
        return null;
    }
}

From source file:uk.ac.ebi.intact.dataexchange.psimi.solr.util.IntactSolrUtils.java

public static SchemaInfo retrieveSchemaInfo(SolrServer solrServer) throws IOException {
    SchemaInfo schemaInfo = new SchemaInfo();

    if (solrServer instanceof CommonsHttpSolrServer) {
        final CommonsHttpSolrServer solr = (CommonsHttpSolrServer) solrServer;

        final String url = solr.getBaseURL() + "/admin/file/?file=schema.xml";
        final GetMethod method = new GetMethod(url);
        final int code = solr.getHttpClient().executeMethod(method);

        XPath xpath = XPathFactory.newInstance().newXPath();
        String expression = "/schema/fields/field";
        InputStream stream = method.getResponseBodyAsStream();
        InputSource inputSource = new InputSource(stream);

        try {/*from ww w.jav  a  2s .  co  m*/
            NodeList nodes = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);

            for (int i = 0; i < nodes.getLength(); i++) {
                final String fieldName = nodes.item(i).getAttributes().getNamedItem("name").getNodeValue();
                schemaInfo.addFieldName(fieldName);
            }

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } finally {
            stream.close();
        }

    } else if (solrServer instanceof HttpSolrServer) {
        final HttpSolrServer solr = (HttpSolrServer) solrServer;

        final String url = solr.getBaseURL() + "/admin/file/?file=schema.xml";
        final HttpUriRequest method = new HttpGet(url);
        final HttpResponse response = solr.getHttpClient().execute(method);

        XPath xpath = XPathFactory.newInstance().newXPath();
        String expression = "/schema/fields/field";
        InputStream stream = response.getEntity().getContent();
        InputSource inputSource = new InputSource(stream);

        try {
            NodeList nodes = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);

            for (int i = 0; i < nodes.getLength(); i++) {
                final String fieldName = nodes.item(i).getAttributes().getNamedItem("name").getNodeValue();
                schemaInfo.addFieldName(fieldName);
            }

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } finally {
            stream.close();
        }

    } else {
        throw new IllegalArgumentException(
                "Cannot get schema for SolrServer with class: " + solrServer.getClass().getName());
    }

    return schemaInfo;
}

From source file:com.twentyn.patentExtractor.PatentDocumentFeatures.java

/**
 * Extracts sentence nodes from a POS-tagger XML document.  These sentences are intended to provide some notion of
 * locality for identified chemical entities.
 *
 * @param docBuilder A document builder to use when producing single-sentence XML documents.
 * @param doc        The POS-tagger XML document from which to extract sentences.
 * @return A list of single-sentence documents.
 * @throws ParserConfigurationException/* w w  w.  j ava2s . c  o  m*/
 * @throws XPathExpressionException
 */
private static List<Document> findSentences(DocumentBuilder docBuilder, Document doc)
        throws ParserConfigurationException, XPathExpressionException {
    if (doc != null) {
        // TODO: is there a more efficient yet still safe way to do this?
        XPath xpath = Util.getXPathFactory().newXPath();
        // TODO: get rid of this inline xpath compilation, run during setup.
        NodeList nodes = (NodeList) xpath.evaluate(SENTENCE_PATH, doc, XPathConstants.NODESET);

        List<Document> docList = new ArrayList<>(nodes.getLength());
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);

            /* With help from:
             * http://examples.javacodegeeks.com/core-java/xml/dom/copy-nodes-subtree-from-one-dom-document-to-another/ */
            org.w3c.dom.Document newDoc = docBuilder.newDocument();
            Element rootElement = newDoc.createElement(SENTENCE_DOC_HEADER);
            Node newNode = newDoc.importNode(n, true);
            rootElement.appendChild(newNode);
            newDoc.appendChild(rootElement);
            docList.add(newDoc);
        }
        return docList;
    } else {
        // TODO: log here.
        return new ArrayList<>(0);
    }
}

From source file:com.streak.logging.analysis.AnalysisUtility.java

public static List<String> fetchCloudStorageUris(String bucketName, String startKey, String endKey,
        HttpRequestFactory requestFactory) throws IOException {
    List<String> result = new ArrayList<String>();

    String bucketUri = "http://commondatastorage.googleapis.com/" + bucketName;
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(bucketUri + "?marker=" + startKey));
    HttpResponse response = request.execute();

    try {/*from   www  .j a va 2 s. com*/
        Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getContent());
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xPath.evaluate("//Contents/Key/text()", responseDoc,
                XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            String key = nodes.item(i).getNodeValue();
            if (key.compareTo(endKey) >= 0) {
                break;
            }
            if (key.endsWith(".schema.json")) {
                continue;
            }
            result.add("gs://" + bucketName + "/" + key);
        }
    } catch (SAXException e) {
        throw new IOException("Error parsing cloud storage response", e);
    } catch (ParserConfigurationException e) {
        throw new IOException("Error configuring cloud storage parser", e);
    } catch (XPathExpressionException e) {
        throw new IOException("Error finding keys", e);
    }

    return result;
}

From source file:com.autentia.tnt.xml.UtilitiesXPath.java

public static List<List> ExtractReport(String folderReport) {
    List reportList = null;//from  w w  w.ja  v a2 s  . co m
    List filesList = null;
    try {
        reportList = new ArrayList<List>();
        filesList = UtilitiesXML.filesFromFolder(folderReport);

        for (int i = 0; i < filesList.size(); i++) {
            List<List> tmp = new ArrayList<List>();
            Document doc = UtilitiesXML.file2Document(filesList.get(i).toString());
            XPath xpath = XPathFactory.newInstance().newXPath();

            if (log.isDebugEnabled()) {
                log.debug("\n>> Nombre del informe: ");
            }

            expression = "/jasperReport[@name]";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            nameReport = UtilitiesXML.printAttribute("name", nodes);
            nameReport.add(UtilitiesXML.cleanReport(filesList.get(i).toString()));

            if (log.isDebugEnabled()) {
                log.debug(nameReport.toString());
                log.debug("Parametros: ");
            }

            expression = "/jasperReport/parameter[@name]";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersName = UtilitiesXML.printAttribute("name", nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersName.toString());
                log.debug("Clases: ");
            }

            expression = "/jasperReport/paremeter[@class]";
            nameClass = UtilitiesXML.printAttribute("class", nodes);

            if (log.isDebugEnabled()) {
                log.debug(nameClass.toString());
                log.debug("Descripcion de Parametros: ");
            }

            expression = "/jasperReport/parameter/parameterDescription";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersDescription = UtilitiesXML.nodes2String(nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersDescription.toString());
                log.debug("Valores por defectos: ");
            }

            expression = "/jasperReport/parameter/defaultValueExpression";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersDefaultValue = UtilitiesXML.nodes2String(nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersDefaultValue.toString());
                log.debug("\n------------------------------------");
            }

            tmp.add(nameReport);
            tmp.add(parametersName);
            tmp.add(nameClass);
            tmp.add(parametersDescription);
            tmp.add(parametersDefaultValue);
            reportList.add(tmp);

        }
        log.debug("Lista de informes:" + reportList);

    } catch (Exception e) {
        log.error(e);
    }
    return reportList;

}

From source file:org.nira.wso2.nexus.ComponentVersion.java

/**
 * Loads the List of all the Dependencies in the DependencyManagement from  the root
 * pom.xml/* ww  w  . jav  a 2  s  .c  o m*/
 *
 * @param pomFilePath : The path to the root pom.xml
 * @throws ComponentException
 */
private static void getDependencyManagement(String pomFilePath) throws ComponentException {
    String nodeName, nodeValue;
    DependencyComponent dependencyComponent;
    NodeList dependenciesList = Utils.getNodeListFromXPath(pomFilePath, Constants.DEPENDENCY_MANAGEMENT_XPATH);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    try {
        for (int i = 0; i < dependenciesList.getLength(); ++i) {

            Node dependency = dependenciesList.item(i);
            if (dependency != null && dependency.getNodeType() == Node.ELEMENT_NODE) {
                NodeList nodes = (NodeList) xpath.evaluate(Constants.SELECT_ALL, dependency,
                        XPathConstants.NODESET);
                dependencyComponent = new DependencyComponent();
                for (int j = 0; j < nodes.getLength(); ++j) {
                    nodeName = nodes.item(j).getNodeName();
                    nodeValue = nodes.item(j).getTextContent();
                    if (nodeValue == null) {
                        throw new ComponentException("Dependency value is NULL for " + nodeName + "!");
                    }
                    switch (nodeName) {
                    case Constants.GROUPID:
                        dependencyComponent.setGroupId(nodeValue);
                        break;
                    case Constants.ARTIFACTID:
                        dependencyComponent.setArtifactId(nodeValue);
                        break;
                    case Constants.VERSION:
                        if (Constants.PROJECT_VERSION.equalsIgnoreCase(nodeValue)) {
                            break;
                        }
                        //ToDo: Check for values like the one below:
                        //<version.tomcat>7.0.59</version.tomcat>
                        //<orbit.version.tomcat>${version.tomcat}.wso2v3</orbit.version.tomcat>
                        while (!Character.isDigit(nodeValue.charAt(0))) {
                            nodeValue = nodeValue.substring(2, nodeValue.length() - 1);
                            nodeValue = dependencyComponentVersions.get(nodeValue);
                            if (nodeValue == null) {
                                throw new ComponentException("Dependency Version cannot be NULL!");
                            }
                        }
                        dependencyComponent.setVersion(nodeValue);
                        break;
                    }
                }
                if (dependencyComponent.getGroupId() != null && dependencyComponent.getArtifactId() != null
                        && dependencyComponent.getVersion() != null) {
                    getLatestComponentVersion(dependencyComponent);
                    dependencyComponentList.add(dependencyComponent);
                }
            }
        }
    } catch (XPathExpressionException e) {
        throw new ComponentException("XPath Exception when retrieving Dependency Components!", e);
    }
    Collections.sort(dependencyComponentList, DependencyComponent.GroupIdArifactIdComparator);
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param documentDom/*from ww w .  ja  v  a  2s .c o m*/
 * @param xpath
 * @return
 * @throws XPathExpressionException
 */
static Node getWordParaForXPath(Document documentDom, String xpath) throws XPathExpressionException {
    XPathFactory xpathFactory = DomUtil.getXPathFactory();
    XPath xpathObj = xpathFactory.newXPath();
    xpathObj.setNamespaceContext(DocxConstants.docxNamespaceContext);
    Object result = xpathObj.evaluate(xpath, documentDom, XPathConstants.NODE);
    Node node = null;
    if (result != null) {
        node = (Node) result;

    }
    return node;
}

From source file:jGPIO.DTO.java

/**
 * Tries to use lshw to detect the physical system in use.
 * /*from  w  ww. j  av a 2 s  .  co  m*/
 * @return The filename of the GPIO Definitions file.
 */
static private String autoDetectSystemFile() {
    String definitions = System.getProperty("definitions.lookup");
    if (definitions == null) {
        definitions = DEFAULT_DEFINITIONS;
    }

    File capabilitiesFile = new File(definitions);

    // If it doesn't exist, fall back to the default
    if (!capabilitiesFile.exists() && !definitions.equals(DEFAULT_DEFINITIONS)) {
        System.out.println("Could not find definitions lookup file at: " + definitions);
        System.out.println("Trying default definitions file at: " + definitions);
        capabilitiesFile = new File(DEFAULT_DEFINITIONS);
    }

    if (!capabilitiesFile.exists()) {
        System.out.println("Could not find definitions file at: " + definitions);
        return null;
    }

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    }

    // Generate the lshw output if available
    Process lshw;
    try {
        lshw = Runtime.getRuntime().exec("lshw -c bus -disable dmi -xml");
        lshw.waitFor();
    } catch (Exception e1) {
        System.out.println("Couldn't execute lshw to identify board");
        e1.printStackTrace();
        return null;
    }
    Document lshwXML = null;
    try {
        lshwXML = dBuilder.parse(lshw.getInputStream());
    } catch (IOException e1) {
        System.out.println("IO Exception running lshw");
        e1.printStackTrace();
        return null;
    } catch (SAXException e1) {
        System.out.println("Could not parse lshw output");
        e1.printStackTrace();
        return null;
    }

    XPath xp = XPathFactory.newInstance().newXPath();
    NodeList capabilities;
    try {
        capabilities = (NodeList) xp.evaluate("/list/node[@id=\"core\"]/capabilities/capability", lshwXML,
                XPathConstants.NODESET);
    } catch (XPathExpressionException e1) {
        System.out.println("Couldn't run Caoability lookup");
        e1.printStackTrace();
        return null;
    }

    Document lookupDocument = null;
    try {
        lookupDocument = dBuilder.parse(capabilitiesFile);
        String lookupID = null;

        for (int i = 0; i < capabilities.getLength(); i++) {
            Node c = capabilities.item(i);
            lookupID = c.getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Looking for: " + lookupID);
            NodeList nl = (NodeList) xp.evaluate("/lookup/capability[@id=\"" + lookupID + "\"]", lookupDocument,
                    XPathConstants.NODESET);

            if (nl.getLength() == 1) {
                definitionFile = nl.item(0).getAttributes().getNamedItem("file").getNodeValue();
                pinDefinitions = (JSONArray) new JSONParser().parse(new FileReader(definitionFile));
                return definitionFile;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:edu.cornell.mannlib.semservices.util.XMLUtils.java

/**
 * @param doc (either a Document or a Node)
 * @param expression//from  w  w w  . ja v  a 2 s . co  m
 * @return string contents
 */
public static Node getNodeWithXpath(Object obj, String expression) {
    Object root = null;
    if (obj instanceof Document) {
        Document doc = (Document) obj;
        root = doc.getDocumentElement();
    } else {
        root = (Node) obj;
    }

    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new MetadataNamespaceContext());
    Node result = null;

    try {
        result = ((Node) xpath.evaluate(expression, root, XPathConstants.NODE));
        return result;
    } catch (XPathExpressionException e) {
        logger.error("XPathExpressionException ", e);
        return null;
    }
}