Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

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

private boolean evaluateExpression(String xml, String xpathStmt) {
    Boolean result = false;/*from  ww w  .j  a  va  2  s.  c  om*/
    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
 * //from   ww  w  .j a va 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;
}

From source file:org.dawb.passerelle.common.utils.XMLUtils.java

public static Map<String, String> getVariables(final Map<?, ?> variables, final String xmlSource,
        final Map<String, String> scalarSource) throws Exception {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(false); // never forget this!
    docFactory.setValidating(false);/*from   w ww .j av  a2s.co  m*/
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = null;

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

    final Map<String, String> values = new HashMap<String, String>(variables.size());
    for (Object varName : variables.keySet()) {
        final String varValue = (String) variables.get(varName.toString());
        if (varValue == null || "".equals(varValue)) {
            values.put(varName.toString(), scalarSource.get(varName));
            continue;
        }

        if ("/".equals(varValue)) {
            values.put(varName.toString(), xmlSource);
            continue;
        }

        final XPathExpression exp = xpath.compile(varValue);
        if (doc == null)
            doc = builder.parse(new InputSource(new StringReader(xmlSource)));

        final NodeList nodeList = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
        values.put(varName.toString(), getNodeValue(nodeList));
    }

    // We allow names of variables to expand values of other variables.
    final Map<String, String> all = new HashMap<String, String>(values.size());
    all.putAll(scalarSource);
    all.putAll(values);

    final Map<String, String> ret = new HashMap<String, String>(variables.size());
    final MultiVariableExpander expander = new MultiVariableExpander();
    expander.addSource("$", all);

    // Create a substitutor with the expander
    final VariableSubstitutor substitutor = new VariableSubstitutor(expander);

    for (final String varName : values.keySet()) {

        if (!varName.contains("$")) {
            ret.put(varName, values.get(varName));
        } else {
            ret.put(substitutor.substitute(varName), values.get(varName));
        }
    }

    return ret;
}

From source file:org.dawb.passerelle.common.utils.XMLUtils.java

public static String getXPathValue(IFile file, String xPath) throws Exception {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(false); // never forget this!
    docFactory.setValidating(false);/*from   w ww.j a  v  a 2s . c o m*/
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    final XPathExpression exp = xpath.compile(xPath);

    Document doc = builder.parse(new InputSource(file.getContents()));

    final NodeList nodeList = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    return XMLUtils.getNodeValue(nodeList);
}

From source file:org.dawb.passerelle.common.utils.XMLUtils.java

public static String getXPathValue(File file, String xPath) throws Exception {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(false); // never forget this!
    docFactory.setValidating(false);/*from w w  w .  j  a v  a  2 s. c  o  m*/
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    final XPathExpression exp = xpath.compile(xPath);

    Document doc = builder.parse(new InputSource(file.getAbsolutePath()));

    final NodeList nodeList = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    return XMLUtils.getNodeValue(nodeList);
}

From source file:org.digidoc4j.impl.bdoc.report.ValidationReportTest.java

private void assertXpathHasValue(String expectedValue, String xPathExpression, String xmlInput)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xmlInput));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(xPathExpression);
    String evaluate = expr.evaluate(doc);
    assertEquals(expectedValue, evaluate);
}

From source file:org.dita.dost.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {/*w  w w . j  a va 2 s  .  c  o  m*/

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        factory.setValidating(false);

        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
    } catch (ParserConfigurationException e) {
    } catch (SAXException e) {
    } catch (IOException e) {
    } catch (XPathExpressionException e) {
    }
    return fileName.toString();
}

From source file:org.drugis.addis.util.ConvertDiabetesDatasetUtil.java

private void renameStudies() throws IOException {
    for (Study study : d_domain.getStudies()) {
        PubMedIdList pubmed = (PubMedIdList) study.getCharacteristic(BasicStudyCharacteristic.PUBMED);

        try {/*ww  w.jav  a  2  s.  c  o  m*/
            Document doc = getPubMedXML(pubmed);

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

            XPathExpression yearExpr = xpath
                    .compile("/PubmedArticleSet/PubmedArticle[1]/MedlineCitation[1]/DateCreated[1]/Year[1]");
            Object yearResults = yearExpr.evaluate(doc, XPathConstants.NODESET);

            String year = ((NodeList) yearResults).item(0).getTextContent();

            XPathExpression authorExpr = xpath.compile(
                    "/PubmedArticleSet/PubmedArticle[1]/MedlineCitation[1]/Article[1]/AuthorList[1]/Author/LastName");
            Object authorResults = authorExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList authorNodes = (NodeList) authorResults;

            List<String> authors = new ArrayList<String>();

            for (int i = 0; i < authorNodes.getLength(); i++) {
                authors.add(authorNodes.item(i).getTextContent());
            }
            String title = "";
            if (authors.size() > 2) {
                title = authors.get(0) + " et al, " + year;
            } else {
                title = StringUtils.join(authors, ", ") + ", " + year;
            }
            study.setName(title);

        } catch (Exception e) {
            continue;
        }
    }
}

From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java

/**
 * Used//ww w  . j  av a  2s .c  o  m
 * @param tenantId
 * @param itemId
 * @param itemType
 * @param dimensionXPath
 *
 * @throws Exception
 */
@Override
public Set<String> loadProfileField(Integer tenantId, String itemId, String itemType, String dimensionXPath)
        throws Exception {

    Set<String> result = new HashSet<>();

    int itemIntID = idMappingDAO.lookupOnly(itemId);

    XPathFactory xpf = XPathFactory.newInstance();

    Document doc = getProfileXMLDocument(tenantId, itemIntID, itemType);

    XPath xp = xpf.newXPath();
    NodeList nodeList = (NodeList) xp.evaluate(dimensionXPath, doc, XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        result.add(node.getTextContent());
    }

    return result;
}

From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java

/**
 * Used/*from   www. j  ava 2  s .  com*/
 * @param tenantId
 * @param itemId
 * @param itemTypeId
 * @param dimensionXPath
 * @param value
 *
 */
@Override
public synchronized boolean storeProfileField(Integer tenantId, String itemId, String itemTypeId,
        String dimensionXPath, String value) throws Exception {

    int itemIntID = idMappingDAO.lookup(itemId);

    XPathFactory xpf = XPathFactory.newInstance();

    // load and parse the profile
    Document doc = getProfileXMLDocument(tenantId, itemIntID, itemTypeId);

    // follow the XPath from bottom to top until you find the first existing path element
    XPath xp = xpf.newXPath();
    String tmpPath = dimensionXPath;
    NodeList nodeList = (NodeList) xp.evaluate(tmpPath, doc, XPathConstants.NODESET);
    if (nodeList.getLength() > 1)
        throw new MultipleProfileFieldsFoundException(nodeList.getLength() + " nodes found.");

    Node node = null;
    if (nodeList.getLength() == 1)
        nodeList.item(0).setTextContent(value);
    else {
        while (node == null) {
            tmpPath = dimensionXPath.substring(0, tmpPath.lastIndexOf("/"));
            if ("".equals(tmpPath))
                tmpPath = "/";
            node = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE);
        }
        insertElement(doc, node, dimensionXPath.substring(tmpPath.length()), value);
    }

    StringWriter writer = new StringWriter();
    Result result = new StreamResult(writer);
    trans.transform(new DOMSource(doc), result);
    writer.close();
    String xml = writer.toString();
    logger.debug(xml);
    storeProfile(tenantId, itemId, itemTypeId, xml);

    return true;
}