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:de.bayern.gdi.services.Atom.java

private void preLoad() throws MalformedURLException, ParserConfigurationException {
    items = new ArrayList<>();
    String getTitle = "//title";
    this.title = (String) XML.xpath(this.mainDoc, getTitle, XPathConstants.STRING, this.nscontext);
    String getSubtitle = "//subtitle";
    this.subTitle = (String) XML.xpath(this.mainDoc, getSubtitle, XPathConstants.STRING, this.nscontext);
    String getID = "//id";
    this.serviceID = (String) XML.xpath(this.mainDoc, getID, XPathConstants.STRING, this.nscontext);
    String getEntriesQuery = "//entry";
    NodeList entries = (NodeList) XML.xpath(this.mainDoc, getEntriesQuery, XPathConstants.NODESET,
            this.nscontext);
    for (int i = 0; i < entries.getLength(); i++) {
        Node entry = entries.item(i);
        String getEntryTitle = "title";
        Node titleN = (Node) XML.xpath(entry, getEntryTitle, XPathConstants.NODE, this.nscontext);
        String getEntryid = "*[local-name()" + "='spatial_dataset_identifier_code']";
        Node id = (Node) XML.xpath(entry, getEntryid, XPathConstants.NODE, this.nscontext);
        if (id == null) {
            getEntryid = "id";
            id = (Node) XML.xpath(entry, getEntryid, XPathConstants.NODE, this.nscontext);
        }//from   ww  w  .j av  a  2s. c om
        String summaryExpr = "summary";
        Node description = (Node) XML.xpath(entry, summaryExpr, XPathConstants.NODE, this.nscontext);
        String describedByExpr = "link[@rel='alternate']/@href";
        Node describedBy = (Node) XML.xpath(entry, describedByExpr, XPathConstants.NODE, this.nscontext);
        if (describedBy == null) {
            describedByExpr = "link/@href";
            describedBy = (Node) XML.xpath(entry, describedByExpr, XPathConstants.NODE, this.nscontext);
        }
        String borderPolygonExpr = "*[local-name()" + "='polygon']";
        Node borderPolyGonN = (Node) XML.xpath(entry, borderPolygonExpr, XPathConstants.NODE, this.nscontext);
        if (borderPolyGonN == null) {
            borderPolygonExpr = "*[local-name()" + "='box']";
            borderPolyGonN = (Node) XML.xpath(entry, borderPolygonExpr, XPathConstants.NODE, this.nscontext);
        }
        Item it = new Item(new URL(this.serviceURL));
        if (id != null) {
            it.id = id.getTextContent();
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. ID not found");
        }
        if (title != null) {
            it.title = titleN.getTextContent();
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. Title not found");
        }
        if (description != null) {
            it.description = description.getTextContent();
        } else {
            it.description = it.title;
        }
        if (describedBy != null) {
            it.describedBy = describedBy.getTextContent();
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. DescribedBy not found");
        }
        if (entry != null) {
            it.otherCRSs = getCRS(entry);
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. Entry not found");
        }
        if (it.otherCRSs != null) {
            it.defaultCRS = it.otherCRSs.get(0);
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. CRSs not found");
        }
        it.username = this.username;
        it.password = this.password;

        // XXX: GML, anyone?
        if (borderPolyGonN != null) {
            WKTReader reader = new WKTReader(new GeometryFactory());
            String bboxStr = convertPolygonToWKT(borderPolyGonN.getTextContent());

            Geometry polygon = null;
            try {
                polygon = reader.read(bboxStr);
            } catch (ParseException e) {
                log.log(Level.SEVERE, e.getMessage(), e);
                continue;
            } catch (IllegalArgumentException e) {
                log.log(Level.SEVERE, e.getMessage(), e);
                throw e;
            }

            Envelope env = polygon.getEnvelopeInternal();
            if (env == null || !(polygon instanceof Polygon)) {
                continue;
            }

            it.polygon = (Polygon) polygon;
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. Bounding Box not Found");
        }
        items.add(it);
    }
}

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

