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:com.espertech.esper.client.ConfigurationParser.java

private static void handleXMLDOM(String name, Configuration configuration, Element xmldomElement) {
    String rootElementName = getRequiredAttribute(xmldomElement, "root-element-name");
    String rootElementNamespace = getOptionalAttribute(xmldomElement, "root-element-namespace");
    String schemaResource = getOptionalAttribute(xmldomElement, "schema-resource");
    String schemaText = getOptionalAttribute(xmldomElement, "schema-text");
    String defaultNamespace = getOptionalAttribute(xmldomElement, "default-namespace");
    String resolvePropertiesAbsoluteStr = getOptionalAttribute(xmldomElement,
            "xpath-resolve-properties-absolute");
    String propertyExprXPathStr = getOptionalAttribute(xmldomElement, "xpath-property-expr");
    String eventSenderChecksRootStr = getOptionalAttribute(xmldomElement, "event-sender-validates-root");
    String xpathFunctionResolverClass = getOptionalAttribute(xmldomElement, "xpath-function-resolver");
    String xpathVariableResolverClass = getOptionalAttribute(xmldomElement, "xpath-variable-resolver");
    String autoFragmentStr = getOptionalAttribute(xmldomElement, "auto-fragment");
    String startTimestampProperty = getOptionalAttribute(xmldomElement, "start-timestamp-property-name");
    String endTimestampProperty = getOptionalAttribute(xmldomElement, "end-timestamp-property-name");

    ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();
    xmlDOMEventTypeDesc.setRootElementName(rootElementName);
    xmlDOMEventTypeDesc.setSchemaResource(schemaResource);
    xmlDOMEventTypeDesc.setSchemaText(schemaText);
    xmlDOMEventTypeDesc.setRootElementNamespace(rootElementNamespace);
    xmlDOMEventTypeDesc.setDefaultNamespace(defaultNamespace);
    xmlDOMEventTypeDesc.setXPathFunctionResolver(xpathFunctionResolverClass);
    xmlDOMEventTypeDesc.setXPathVariableResolver(xpathVariableResolverClass);
    xmlDOMEventTypeDesc.setStartTimestampPropertyName(startTimestampProperty);
    xmlDOMEventTypeDesc.setEndTimestampPropertyName(endTimestampProperty);
    if (resolvePropertiesAbsoluteStr != null) {
        xmlDOMEventTypeDesc/*w w  w . ja v a2 s.  c  o  m*/
                .setXPathResolvePropertiesAbsolute(Boolean.parseBoolean(resolvePropertiesAbsoluteStr));
    }
    if (propertyExprXPathStr != null) {
        xmlDOMEventTypeDesc.setXPathPropertyExpr(Boolean.parseBoolean(propertyExprXPathStr));
    }
    if (eventSenderChecksRootStr != null) {
        xmlDOMEventTypeDesc.setEventSenderValidatesRoot(Boolean.parseBoolean(eventSenderChecksRootStr));
    }
    if (autoFragmentStr != null) {
        xmlDOMEventTypeDesc.setAutoFragment(Boolean.parseBoolean(autoFragmentStr));
    }
    configuration.addEventType(name, xmlDOMEventTypeDesc);

    DOMElementIterator propertyNodeIterator = new DOMElementIterator(xmldomElement.getChildNodes());
    while (propertyNodeIterator.hasNext()) {
        Element propertyElement = propertyNodeIterator.next();
        if (propertyElement.getNodeName().equals("namespace-prefix")) {
            String prefix = getRequiredAttribute(propertyElement, "prefix");
            String namespace = getRequiredAttribute(propertyElement, "namespace");
            xmlDOMEventTypeDesc.addNamespacePrefix(prefix, namespace);
        }
        if (propertyElement.getNodeName().equals("xpath-property")) {
            String propertyName = getRequiredAttribute(propertyElement, "property-name");
            String xPath = getRequiredAttribute(propertyElement, "xpath");
            String propertyType = getRequiredAttribute(propertyElement, "type");
            QName xpathConstantType;
            if (propertyType.toUpperCase().equals("NUMBER")) {
                xpathConstantType = XPathConstants.NUMBER;
            } else if (propertyType.toUpperCase().equals("STRING")) {
                xpathConstantType = XPathConstants.STRING;
            } else if (propertyType.toUpperCase().equals("BOOLEAN")) {
                xpathConstantType = XPathConstants.BOOLEAN;
            } else if (propertyType.toUpperCase().equals("NODE")) {
                xpathConstantType = XPathConstants.NODE;
            } else if (propertyType.toUpperCase().equals("NODESET")) {
                xpathConstantType = XPathConstants.NODESET;
            } else {
                throw new IllegalArgumentException("Invalid xpath property type for property '" + propertyName
                        + "' and type '" + propertyType + '\'');
            }

            String castToClass = null;
            if (propertyElement.getAttributes().getNamedItem("cast") != null) {
                castToClass = propertyElement.getAttributes().getNamedItem("cast").getTextContent();
            }

            String optionaleventTypeName = null;
            if (propertyElement.getAttributes().getNamedItem("event-type-name") != null) {
                optionaleventTypeName = propertyElement.getAttributes().getNamedItem("event-type-name")
                        .getTextContent();
            }

            if (optionaleventTypeName != null) {
                xmlDOMEventTypeDesc.addXPathPropertyFragment(propertyName, xPath, xpathConstantType,
                        optionaleventTypeName);
            } else {
                xmlDOMEventTypeDesc.addXPathProperty(propertyName, xPath, xpathConstantType, castToClass);
            }
        }
    }
}

