Example usage for javax.xml.xpath XPathConstants NODE

List of usage examples for javax.xml.xpath XPathConstants NODE

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODE.

Prototype

QName NODE

To view the source code for javax.xml.xpath XPathConstants NODE.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:org.sakaiproject.james.JamesServlet.java

protected void customizeConfig(String host, String dns1, String dns2, String smtpPort, String logDir,
        String postmasterAddress) throws JamesConfigurationException {
    String configPath = m_phoenixHome + "/apps/james/SAR-INF/config.xml";
    String environmentPath = m_phoenixHome + "/apps/james/SAR-INF/environment.xml";

    XPath xpath = XPathFactory.newInstance().newXPath();
    Document doc;/*from   ww  w  .j  ava 2s  . co  m*/

    try {
        // process config.xml first
        doc = Xml.readDocument(configPath);
        if (doc == null) {
            M_log.error("init(): James config file " + configPath + "could not be found.");
            throw new JamesConfigurationException();
        }

        if (postmasterAddress == null) {
            postmasterAddress = "postmaster@" + host;
        }

        // build a hashmap of node paths and values to set
        HashMap<String, String> nodeValues = new HashMap<String, String>();

        // WARNING!! in XPath, node-set indexes begin with 1, and NOT 0
        nodeValues.put("/config/James/servernames/servername[1]", host);
        nodeValues.put("/config/dnsserver/servers/server[2]", dns1);
        nodeValues.put("/config/dnsserver/servers/server[3]", dns2);
        nodeValues.put("/config/James/postmaster", postmasterAddress);
        nodeValues.put("/config/smtpserver/port", smtpPort);

        // loop through the hashmap, setting each value, or failing if one can't be found
        for (String nodePath : nodeValues.keySet()) {
            if (!(Boolean) xpath.evaluate(nodePath, doc, XPathConstants.BOOLEAN)) {
                if (nodePath.startsWith("/config/dnsserver/servers/server")) {
                    // add node (only if we're dealing with DNS server entries)
                    Element element = doc.createElement("server");
                    element.appendChild(doc.createTextNode(nodeValues.get(nodePath)));
                    Node parentNode = (Node) xpath.evaluate("/config/dnsserver/servers", doc,
                            XPathConstants.NODE);
                    parentNode.appendChild(element);

                } else {
                    // else, throw an exception
                    throw new JamesConfigurationException();
                }

            } else {
                // change existing node (if value != null else remove it)
                Node node = (Node) xpath.evaluate(nodePath, doc, XPathConstants.NODE);
                if (nodeValues.get(nodePath) != null) {
                    node.setTextContent(nodeValues.get(nodePath));
                } else {
                    node.getParentNode().removeChild(node);
                }
            }
        }

        M_log.debug("init(): writing James configuration to " + configPath);
        Xml.writeDocument(doc, configPath);

        // now handle environment.xml
        doc = Xml.readDocument(environmentPath);
        if (doc == null) {
            M_log.error("init(): James config file " + environmentPath + "could not be found.");
            throw new JamesConfigurationException();
        }

        String nodePath = "/server/logs/targets/file/filename";
        String nodeValue = logDir + "james";

        if (!(Boolean) xpath.evaluate(nodePath, doc, XPathConstants.BOOLEAN)) {
            M_log.error("init(): Could not find XPath '" + nodePath + "' in " + environmentPath + ".");
            throw new JamesConfigurationException();
        }
        ((Node) xpath.evaluate(nodePath, doc, XPathConstants.NODE)).setTextContent(nodeValue);

        M_log.debug("init(): writing James configuration to " + environmentPath);
        Xml.writeDocument(doc, environmentPath);
    } catch (JamesConfigurationException e) {
        throw e;
    } catch (Exception e) {
        M_log.warn("init(): An unhandled exception was encountered while configuring James: " + e.getMessage());
    }
}

From source file:org.sakaiproject.kernel.component.core.PersistenceUnitClassLoader.java

/**
 * Scans the classloader for persistence.xml files, parses the expected XML
 * and merges the results together for a unified view of the various
 * instances. The master copy is taken in entirety and only the class and
 * mapping-file entries are taken from the other copies.Well
 *
 * @param filename//from w  ww. j  a  va2 s . com
 * @return
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 * @throws XPathException
 */
