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:nl.nn.adapterframework.util.XmlUtils.java

public static Double evaluateXPathNumber(String input, String xpathExpr)
        throws DomBuilderException, XPathExpressionException {
    String msg = XmlUtils.removeNamespaces(input);

    Document doc = buildDomDocument(msg, true, true);
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(xpathExpr);
    Object result = xPathExpression.evaluate(doc, XPathConstants.NUMBER);
    return (Double) result;
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

public static Map<String, String> evaluateXPathNodeSet(String input, String xpathExpr, String keyElement,
        String valueElement) throws DomBuilderException, XPathExpressionException {
    String msg = XmlUtils.removeNamespaces(input);

    Map<String, String> m = new HashMap<String, String>();
    Document doc = buildDomDocument(msg, true, true);
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(xpathExpr);
    Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            String key = getChildTagAsString(element, keyElement);
            String value = getChildTagAsString(element, valueElement);
            m.put(key, value);//from w ww  . j  a  v  a  2s.  co m
        }
    }
    if (m != null && m.size() > 0) {
        return m;
    }
    return null;
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

public static Collection<String> evaluateXPathNodeSet(String input, String xpathExpr, String xpathExpr2)
        throws DomBuilderException, XPathExpressionException {
    String msg = XmlUtils.removeNamespaces(input);

    Collection<String> c = new LinkedList<String>();
    Document doc = buildDomDocument(msg, true, true);
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(xpathExpr);
    Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            XPathExpression xPathExpression2 = xPath.compile(xpathExpr2);
            Object result2 = xPathExpression2.evaluate(element, XPathConstants.STRING);
            c.add((String) result2);
        }//  w  w w .j a  va 2  s.  c om
    }
    if (c != null && c.size() > 0) {
        return c;
    }
    return null;
}

From source file:org.alfresco.repo.content.metadata.xml.XPathMetadataExtracter.java

private Serializable getStringValue(Document document, XPathExpression xpathExpression)
        throws XPathExpressionException {
    String value = (String) xpathExpression.evaluate(document, XPathConstants.STRING);
    // Done//w  w  w . j  a va 2s . c  o m
    return value;
}

From source file:org.alfresco.repo.content.metadata.xml.XPathMetadataExtracter.java

private Serializable getNodeSetValue(Document document, XPathExpression xpathExpression)
        throws XPathExpressionException {
    // Execute it
    NodeList nodeList = null;//from w  ww  . j a  v  a2  s  .  c  om
    try {
        nodeList = (NodeList) xpathExpression.evaluate(document, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        // Expression didn't evaluate to a nodelist
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to evaluate expression and return a NODESET: " + xpathExpression);
        }
        throw e;
    }
    // Convert the value
    Serializable value = null;
    int nodeCount = nodeList.getLength();
    if (nodeCount == 0) {
        // No result
    } else if (nodeCount == 1) {
        Node node = nodeList.item(0);
        // Get the string value
        value = node.getTextContent();
    } else {
        // Make a collection of the values
        ArrayList<String> stringValues = new ArrayList<String>(5);
        for (int i = 0; i < nodeCount; i++) {
            stringValues.add(nodeList.item(i).getTextContent());
        }
        value = stringValues;
    }
    // Done
    return value;
}

From source file:org.alfresco.repo.dictionary.CustomModelServiceImpl.java

/**
 * Finds the {@code module} element within the Share persisted-extension
 * XML file and then writes the XML fragment as the content of a newly created node.
 *
 * @param modelName the model name//from   w w  w.  j a v  a2s  .  c  om
 * @return the created nodeRef
 */