From source file:edu.lternet.pasta.datapackagemanager.LevelOneEMLFactory.java

/**
 * Returns the dataset element node contained in
 * this EML document.//www.j a  v a 2 s . c o m
 * 
 * @return  the dataset element Node object
 */
private Node getDatasetNode(Document emlDocument) {
    Node node = null;

    try {
        XPath xPath = XPathFactory.newInstance().newXPath();
        node = (Node) xPath.evaluate("//dataset", emlDocument, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new IllegalStateException(e);
    }

    return node;
}

From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java

/**
 * Parses a stagingRepositories element to obtain the list of open stages.
 * /*from  www  .  j  a v a  2s.  c  om*/
 * @param doc the stagingRepositories to parse.
 * @return a List of open stages.
 * @throws XPathException if the XPath expression is invalid.
 */
protected List<Stage> getOpenStageIDs(Document doc) throws StageException {
    List<Stage> stages = new ArrayList<Stage>();

    NodeList stageRepositories = (NodeList) evaluateXPath("//stagingProfileRepository", doc,
            XPathConstants.NODESET);
    for (int i = 0; i < stageRepositories.getLength(); i++) {

        Node stageRepo = stageRepositories.item(i);

        Node type = (Node) evaluateXPath("./type", stageRepo, XPathConstants.NODE);
        // type will be "open" or "closed"
        if ("open".equals(type.getTextContent())) {
            Node profileId = (Node) evaluateXPath("./profileId", stageRepo, XPathConstants.NODE);
            Node repoId = (Node) evaluateXPath("./repositoryId", stageRepo, XPathConstants.NODE);
            Node releaseRepositoryId = (Node) evaluateXPath("./releaseRepositoryId", stageRepo,
                    XPathConstants.NODE);
            Node repositoryURI = (Node) evaluateXPath("./repositoryURI", stageRepo, XPathConstants.NODE);

            Node description = (Node) evaluateXPath("./description", stageRepo, XPathConstants.NODE);
            GAV gav = new GAV(description.getTextContent());
            stages.add(new Stage(profileId.getTextContent(), repoId.getTextContent(),
                    releaseRepositoryId.getTextContent(), gav.getGroupId(), gav.getArtifactId(),
                    gav.getVersion(), repositoryURI.getTextContent()));
        }
    }
    return stages;
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method takes the SOAP request that come from the WSP and removes
 * the elements that need to be removed per the SAML Profiles spec.
 * /* w  w  w.  j  a v  a2  s  .c o  m*/
 * @param samlSession
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPRequest(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 3 of 5: Process SOAP Request");
    try {
        String expression = "/S:Envelope/S:Header/paos:Request";
        Document dom = authnState.getSoapRequestDom();
        Node node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);

        if (node != null) {
            // Save the response consumer URL to samlSession
            String responseConsumerURL = node.getAttributes().getNamedItem("responseConsumerURL")
                    .getTextContent();
            logger.debug("Loaded response consumer URL {}", responseConsumerURL);
            authnState.setResponseConsumerURL(responseConsumerURL);
            // Save the PAOS MessageID, if present
            Node paosMessageID = node.getAttributes().getNamedItem("messageID");

            if (paosMessageID != null)
                authnState.setPaosMessageID(paosMessageID.getTextContent());
            else
                authnState.setPaosMessageID(null);

            // This removes the paos:Request node
            node.getParentNode().removeChild(node);

            // Retrieve the RelayState cookie for sending it back to the WSP with the SOAP Response
            expression = "/S:Envelope/S:Header/ecp:RelayState";
            node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);
            if (node != null) {
                Element relayStateElement = (Element) node;
                authnState.setRelayStateElement(relayStateElement);
                node.getParentNode().removeChild(node);
            }

            // On to the ecp:Request for removal
            expression = "/S:Envelope/S:Header/ecp:Request";
            node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);
            node.getParentNode().removeChild(node);

            // Now add some namespace bindings to the SOAP Header
            expression = "/S:Envelope/S:Header";
            Element soapHeader = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);

            // Add new elements to S:Header
            Element newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sbf"), "sbf:Framework");
            newElement.setAttribute("version", "2.0");
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sb"), "sb:Sender");
            newElement.setAttribute("providerID", samlSession.getPortalEntityID());
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:MessageID");
            String messageID = generateMessageID();
            newElement.setTextContent(messageID);
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:Action");
            newElement.setTextContent("urn:liberty:ssos:2006-08:AuthnRequest");
            soapHeader.appendChild(newElement);

            // This is the wsse:Security element 
            Element securityElement = dom.createElementNS(
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "wsse:Security");
            securityElement.setAttribute(soapHeader.getPrefix() + ":mustUnderstand", "1");
            Element createdElement = dom.createElement("wsu:Created");
            // The examples use Zulu time zone, not local
            TimeZone zuluTimeZone = TimeZone.getTimeZone("Zulu");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
            sdf.setTimeZone(zuluTimeZone);
            createdElement.setTextContent(sdf.format(new Date()));
            newElement = dom.createElementNS(
                    "http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
                    "wsu:Timestamp");
            newElement.appendChild(createdElement);
            securityElement.appendChild(newElement);
            // Finally, insert the original SAML assertion
            Node samlAssertionNode = dom.importNode(samlSession.getSamlAssertionDom().getDocumentElement(),
                    true);
            securityElement.appendChild(samlAssertionNode);
            soapHeader.appendChild(securityElement);

            // Store the modified SOAP Request in the SAML Session
            String modifiedSOAPRequest = writeDomToString(dom);
            authnState.setModifiedSOAPRequest(modifiedSOAPRequest);
            logger.debug("Completed processing of SOAP request");
            return true;
        }
        logger.debug("Failed to process SOAP request using expression {}", expression);
    } catch (XPathExpressionException ex) {
        logger.error("Programming error.  Invalid XPath expression.", ex);
        throw new DelegatedAuthenticationRuntimeException("Programming error.  Invalid XPath expression.", ex);
    }
    return false;
}