private String scanPersistenceXml() throws ParserConfigurationException, IOException, SAXException,
        XPathExpressionException, TransformerException {

    String outxml = null;

    LOG.trace("scanPersistenceXML()");
    final DocumentBuilder builder = DOC_BUILDER_FACTORY.newDocumentBuilder();
    DOC_BUILDER_FACTORY.setNamespaceAware(true);

    final URL masterURL = getResource(KERNEL_PERSISTENCE_XML);
    if (masterURL == null) {
        LOG.error("Can't find " + KERNEL_PERSISTENCE_XML);
    } else {
        if (debug)
            LOG.debug(String.format(">>>> master persistence.xml: %s", masterURL));
        final Document masterDocument = builder.parse(masterURL.toExternalForm());

        // collect the class and mappings together so they can be added to the
        // document in groups rather than strewn about.
        final HashSet<String> mappings = new HashSet<String>();
        final HashSet<String> classes = new HashSet<String>();

        // collect mapping-file and class nodes from non-master persistence.xml's
        for (final URL url : findXMLs(PERSISTENCE_XML)) {
            LOG.debug(String.format(">>>> other persistence.xml: %s", url));
            final Document document = builder.parse(url.toExternalForm());
            // collect the mappings
            accumulateNodeText((NodeList) XPATH_MAPPING_TEXT.evaluate(document, XPathConstants.NODESET),
                    mappings);

            // collect the classes
            accumulateNodeText((NodeList) XPATH_CLASS_TEXT.evaluate(document, XPathConstants.NODESET), classes);
        }

        // build the final document
        final Node puNode = (Node) XPATH_PU_NODE.evaluate(masterDocument, XPathConstants.NODE);
        if (puNode == null) {
            LOG.error("No persistence unit found!");
            LOG.error("PERSISTENCE.XML\n" + readFile(masterURL));
        } else {
            NodeList nodes = puNode.getChildNodes();
            int mappingRank = tagOrder.get(EntityType.MAPPING.getType());
            int classRank = tagOrder.get(EntityType.CLASS.getType());
            boolean mappingsInserted = false;
            boolean classesInserted = false;
            if (nodes.getLength() > 0) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    if (tagOrder.containsKey(node.getNodeName())) {
                        int rank = tagOrder.get(node.getNodeName());
                        // insert the mapping-file nodes
                        if (!mappingsInserted && rank > mappingRank) {
                            insertBefore(mappings, masterDocument, puNode, node, EntityType.MAPPING);
                            mappingsInserted = true;
                        }
                        // insert the mapping-file nodes
                        if (!classesInserted && rank > classRank) {
                            insertBefore(classes, masterDocument, puNode, node, EntityType.CLASS);
                            classesInserted = true;
                        }
                    }
                }
            } else {
                appendChildren(masterDocument, puNode, nodes, EntityType.MAPPING);
                appendChildren(masterDocument, puNode, nodes, EntityType.CLASS);
            }
        }

        outxml = toString(masterDocument);
    }

    return outxml;
}

From source file:org.sejda.core.context.XmlConfigurationStrategy.java

/**
 * Given a document, search for the notification strategy configuration and returns the configured strategy or the default one if nothing is configured.
 * /*from   w w  w.j a v a2 s  . c  o m*/
 * @param document
 * @return the class extending {@link NotificationStrategy} configured.
 * @throws XPathExpressionException
 */
private Class<? extends NotificationStrategy> getNotificationStrategy(Document document)
        throws XPathExpressionException {
    Node node = (Node) xpathFactory.newXPath().evaluate(ROOT_NODE + NOTIFICATION_XPATH, document,
            XPathConstants.NODE);
    if (nullSafeGetBooleanAttribute(node, NOTIFICATION_ASYNC_ATTRIBUTENAME)) {
        return AsyncNotificationStrategy.class;
    }
    return SyncNotificationStrategy.class;
}

From source file:org.sejda.core.context.XmlConfigurationStrategy.java

private boolean getValidation(Document document) throws XPathExpressionException {
    Node node = (Node) xpathFactory.newXPath().evaluate(ROOT_NODE, document, XPathConstants.NODE);
    return nullSafeGetBooleanAttribute(node, VALIDATION_ATTRIBUTENAME);
}

From source file:org.sejda.core.context.XmlConfigurationStrategy.java

