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:gov.nij.bundles.intermediaries.ers.EntityResolutionServiceIntermediaryTest.java

private void performSortTest(File inputMessageFile, int factor1, int factor2, int factor3) throws Exception {

    senderExchange.getIn().setBody(inputMessageFile);
    Exchange returnExchange = template.send("direct:entityResolutionRequestServiceEndpoint", senderExchange);

    if (returnExchange.getException() != null) {
        throw new Exception(returnExchange.getException());
    }//  ww  w. j  a v  a  2 s .c om

    Thread.sleep(3000);

    entityResolutionResponseMock.assertIsSatisfied();
    entityResolutionResponseMock.expectedMessageCount(1);

    Exchange ex = entityResolutionResponseMock.getExchanges().get(0);
    Document responseDocument = ex.getIn().getBody(Document.class);
    //        String docString = new XmlConverter().toString(responseDocument, ex);
    //        log.info("\n" + docString + "\n");

    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(testNamespaceContext);

    NodeList personNodes = (NodeList) xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:EntityContainer/merge-result-ext:Entity/ext:PersonSearchResult/ext:Person",
            responseDocument, XPathConstants.NODESET);
    assertEquals(5, personNodes.getLength());

    List<Node> lastNameNodes = new ArrayList<Node>();
    List<Node> firstNameNodes = new ArrayList<Node>();
    List<Node> idNodes = new ArrayList<Node>();

    for (int i = 0; i < personNodes.getLength(); i++) {
        Node personNode = personNodes.item(i);
        Node lastNameNode = (Node) xp.evaluate("nc:PersonName/nc:PersonSurName", personNode,
                XPathConstants.NODE);
        lastNameNodes.add(lastNameNode);
        Node firstNameNode = (Node) xp.evaluate("nc:PersonName/nc:PersonGivenName", personNode,
                XPathConstants.NODE);
        firstNameNodes.add(firstNameNode);
        Node idNode = (Node) xp.evaluate(
                "jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID",
                personNode, XPathConstants.NODE);
        idNodes.add(idNode);
    }

    assertTrue(compareTextNodeLists(personNodes.getLength(), lastNameNodes, firstNameNodes, idNodes, factor1,
            factor2, factor3));
}

From source file:hudson.plugins.plot.XMLSeries.java

/**
 * Load the series from a properties file.
 *//*  w  w w .j  av a 2  s  .  c  o  m*/
@Override
public List<PlotPoint> loadSeries(FilePath workspaceRootDir, int buildNumber, PrintStream logger) {
    InputStream in = null;
    InputSource inputSource = null;

    try {
        List<PlotPoint> ret = new ArrayList<PlotPoint>();
        FilePath[] seriesFiles = null;

        try {
            seriesFiles = workspaceRootDir.list(getFile());
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Exception trying to retrieve series files", e);
            return null;
        }

        if (ArrayUtils.isEmpty(seriesFiles)) {
            LOGGER.info("No plot data file found: " + getFile());
            return null;
        }

        try {
            if (LOGGER.isLoggable(defaultLogLevel))
                LOGGER.log(defaultLogLevel, "Loading plot series data from: " + getFile());

            in = seriesFiles[0].read();
            // load existing plot file
            inputSource = new InputSource(in);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Exception reading plot series data from " + seriesFiles[0], e);
            return null;
        }

        if (LOGGER.isLoggable(defaultLogLevel))
            LOGGER.log(defaultLogLevel, "NodeType " + nodeTypeString + " : " + nodeType);

        if (LOGGER.isLoggable(defaultLogLevel))
            LOGGER.log(defaultLogLevel, "Loaded XML Plot file: " + getFile());

        XPath xpath = XPathFactory.newInstance().newXPath();
        Object xmlObject = xpath.evaluate(xpathString, inputSource, nodeType);

        /*
         * If we have a nodeset, we need multiples, otherwise we just need
         * one value, and can do a toString() to set it.
         */
        if (nodeType.equals(XPathConstants.NODESET)) {
            NodeList nl = (NodeList) xmlObject;
            if (LOGGER.isLoggable(defaultLogLevel))
                LOGGER.log(defaultLogLevel, "Number of nodes: " + nl.getLength());

            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                if (!new Scanner(node.getTextContent().trim()).hasNextDouble()) {
                    return coalesceTextnodesAsLabelsStrategy(nl, buildNumber);
                }
            }
            return mapNodeNameAsLabelTextContentAsValueStrategy(nl, buildNumber);
        } else if (nodeType.equals(XPathConstants.NODE)) {
            addNodeToList(ret, (Node) xmlObject, buildNumber);
        } else {
            // otherwise we have a single type and can do a toString on it.
            if (xmlObject instanceof NodeList) {
                NodeList nl = (NodeList) xmlObject;

                if (LOGGER.isLoggable(defaultLogLevel))
                    LOGGER.log(defaultLogLevel, "Number of nodes: " + nl.getLength());

                for (int i = 0; i < nl.getLength(); i++) {
                    Node n = nl.item(i);

                    if (n != null && n.getLocalName() != null && n.getTextContent() != null) {
                        addValueToList(ret, label, xmlObject, buildNumber);
                    }
                }

            } else {
                addValueToList(ret, label, xmlObject, buildNumber);
            }
        }
        return ret;

    } catch (XPathExpressionException e) {
        LOGGER.log(Level.SEVERE, "XPathExpressionException for XPath '" + getXpath() + "'", e);
    } finally {
        IOUtils.closeQuietly(in);
    }

    return null;
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java