/**
 * Get references for a given article/* www . j a v  a2 s  .  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 {
        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;
        }

        XPathExpression typeExpr = xpath.compile("//citation | //nlm-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) {
                NamedNodeMap nnm = resultNode.getAttributes();
                Node nnmNode = nnm.getNamedItem("citation-type");
                // some old articles do not have this attribute
                if (nnmNode != null) {
                    citation.setCitationType(nnmNode.getTextContent());
                }
            }

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

/**
 * Test the entity resolution service./*from w ww.  j  a  v a  2 s  .  com*/
 * 
 * @throws Exception
 */
@Test
@DirtiesContext
public void testEntityResolution() throws Exception {

    // Read the er search request file from the file system
    File inputFile = new File("src/test/resources/xml/EntityMergeRequestMessageWithAttributeParameters.xml");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document inputDocument = dbf.newDocumentBuilder().parse(inputFile);

    // Set it as the message message body
    senderExchange.getIn().setBody(inputDocument);

    // Send the one-way exchange. Using template.send will send an one way message
    Exchange returnExchange = template.send("direct:entityResolutionRequestServiceEndpoint", senderExchange);

    // Use getException to see if we received an exception
    if (returnExchange.getException() != null) {
        throw new Exception(returnExchange.getException());
    }

    // Sleep while a response is generated
    Thread.sleep(3000);

    // Assert that the mock endpoint is satisfied
    entityResolutionResponseMock.assertIsSatisfied();

    // We should get one message
    entityResolutionResponseMock.expectedMessageCount(1);

    // Get the first exchange (the only one)
    Exchange ex = entityResolutionResponseMock.getExchanges().get(0);

    // Get the actual response
    Document actualResponse = ex.getIn().getBody(Document.class);
    log.info("Input document: " + new XmlConverter().toString(inputDocument, null));
    log.info("Body recieved by Mock: " + new XmlConverter().toString(actualResponse, ex));

    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(testNamespaceContext);
    // note:  slash-slash xpaths are ok here because in tests we don't really care about performance...
    int inputEntityNodeCount = ((NodeList) xp.evaluate("//er-ext:Entity", inputDocument,
            XPathConstants.NODESET)).getLength();
    int outputEntityNodeCount = ((NodeList) xp.evaluate("//merge-result-ext:Entity", actualResponse,
            XPathConstants.NODESET)).getLength();
    NodeList outputOriginalRecordReferenceNodeList = (NodeList) xp
            .evaluate("//merge-result-ext:OriginalRecordReference", actualResponse, XPathConstants.NODESET);
    int outputOriginalRecordReferenceNodeCount = outputOriginalRecordReferenceNodeList.getLength();
    assertEquals(inputEntityNodeCount, outputEntityNodeCount);
    assertEquals(inputEntityNodeCount, outputOriginalRecordReferenceNodeCount);

    NodeList inputPersonNodes = (NodeList) xp.evaluate("//ext:Person", inputDocument, XPathConstants.NODESET);
    for (int i = 0; i < inputPersonNodes.getLength(); i++) {
        String inputLastName = xp.evaluate("nc:PersonName/nc:PersonSurName/text()", inputPersonNodes.item(i));
        if (inputLastName != null) {
            String xpathExpression = "//ext:Person[nc:PersonName/nc:PersonSurName/text()='" + inputLastName
                    + "']";
            assertNotNull(xp.evaluate(xpathExpression, actualResponse, XPathConstants.NODE));
        }
        String inputFirstName = xp.evaluate("nc:PersonName/nc:PersonGivenName/text()",
                inputPersonNodes.item(i));
        if (inputFirstName != null) {
            String xpathExpression = "//ext:Person[nc:PersonName/nc:PersonGivenName/text()='" + inputFirstName
                    + "']";
            log.info("xpathExpression=" + xpathExpression);
            assertNotNull(xp.evaluate(xpathExpression, actualResponse, XPathConstants.NODE));
        }
        String inputId = xp.evaluate(
                "jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID",
                inputPersonNodes.item(i));
        if (inputId != null) {
            String xpathExpression = "//ext:Person[jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID/text()='"
                    + inputId + "']";
            assertNotNull(xp.evaluate(xpathExpression, actualResponse, XPathConstants.NODE));
        }
    }

    for (int i = 0; i < outputOriginalRecordReferenceNodeCount; i++) {
        String nodeRef = ((Element) outputOriginalRecordReferenceNodeList.item(i))
                .getAttributeNS("http://niem.gov/niem/structures/2.0", "ref");
        assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + nodeRef + "']", actualResponse,
                XPathConstants.NODE));
    }

}

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