protected NodeRef createCustomModelShareExtModuleRef(final String modelName) {
    final String moduleId = "CMM_" + modelName;

    final NodeRef formNodeRef = getShareExtModule();
    ContentReader reader = contentService.getReader(formNodeRef, ContentModel.PROP_CONTENT);

    if (reader == null) {
        throw new CustomModelException("cmm.service.download.share_ext_node_read_err");
    }

    InputStream in = reader.getContentInputStream();
    Node moduleIdXmlNode = null;
    try {
        Document document = XMLUtil.parse(in); // the stream will be closed

        final String xpathQuery = "/extension//modules//module//id[.= '" + moduleId + "']";

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expression = xPath.compile(xpathQuery);

        moduleIdXmlNode = (Node) expression.evaluate(document, XPathConstants.NODE);
    } catch (Exception ex) {
        throw new CustomModelException("cmm.service.download.share_ext_file_parse_err", ex);
    }

    if (moduleIdXmlNode == null) {
        throw new CustomModelException("cmm.service.download.share_ext_module_not_found",
                new Object[] { moduleId });
    }

    final File moduleFile = TempFileProvider.createTempFile(moduleId, ".xml");
    try {
        XMLUtil.print(moduleIdXmlNode.getParentNode(), moduleFile);
    } catch (IOException error) {
        throw new CustomModelException("cmm.service.download.share_ext_write_err", new Object[] { moduleId },
                error);
    }

    return doInTransaction(MSG_DOWNLOAD_CREATE_SHARE_EXT_ERR, true, new RetryingTransactionCallback<NodeRef>() {
        @Override
        public NodeRef execute() throws Exception {
            final NodeRef nodeRef = createDownloadTypeNode(moduleId + SHARE_EXT_MODULE_SUFFIX);
            ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(MimetypeMap.MIMETYPE_XML);
            writer.setEncoding("UTF-8");
            writer.putContent(moduleFile);

            return nodeRef;
        }
    });
}

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

/**
 * Returns a list of ref nodes from the ref-list of the DOM.
 *
 * @param doc DOM representation of the XML
 * @return NodeList of ref elements//from  www. ja  va2s.  com
 * @throws XPathExpressionException
 */
private NodeList getReferenceNodes(Document doc) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//back/ref-list[title='References']/ref");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList refList = (NodeList) result;

    if (refList.getLength() == 0) {
        expr = xpath.compile("//back/ref-list/ref");
        result = expr.evaluate(doc, XPathConstants.NODESET);
        refList = (NodeList) result;
    }
    return refList;
}

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

/**
 * Get references for a given article/*from w w  w .  j  a  v a  2s  .  co m*/
 *
 * @param doc article xml
 * @return references
 */
public ArrayList<CitationReference> getReferences(Document doc) {
    ArrayList<CitationReference> list = new ArrayList<CitationReference>();

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

    try {
        NodeList refList = getReferenceNodes(doc);

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

        XPathExpression typeExpr = xpath.compile("//citation | //nlm-citation | //element-citation");
        XPathExpression titleExpr = xpath.compile("//article-title");
        XPathExpression authorsExpr = xpath.compile("//person-group[@person-group-type='author']/name");
        XPathExpression journalExpr = xpath.compile("//source");
        XPathExpression volumeExpr = xpath.compile("//volume");
        XPathExpression numberExpr = xpath.compile("//label");
        XPathExpression fPageExpr = xpath.compile("//fpage");
        XPathExpression lPageExpr = xpath.compile("//lpage");
        XPathExpression yearExpr = xpath.compile("//year");
        XPathExpression publisherExpr = xpath.compile("//publisher-name");

        for (int i = 0; i < refList.getLength(); i++) {

            Node refNode = refList.item(i);
            CitationReference citation = new CitationReference();

            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(refNode);

            // citation type
            Object resultObj = typeExpr.evaluate(df, XPathConstants.NODE);
            Node resultNode = (Node) resultObj;
            if (resultNode != null) {
                String citationType = getCitationType(resultNode);
                if (citationType != null) {
                    citation.setCitationType(citationType);
                }
            }

            // title
            resultObj = titleExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setTitle(resultNode.getTextContent());
            }

            // authors
            resultObj = authorsExpr.evaluate(df, XPathConstants.NODESET);
            NodeList resultNodeList = (NodeList) resultObj;
            ArrayList<String> authors = new ArrayList<String>();
            for (int j = 0; j < resultNodeList.getLength(); j++) {
                Node nameNode = resultNodeList.item(j);
                NodeList namePartList = nameNode.getChildNodes();
                String surName = "";
                String givenName = "";
                for (int k = 0; k < namePartList.getLength(); k++) {
                    Node namePartNode = namePartList.item(k);
                    if (namePartNode.getNodeName().equals("surname")) {
                        surName = namePartNode.getTextContent();
                    } else if (namePartNode.getNodeName().equals("given-names")) {
                        givenName = namePartNode.getTextContent();
                    }
                }
                authors.add(givenName + " " + surName);
            }

            citation.setAuthors(authors);

            // journal title
            resultObj = journalExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setJournalTitle(resultNode.getTextContent());
            }

            // volume
            resultObj = volumeExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setVolume(resultNode.getTextContent());
            }

            // citation number
            resultObj = numberExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setNumber(resultNode.getTextContent());
            }

            // citation pages
            String firstPage = null;
            String lastPage = null;
            resultObj = fPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                firstPage = resultNode.getTextContent();
            }

            resultObj = lPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                lastPage = resultNode.getTextContent();
            }

            if (firstPage != null) {
                if (lastPage != null) {
                    citation.setPages(firstPage + "-" + lastPage);
                } else {
                    citation.setPages(firstPage);
                }
            }

            // citation year
            resultObj = yearExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setYear(resultNode.getTextContent());
            }

            // citation publisher
            resultObj = publisherExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setPublisher(resultNode.getTextContent());
            }

            list.add(citation);
        }

    } catch (Exception e) {
        log.error("Error occurred while gathering the citation references.", e);
    }

    return list;

}

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