From source file:com.enonic.esl.xml.XMLTool.java

private static Node selectSingleNode(Node node, String xpath) {
    try {/*  w  ww .  j  av a  2 s . c  o m*/
        final XPath xp = XPATH_FACTORY.newXPath();
        return (Node) xp.evaluate(xpath, node, XPathConstants.NODE);
    } catch (Exception e) {
        throw new XMLToolException(e);
    }
}

From source file:erwins.util.repack.xml.XMLBuilder.java

/**
 * Find the first element in the builder's DOM matching the given
 * XPath expression, where the expression may include namespaces if
 * a {@link NamespaceContext} is provided.
 *
 * @param xpath/*from   w  w w  . j  av a 2s. com*/
 * An XPath expression that *must* resolve to an existing Element within
 * the document object model.
 * @param nsContext
 * a mapping of prefixes to namespace URIs that allows the XPath expression
 * to use namespaces.
 *
 * @return
 * a builder node representing the first Element that matches the
 * XPath expression.
 *
 * @throws XPathExpressionException
 * If the XPath is invalid, or if does not resolve to at least one
 * {@link Node#ELEMENT_NODE}.
 */
public XMLBuilder xpathFind(String xpath, NamespaceContext nsContext) throws XPathExpressionException {
    Node foundNode = (Node) this.xpathQuery(xpath, XPathConstants.NODE, nsContext);
    if (foundNode == null || foundNode.getNodeType() != Node.ELEMENT_NODE) {
        throw new XPathExpressionException("XPath expression \"" + xpath
                + "\" does not resolve to an Element in context " + this.xmlNode + ": " + foundNode);
    }
    return new XMLBuilder(foundNode, null);
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Returns a node from the xml document defined by the Xpath
 *
 * @param elements//from   w w  w  . j  a v  a 2s  .  c om
 * @param xPath
 * @return
 */
public static Node xPathEvaluateNode(List<Element> elements, String xPath) throws MetsExportException {
    Document document = null;
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new MetsExportException("Error while evaluating xPath " + xPath, false, e1);
    }

    for (Element element : elements) {
        Node newNode = element.cloneNode(true);
        document.adoptNode(newNode);
        document.appendChild(newNode);
    }
    XPath xpathObject = XPathFactory.newInstance().newXPath();

    try {
        return (Node) xpathObject.compile(xPath).evaluate(document, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new MetsExportException("Error while evaluating xPath " + xPath, false, e);
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

private static void readGeosearchConfiguration(Document xmlConfiguration, XPath xpath)
        throws XPathExpressionException {
    /**************************
     * MASTER/*from  www.j a v  a 2 s  .c  o  m*/
     **************************/
    Node masterNode = (Node) xpath.compile("/configuration/general/geosearch/master").evaluate(xmlConfiguration,
            XPathConstants.NODE);
    geosearchMaster = readGeosearchNode(masterNode);

    if (geosearchMaster != null) {
        geosearchMaster.setMaster(true);
        // sets files
        GeosearchFilesVO geosearchFilesVO = readGeosearchMasterFiles(xmlConfiguration, xpath);
        geosearchMaster.setFiles(geosearchFilesVO);
    }

    /*************************
     * SLAVES
     *************************/
    geosearchSlaves = new LinkedList<GeosearchInstanceVO>();

    NodeList slavesNodes = (NodeList) xpath.compile("/configuration/general/geosearch/slaves/slave")
            .evaluate(xmlConfiguration, XPathConstants.NODESET);
    for (int i = 0; i < slavesNodes.getLength(); i++) {
        Node slaveNode = slavesNodes.item(i);
        GeosearchInstanceVO slave = readGeosearchNode(slaveNode);
        if (slave != null) {
            slave.setMaster(false);
            geosearchSlaves.add(slave);
        }
    }
}

From source file:com.bekwam.mavenpomupdater.MainViewController.java

public void doUpdate() {

    for (POMObject p : tblPOMS.getItems()) {

        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] p=" + p.getAbsPath());
        }/*  www  .jav  a 2s. c om*/

        if (p.getParseError()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because of a parse error on scanning");
            }
            continue;
        }

        if (!p.getUpdate()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because user excluded it from update");
            }
            continue;
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(p.getAbsPath());

            if (p.getParentVersion() != null && p.getParentVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/parent/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getParentVersion());
                }
            }

            if (p.getVersion() != null && p.getVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getVersion());
                }
            }

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();

            String workingFileName = p.getAbsPath() + ".mpu";
            FileWriter fw = new FileWriter(workingFileName);
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(fw);
            transformer.transform(source, result);
            fw.close();

            Path src = FileSystems.getDefault().getPath(workingFileName);
            Path target = FileSystems.getDefault().getPath(p.getAbsPath());

            Files.copy(src, target, StandardCopyOption.REPLACE_EXISTING);

            Files.delete(src);

        } catch (Exception exc) {
            log.error("error updating poms", exc);
        }
    }

    if (StringUtils.isNotEmpty(tfRootDir.getText())) {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] issuing rescan command");
        }
        scan();
    } else {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] did an update, but there is not value in root; clearing");
        }
        tblPOMS.getItems().clear();
    }
    tblPOMSDirty = false;
    tfNewVersion.setDisable(false);
}

From source file:com.cloud.hypervisor.kvm.resource.LibvirtComputingResourceTest.java

static void assertNodeExists(final Document doc, final String xPathExpr) {
    try {/*from  w  w  w. ja  v a2 s  . c  o m*/
        Assert.assertNotNull(
                XPathFactory.newInstance().newXPath().evaluate(xPathExpr, doc, XPathConstants.NODE));
    } catch (final XPathExpressionException e) {
        Assert.fail(e.getMessage());
    }
}