/**
 * This method extracts the IDP from the SAML assertion
 * /*ww w.j ava 2s  .c o m*/
 * @param samlSession
 * @param authnState 
 * @return true, if successful
 */
private boolean getIDP(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 1 of 5: get IDP from SAML Assertion");
    InputStream is = null;
    try {
        if (samlSession.getSamlAssertionDom() == null) {
            is = new ByteArrayInputStream(samlSession.getSamlAssertion().getBytes());
            InputSource source = new InputSource(is);
            DOMParser parser = new DOMParser();
            parser.setFeature("http://xml.org/sax/features/namespaces", true);
            parser.parse(source);
            Document doc = parser.getDocument();
            samlSession.setSamlAssertionDom(doc);
        }
        String expression = "/saml2:Assertion/saml2:Issuer";
        Node node = EXPRESSION_POOL.evaluate(expression, samlSession.getSamlAssertionDom(),
                XPathConstants.NODE);

        if (node != null) {
            String idp = node.getTextContent();
            logger.debug("Found IDP {} using expression {}", idp, expression);
            authnState.setIdp(idp);

            if (samlSession.getIdpResolver() == null) {
                samlSession.setIdpResolver(new AssertionIdpResolverImpl(EXPRESSION_POOL));
            }

            samlSession.getIdpResolver().resolve(samlSession, authnState);
            return true;
        }

        logger.debug("No IDP found using expression {}", expression);
    } catch (XPathExpressionException ex) {
        logger.error("Programming error.  Invalid XPath expression.", ex);
        throw new DelegatedAuthenticationRuntimeException("Programming error.  Invalid XPath expression.", ex);
    } catch (SAXException ex) {
        logger.error("XML error.", ex);
        logger.trace("XML parsing error when parsing the SAML assertion.  The assertion was: ["
                + samlSession.getSamlAssertion() + "].");
        throw new DelegatedAuthenticationRuntimeException("XML error.", ex);
    } catch (IOException ex) {
        logger.error("Unexpected error.  This method performs no I/O!", ex);
        throw new DelegatedAuthenticationRuntimeException("Unexpected error.  This method performs no I/O!",
                ex);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                //safe to ignore during cleanup
            }
        }
    }
    return false;
}

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

@Test
public void serviceProviderElementsHaveServicesChildElement() throws XPathException {
    //Get all entry elements
    NodeList entries = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:entry", doc,
            XPathConstants.NODESET);
    for (int i = 0; i < entries.getLength(); i++) {
        Node sp = (Node) OSLCUtils.getXPath().evaluate(
                "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider", doc, XPathConstants.NODE);
        //This entry has a ServiceProvider and not a catalog
        if (sp != null) {
            //Verify the ServiceProvider has a child element services
            Node services = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider/oslc_disc:services", doc,
                    XPathConstants.NODE);
            assertNotNull(services);//w w  w .  j a  v  a2 s  .  c  o  m
        }
    }
}

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