/**
 * Decorates the citation elements of the XML DOM with extra information from the citedArticle table in the DB. An
 * extraCitationInfo element is appended to each citation element.  It will contain between one and two attributes
 * with the extra info: citedArticleID, the DB primary key, and doi, the DOI string, if it exists.
 *
 * @param doc           DOM of the XML/*from   w w  w .jav a  2 s  . co  m*/
 * @param citedArticles List of CitedArticle persistent objects
 * @return modified DOM
 * @throws ApplicationException
 */
private Document addExtraCitationInfo(Document doc, List<CitedArticle> citedArticles)
        throws ApplicationException {
    if (citedArticles.isEmpty()) {
        return doc; // This happens in some unit tests.
    }
    try {
        NodeList referenceList = getReferenceNodes(doc);

        // If sortOrder on citedArticle has duplicate value, you will get below error.Ideally it should not happen
        // but since sortOrder is not unique it may be possible to update that field from backend to have duplicate value
        // Now index is on sortOrder(article.hbm.xml), index will be only on one of those of duplicate value and
        // hence citedArticle will have less count then the xml.
        if (referenceList.getLength() != citedArticles.size()) {
            throw new ApplicationException(String.format("Article has %d citedArticles but %d references",
                    citedArticles.size(), referenceList.getLength()));
        }
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression citationExpr = xpath
                .compile("./citation|./nlm-citation|./element-citation|./mixed-citation");
        for (int i = 0; i < referenceList.getLength(); i++) {
            Node referenceNode = referenceList.item(i);
            Node citationNode = (Node) citationExpr.evaluate(referenceNode, XPathConstants.NODE);
            CitedArticle citedArticle = citedArticles.get(i);
            if (citationNode != null && "journal".equals(getCitationType(citationNode))
                    && citedArticleIsValid(citedArticle)) {
                Element extraInfo = doc.createElement("extraCitationInfo");
                setExtraCitationInfo(extraInfo, citedArticle);
                citationNode.appendChild(extraInfo);
            }
        }
    } catch (XPathExpressionException xpee) {
        throw new ApplicationException(xpee);
    }

    return doc;
}

From source file:org.apache.airavata.gfac.core.GFacUtils.java

public static List<Element> getElementList(Document doc, String expression) throws XPathExpressionException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression expr = xPath.compile(expression);
    NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    List<Element> elementList = new ArrayList<Element>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node item = nodeList.item(i);
        if (item instanceof Element) {
            elementList.add((Element) item);
        }/*ww w. ja  v  a 2s.c  o m*/
    }
    return elementList;
}