@Test
public void serviceDescriptionHasDescription() throws XPathException {
    //Verify the ServiceDescription has a dc:description child element      
    Node description = (Node) OSLCUtils.getXPath().evaluate("/oslc_cm:ServiceDescriptor/dc:description", doc,
            XPathConstants.NODE);
    assertNotNull(description);//  ww  w  .  jav a  2  s .com
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceProviderCatalogTests.java

@Test
public void serviceProviderCatalogsHaveValidTitles() throws XPathException {
    //Check root/*from ww w. ja v  a2 s  .c om*/
    Node rootCatalogTitle = (Node) OSLCUtils.getXPath().evaluate("/oslc_disc:ServiceProviderCatalog/dc:title",
            doc, XPathConstants.NODE);
    assertNotNull(rootCatalogTitle);
    assertFalse(rootCatalogTitle.getTextContent().isEmpty());
    NodeList titleSub = (NodeList) OSLCUtils.getXPath().evaluate("/oslc_disc:ServiceProviderCatalog/dc:title/*",
            doc, XPathConstants.NODESET);
    assertTrue(titleSub.getLength() == 0);

    //Get all entries, parse out which have embedded catalogs and check the titles
    NodeList catalogs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:entry/*", doc,
            XPathConstants.NODESET);
    for (int i = 0; i < catalogs.getLength(); i++) {
        Node catalog = (Node) OSLCUtils.getXPath().evaluate(
                "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProviderCatalog", doc,
                XPathConstants.NODE);
        //This entry has a catalog, check that it has a title
        if (catalog != null) {
            Node cTitle = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProviderCatalog/dc:title", doc,
                    XPathConstants.NODE);
            assertNotNull(cTitle);
            //Make sure the child isn't empty
            assertFalse(cTitle.getTextContent().isEmpty());
            Node child = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProviderCatalog/dc:title/*", doc,
                    XPathConstants.NODE);
            //Make sure the title has no child elements
            assertTrue(child == null);
        }
    }
}

From source file:core.com.qiniu.util.XpathUtils.java

public static Node asNode(String nodeName, Node node) throws XPathExpressionException {
    if (node == null)
        return null;
    return (Node) xpath().evaluate(nodeName, node, XPathConstants.NODE);
}

From source file:com.esri.gpt.server.csw.provider3.GetRecordsProvider.java

/**
 * Builds an ogc:Filter node from HTTP GET parameters.
 * @param namespace the namespace parameter values
 * @param constraintFilter the constraint parameter value
 * @throws Exception if a processing exception occurs
 */// w  w  w  .j  a  v a  2  s. c o  m
protected Node buildFilterNode(String[] namespace, String constraintFilter) throws Exception {

    // TODO GetRecordsDomBuilder had a different pattern??

    // parse namespaces
    // pattern: namespace=xmlns(ogc=http://www.opengis.net/ogc),xmlns(gml=http://www.opengis.net/gml)...
    StringBuilder nsBuffer = new StringBuilder();
    boolean hasCswUri = false;
    boolean hasCswPfx = false;
    String cswPfx = "";

    List<String[]> parseNamespace = parseNamespace(namespace);
    for (String[] ns : parseNamespace) {
        String nsUri = ns[0];
        String nsPfx = ns[1];
        if (nsUri.equals(CswNamespaces.CSW_30.URI_CSW())) {
            hasCswUri = true;
            if (!nsPfx.isEmpty()) {
                hasCswPfx = true;
                cswPfx = nsPfx;
            }
        }
        if (nsPfx.isEmpty()) {
            nsBuffer.append(" xmlns=\"").append(nsUri).append("\"");
        } else {
            nsBuffer.append(" xmlns:").append(nsPfx).append("=\"").append(nsUri).append("\"");
        }
    }

    // use ogc as the default namespace if no namespace parameter was supplied
    if (nsBuffer.length() == 0) {
        nsBuffer.append(" xmlns=\"http://www.opengis.net/ogc\"");
    }

    // build the constraint XML
    StringBuilder sbXml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    if (hasCswUri && hasCswPfx) {
        cswPfx = cswPfx + ":";
    } else if (hasCswUri) {
        cswPfx = "";
    } else {
        cswPfx = "csw:";
        nsBuffer.append(" xmlns:csw=\"http://www.opengis.net/cat/csw/3.0\"");
    }
    sbXml.append("\r\n<").append(cswPfx).append("Constraint");
    if (nsBuffer.length() > 0) {
        sbXml.append(" ").append(nsBuffer);
    }
    sbXml.append(">");
    sbXml.append("\r\n").append(constraintFilter);
    sbXml.append("\r\n</").append(cswPfx).append("Constraint>");

    // make the dom, find the ogc:Filter node
    try {
        Document dom = DomUtil.makeDomFromString(sbXml.toString(), true);
        CswNamespaces ns = CswNamespaces.CSW_30;
        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(ns.makeNamespaceContext());

        Node ndFilter = null;
        Node ndConstraint = (Node) xpath.evaluate("csw:Constraint", dom, XPathConstants.NODE);
        if (ndConstraint != null) {
            ndFilter = (Node) xpath.evaluate("ogc:Filter", ndConstraint, XPathConstants.NODE);
            ;
        }
        if (ndFilter == null) {
            String msg = "The supplied constraint was not a valid ogc:Filter.";
            throw new OwsException(OwsException.OWSCODE_NoApplicableCode, "constraint", msg);
        } else {
            return ndFilter;
        }

    } catch (SAXException e) {
        String msg = "The supplied namespace/constraint pairs were not well-formed xml: ";
        msg += " " + e.toString();
        throw new OwsException(OwsException.OWSCODE_NoApplicableCode, "constraint", msg);
    }

}

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

/**
 * @param documentDom//from w ww  .  j a v a2s .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:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java

@Test
public void serviceDescriptionContributorHasIdentifier() throws XPathException {
    //If the ServiceDescription has a dc:contributor element, make sure it has a dc:identifier child element
    NodeList contrib = (NodeList) OSLCUtils.getXPath().evaluate("//dc:contributor", doc, XPathConstants.NODE);
    if (contrib != null) {
        Node identifier = (Node) OSLCUtils.getXPath().evaluate("//dc:contributor/dc:identifier", doc,
                XPathConstants.NODE);
        assertNotNull(identifier);/*w ww.  ja va  2s.c om*/
    }
}