private boolean getIgnoreXmlConfig(Document document) throws XPathExpressionException {
    Node node = (Node) xpathFactory.newXPath().evaluate(ROOT_NODE, document, XPathConstants.NODE);
    return nullSafeGetBooleanAttribute(node, IGNORE_XML_CONFIG_VALIDATION_ATTRIBUTENAME, true);
}

From source file:org.silverpeas.SilverpeasSettings.xml.transform.XPathTransformer.java

/**
 * Find the matching node in the specified DOM tree.
 * @param xpathExpression the XPATh expression.
 * @param doc the DOM tree/*from  w w w.ja v  a 2  s  . co m*/
 * @return the Node matching the XPATH expression - null otherwise.
 */
public Node getMatchingNode(String xpathExpression, Node doc) {
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        return (Node) xpath.evaluate(xpathExpression, doc, XPathConstants.NODE);
    } catch (XPathExpressionException ex) {
        Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE,
                "Incorrect expression " + xpathExpression, ex);
    } catch (Exception ex) {
        Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE,
                "Incorrect expression " + xpathExpression, ex);
    }
    return null;
}

From source file:org.socraticgrid.xmlCommon.XpathHelper.java

public static Node performXpathQuery(String sourceXml, String xpathQuery, NamespaceContext namespaceContext)
        throws XPathExpressionException {
    javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    javax.xml.xpath.XPath xpath = factory.newXPath();

    if (namespaceContext != null) {
        xpath.setNamespaceContext(namespaceContext);
    }//w w  w  . j av a 2  s .c o  m

    InputSource inputSource = new InputSource(new ByteArrayInputStream(sourceXml.getBytes()));

    log.debug("perform xpath query (query='" + xpathQuery + "'");
    Node result = null;
    if (XmlUtfHelper.isUtf16(sourceXml)) {
        try {
            result = (Node) xpath.evaluate(xpathQuery, inputSource, XPathConstants.NODE);
        } catch (Exception ex) {
            // Exception may be due to the encoding of the message being incorrect.
            // retry using UTF-8
            log.warn("failed to perform xpath query - retrying with UTF-8");
            sourceXml = XmlUtfHelper.convertToUtf8(sourceXml);
            result = performXpathQuery(sourceXml, xpathQuery, namespaceContext);
        }
    } else {
        result = (Node) xpath.evaluate(xpathQuery, inputSource, XPathConstants.NODE);
    }
    log.debug("xpath query complete [result?=" + result + "]");
    return result;
}

From source file:org.socraticgrid.xmlCommon.XpathHelper.java

public static Node performXpathQuery(Element sourceElement, String xpathQuery,
        NamespaceContext namespaceContext) throws XPathExpressionException {
    javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    javax.xml.xpath.XPath xpath = factory.newXPath();

    if (namespaceContext != null) {
        xpath.setNamespaceContext(namespaceContext);
    }/*www. j  ava  2  s  .c o m*/

    log.debug("About to perform xpath query (query='" + xpathQuery + "'");
    Node result = (Node) xpath.evaluate(xpathQuery, sourceElement, XPathConstants.NODE);
    return result;
}

From source file:org.sonar.api.utils.XpathParser.java

public Node executeXPathNode(Node node, String xPathExpression) {
    return (Node) executeXPath(node, XPathConstants.NODE, xPathExpression);
}

From source file:org.sonatype.nexus.testsuite.obr.ObrITSupport.java

protected void assertObrPath(final String repositoryId, final String expectedRemoteUrl,
        final String expectedObrPath) throws Exception {
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    final DocumentBuilder db = dbf.newDocumentBuilder();
    final Document doc = db.parse(new File(nexus().getWorkDirectory(), "etc/nexus.xml"));

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

    final Node url = (Node) xpath.evaluate(
            "/nexusConfiguration/repositories/repository[id='" + repositoryId + "']/remoteStorage/url", doc,
            XPathConstants.NODE);
    assertThat(url, is(notNullValue()));
    assertThat(url.getTextContent(), is(expectedRemoteUrl));

    final Node obrPath = (Node) xpath.evaluate("/nexusConfiguration/repositories/repository[id='" + repositoryId
            + "']/externalConfiguration/obrPath", doc, XPathConstants.NODE);
    assertThat(obrPath, is(notNullValue()));
    assertThat(obrPath.getTextContent(), is(expectedObrPath));
}