/**
 * Parses a stagingRepositories element to obtain the list of open stages.
 *
 * @param doc the stagingRepositories to parse.
 * @return a List of open stages./*from w w  w. j  a va 2s.  c  o m*/
 * @throws XPathException if the XPath expression is invalid.
 */
protected List<Stage> getClosedStageIds(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 ("closed".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.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java

@Test
public void homeElementHasTitleAndUrlChildElements() throws XPathException {
    //Make sure each home element has a title and url
    NodeList hElements = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm:home", doc,
            XPathConstants.NODESET);
    for (int i = 0; i < hElements.getLength(); i++) {
        Node hUrl = (Node) OSLCUtils.getXPath().evaluate("./oslc_cm:url", hElements.item(i),
                XPathConstants.NODE);
        assertNotNull(hUrl);/*from ww w  .j  ava 2  s. co  m*/
        Node hTitle = (Node) OSLCUtils.getXPath().evaluate("./dc:title", hElements.item(i),
                XPathConstants.NODE);
        assertNotNull(hTitle);
        assertFalse(hTitle.getTextContent().isEmpty());
    }
}

From source file:com.vmware.o11n.plugin.powershell.model.RemotePsType.java

private Object getObjByRefId(String refId) {
    Object obj = objects.get(refId);
    if (obj != null) {
        return obj;
    }/*w ww .  j av a2s .  co m*/

    try {
        //TODO precompile
        XPath xpathFindByRefId = xpathFactory.newXPath();
        Node propNode = (Node) xpathFindByRefId.evaluate(String.format("//Obj[@RefId=\"%s\"]", refId),
                doc.getDocumentElement(), XPathConstants.NODE);
        obj = read(propNode);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Unable to resolve object with id " + refId);
    }

    return obj;
}

From source file:net.firejack.platform.installation.processor.OFRInstallProcessor.java

private Module getModule(File ofr) throws IOException, XPathExpressionException {
    XPath xpath = factory.newXPath();
    InputStream file = ArchiveUtils.getFile(ofr, PackageFileType.PACKAGE_XML.getOfrFileName());
    Object evaluate = xpath.evaluate("/package", new InputSource(file), XPathConstants.NODE);
    String path = (String) xpath.evaluate("@path", evaluate, XPathConstants.STRING);
    String name = (String) xpath.evaluate("@name", evaluate, XPathConstants.STRING);
    String version = (String) xpath.evaluate("@version", evaluate, XPathConstants.STRING);
    String dependencies = (String) xpath.evaluate("@dependencies", evaluate, XPathConstants.STRING);
    IOUtils.closeQuietly(file);//  www  .j  a va2 s  .c o m

    String lookup = path + "." + name;
    Integer ver = VersionUtils.convertToNumber(version);

    return new Module(ofr, lookup, ver, dependencies);
}

From source file:com.redhat.plugin.eap6.EAP6DeploymentStructureMojo.java

protected void fillModuleEntries(Document doc, Element dependencies, Collection<String> modules)
        throws XPathExpressionException {
    for (String module : modules) {
        XPathExpression xp = xpf.newXPath().compile("module [@name=\"" + module + "\"]");
        // getLog().debug(xp.toString());
        Object result = xp.evaluate(dependencies, XPathConstants.NODE);
        if (result == null) {
            getLog().debug("insert module-dependency for " + module);
            Element moduleEl = doc.createElement("module");
            moduleEl.setAttribute("name", module);
            if (defaultSlot != null && !defaultSlot.isEmpty()) {
                moduleEl.setAttribute("slot", defaultSlot);
            }/*from www  .j a  v  a 2s.  c  om*/
            if (exportModules) {
                moduleEl.setAttribute("export", "true");
            }
            dependencies.appendChild(moduleEl);
            // if (verbose) {
            // getLog().debug("Module <" + moduleEl.getAttribute("name") + ">:" + moduleEl);
            // }
        } else {
            if (verbose) {
                getLog().debug("unresolved dependency with module-name " + module);
            }
            printXpathResult(result);
        }
    }
}