From source file:de.ingrid.iplug.opensearch.converter.IngridRSSConverter.java

/**
 * Extract the score value from a given node and return it as a float value.
 * In case no score node could be found 0.0f is returned. This score will
 * not be put into an IngridHit then.//from ww w  .  j  ava 2  s  .  co m
 * 
 * @param item
 *            is the node to look for the score entry
 * @return the score but 0.0f if no ranking is supported
 * @throws XPathExpressionException
 */
private float getScore(Node item) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node node = (Node) xpath.evaluate("score", item, XPathConstants.NODE);
    if (node != null) {
        return Float.valueOf(node.getTextContent());
    }
    return 0.0f;
}

From source file:cn.ctyun.amazonaws.util.XpathUtils.java

/**
 * Evaluates the specified XPath expression and returns the result as a
 * Node.//from w  w  w .  j  av a2  s .c  o m
 *
 * @param nodeName
 *            The XPath expression to evaluate.
 * @param node
 *            The node to run the expression on.
 *
 * @return The Node result.
 *
 * @throws XPathExpressionException
 *             If there was a problem processing the specified XPath
 *             expression.
 */
public static Node asNode(String nodeName, Node node) throws XPathExpressionException {
    if (node == null)
        return null;
    return (Node) xpath.evaluate(nodeName, node, XPathConstants.NODE);
}