Example usage for javax.xml.xpath XPathConstants NODESET

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

Introduction

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

Prototype

QName NODESET

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

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

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

@Test
public void serviceProviderCatalogsHaveValidTitles() throws XPathException {
    //Check root//from   www. java 2  s .co  m
    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:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Get the author affiliations for a given article
 * @param doc article xml//from   w ww  . jav a 2  s.c  om
 * @param doc article xml
 * @return author affiliations
 */
public ArrayList<AuthorExtra> getAuthorAffiliations(Document doc) {

    ArrayList<AuthorExtra> list = new ArrayList<AuthorExtra>();
    Map<String, String> affiliateMap = new HashMap<String, String>();

    if (doc == null) {
        return list;
    }

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

        XPathExpression affiliationListExpr = xpath.compile("//aff");
        XPathExpression affiliationAddrExpr = xpath.compile("//addr-line");

        NodeList affiliationNodeList = (NodeList) affiliationListExpr.evaluate(doc, XPathConstants.NODESET);

        // Map all affiliation id's to their affiliation strings
        for (int i = 0; i < affiliationNodeList.getLength(); i++) {
            Node node = affiliationNodeList.item(i);
            // Not all <aff>'s have the 'id' attribute.
            String id = (node.getAttributes().getNamedItem("id") == null) ? ""
                    : node.getAttributes().getNamedItem("id").getTextContent();
            // Not all <aff> id's are affiliations.
            if (id.startsWith("aff")) {
                DocumentFragment df = doc.createDocumentFragment();
                df.appendChild(node);
                String address = ((Node) affiliationAddrExpr.evaluate(df, XPathConstants.NODE))
                        .getTextContent();
                affiliateMap.put(id, address);
            }
        }

        XPathExpression authorExpr = xpath.compile("//contrib-group/contrib[@contrib-type='author']");
        XPathExpression surNameExpr = xpath.compile("//name/surname");
        XPathExpression givenNameExpr = xpath.compile("//name/given-names");
        XPathExpression affExpr = xpath.compile("//xref[@ref-type='aff']");

        NodeList authorList = (NodeList) authorExpr.evaluate(doc, XPathConstants.NODESET);

        for (int i = 0; i < authorList.getLength(); i++) {
            Node cnode = authorList.item(i);
            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(cnode);
            Node sNode = (Node) surNameExpr.evaluate(df, XPathConstants.NODE);
            Node gNode = (Node) givenNameExpr.evaluate(df, XPathConstants.NODE);

            // Either surname or givenName can be blank
            String surname = (sNode == null) ? "" : sNode.getTextContent();
            String givenName = (gNode == null) ? "" : gNode.getTextContent();
            // If both are null then don't bother to add
            if ((sNode != null) || (gNode != null)) {
                NodeList affList = (NodeList) affExpr.evaluate(df, XPathConstants.NODESET);
                ArrayList<String> affiliations = new ArrayList<String>();

                // Build a list of affiliations for this author
                for (int j = 0; j < affList.getLength(); j++) {
                    Node anode = affList.item(j);
                    String affId = anode.getAttributes().getNamedItem("rid").getTextContent();
                    affiliations.add(affiliateMap.get(affId));
                }

                AuthorExtra authorEx = new AuthorExtra();
                authorEx.setAuthorName(surname, givenName);
                authorEx.setAffiliations(affiliations);
                list.add(authorEx);
            }
        }
    } catch (Exception e) {
        log.error("Error occurred while gathering the author affiliations.", e);
    }

    return list;
}

From source file:eumetsat.pn.common.ISO2JSON.java

private JSONObject convert(Document xmlDocument) throws XPathExpressionException, IOException {
    String expression = null;/*  w w  w.ja v  a2s. c o m*/
    String result = null;
    XPath xPath = XPathFactory.newInstance().newXPath();
    JSONObject jsonObject = new JSONObject();

    String xpathFileID = "//*[local-name()='fileIdentifier']/*[local-name()='CharacterString']";
    String fileID = xPath.compile(xpathFileID).evaluate(xmlDocument);
    log.trace("{} >>> {}", xpathFileID, fileID);
    if (fileID != null) {
        jsonObject.put(FILE_IDENTIFIER_PROPERTY, fileID);
    }

    expression = "//*[local-name()='hierarchyLevelName']/*[local-name()='CharacterString']";
    JSONArray list = new JSONArray();
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        list.add(nodeList.item(i).getFirstChild().getNodeValue());
    }
    if (list.size() > 0) {
        JSONObject hierarchies = parseThemeHierarchy((String) jsonObject.get(FILE_IDENTIFIER_PROPERTY), list);
        hierarchies.writeJSONString(writer);
        jsonObject.put("hierarchyNames", hierarchies);
        log.trace("{} >>> {}", expression, jsonObject.get("hierarchyNames"));
    }

    // Get Contact info
    String deliveryPoint = "//*[local-name()='address']//*[local-name()='deliveryPoint']/*[local-name()='CharacterString']";
    String city = "//*[local-name()='address']//*[local-name()='city']/*[local-name()='CharacterString']";
    String administrativeArea = "//*[local-name()='address']//*[local-name()='administrativeArea']/*[local-name()='CharacterString']";
    String postalCode = "//*[local-name()='address']//*[local-name()='postalCode']/*[local-name()='CharacterString']";
    String country = "//*[local-name()='address']//*[local-name()='country']/*[local-name()='CharacterString']";
    String email = "//*[local-name()='address']//*[local-name()='electronicMailAddress']/*[local-name()='CharacterString']";

    StringBuilder addressString = new StringBuilder();
    StringBuilder emailString = new StringBuilder();

    appendIfResultNotNull(xPath, xmlDocument, addressString, deliveryPoint);

    result = xPath.compile(postalCode).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(city).evaluate(xmlDocument);
    if (result != null) {
        addressString.append(" ").append(result.trim());
    }

    result = xPath.compile(administrativeArea).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(country).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(email).evaluate(xmlDocument);
    if (result != null) {
        emailString.append(result.trim());
    }

    HashMap<String, String> map = new HashMap<>();
    map.put("address", addressString.toString());
    map.put("email", emailString.toString());
    jsonObject.put("contact", map);
    log.trace("contact: {}", Arrays.toString(map.entrySet().toArray()));

    // add identification info
    String abstractStr = "//*[local-name()='identificationInfo']//*[local-name()='abstract']/*[local-name()='CharacterString']";
    String titleStr = "//*[local-name()='identificationInfo']//*[local-name()='title']/*[local-name()='CharacterString']";
    String statusStr = "//*[local-name()='identificationInfo']//*[local-name()='status']/*[local-name()='MD_ProgressCode']/@codeListValue";
    String keywords = "//*[local-name()='keyword']/*[local-name()='CharacterString']";

    HashMap<String, Object> idMap = new HashMap<>();

    result = xPath.compile(titleStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("title", result.trim());
    }

    result = xPath.compile(abstractStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("abstract", result.trim());
    }

    result = xPath.compile(statusStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("status", result.trim());
    }

    list = new JSONArray();
    nodeList = (NodeList) xPath.compile(keywords).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        list.add(nodeList.item(i).getFirstChild().getNodeValue());
    }

    if (list.size() > 0) {
        idMap.put("keywords", list);
    }

    jsonObject.put("identificationInfo", idMap);
    log.trace("idMap: {}", idMap);

    // get thumbnail product
    String browseThumbnailStr = "//*[local-name()='graphicOverview']//*[local-name()='MD_BrowseGraphic']//*[local-name()='fileName']//*[local-name()='CharacterString']";
    result = xPath.compile(browseThumbnailStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("thumbnail", result.trim());
        log.trace("thumbnail: {}", result);
    }

    // add Geo spatial information
    String westBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='westBoundLongitude']/*[local-name()='Decimal']";
    String eastBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='eastBoundLongitude']/*[local-name()='Decimal']";
    String northBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='northBoundLatitude']/*[local-name()='Decimal']";
    String southBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='southBoundLatitude']/*[local-name()='Decimal']";

    // create a GeoJSON envelope object
    HashMap<String, Object> latlonMap = new HashMap<>();
    latlonMap.put("type", "envelope");

    JSONArray envelope = new JSONArray();
    JSONArray leftTopPt = new JSONArray();
    JSONArray rightDownPt = new JSONArray();

    result = xPath.compile(westBLonStr).evaluate(xmlDocument);
    if (result != null) {
        leftTopPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(northBLatStr).evaluate(xmlDocument);
    if (result != null) {
        leftTopPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(eastBLonStr).evaluate(xmlDocument);
    if (result != null) {
        rightDownPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(southBLatStr).evaluate(xmlDocument);
    if (result != null) {
        rightDownPt.add(Double.parseDouble(result.trim()));
    }

    envelope.add(leftTopPt);
    envelope.add(rightDownPt);

    latlonMap.put("coordinates", envelope);
    jsonObject.put("location", latlonMap);

    DOMImplementationLS domImplementation = (DOMImplementationLS) xmlDocument.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    String xmlString = lsSerializer.writeToString(xmlDocument);

    jsonObject.put("xmldoc", xmlString);

    return jsonObject;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java

@Test
public void changeRequestHasAtMostOneInstanceShape() throws XPathExpressionException {
    NodeList instances = (NodeList) OSLCUtils.getXPath()
            .evaluate("//oslc_cm_v2:ChangeRequest/oslc:instanceShape", doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), instances.getLength() <= 1);
}

From source file:org.eclipse.lyo.testsuite.oslcv2.ServiceProviderCatalogXmlTests.java

@Test
public void serviceProviderCatalogsHaveAtMostOnePublisher() throws XPathExpressionException {
    // Check root for Publisher, make sure it only has at most one
    NodeList rootChildren = (NodeList) OSLCUtils.getXPath()
            .evaluate("/rdf:RDF/oslc_v2:ServiceProviderCatalog/*", doc, XPathConstants.NODESET);
    int numPublishers = 0;/*from  w w  w .j a v a 2s .  c  o  m*/
    for (int i = 0; i < rootChildren.getLength(); i++) {
        if (rootChildren.item(i).getNamespaceURI().equals(OSLCConstants.DC)
                && rootChildren.item(i).getLocalName().equals("publisher")) {
            numPublishers++;
        }
    }
    assert (numPublishers <= 1);

    // Get list of other ServiceProviderCatalog elements
    NodeList nestedSPCs = (NodeList) OSLCUtils.getXPath().evaluate("/*/*//oslc_v2:serviceProviderCatalog", doc,
            XPathConstants.NODESET);
    // Go through the children of each catalog
    for (int i = 0; i < nestedSPCs.getLength(); i++) {
        NodeList spcChildren = (NodeList) OSLCUtils.getXPath()
                .evaluate("/*/*//oslc_v2:serviceProviderCatalog[" + i + "]/*/*", doc, XPathConstants.NODESET);
        int publisherCount = 0;
        // Make sure there's at most one Publisher blocks
        for (int j = 0; j < spcChildren.getLength(); j++) {
            if (spcChildren.item(j).getNamespaceURI().equals(OSLCConstants.DC)
                    && spcChildren.item(j).getLocalName().equals("publisher")) {
                publisherCount++;
            }
        }
        assert (publisherCount <= 1);
    }
}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

/**
 * Returns the NodeList corresponding to the XPath query.
 *
 * @param xmlNode     The node where the search should be performed.
 * @param xPathString XPath query string
 * @return/*ww w.  j av a 2s  . c o m*/
 * @throws XPathExpressionException
 */
public static NodeList getNodeList(final Node xmlNode, final String xPathString) {

    try {

        final XPathExpression expr = createXPathExpression(xPathString);
        final NodeList evaluated = (NodeList) expr.evaluate(xmlNode, XPathConstants.NODESET);
        return evaluated;
    } catch (XPathExpressionException e) {
        throw new DSSException(e);
    }
}

From source file:pl.psnc.synat.wrdz.mdz.format.FileFormatVerifierBean.java

/**
 * Returns the nodes from the given xml document that match the given xpath expression.
 * /* w  w  w  .  j av a 2 s  . c  o  m*/
 * @param document
 *            xml document to search
 * @param path
 *            xpath expression
 * @return matching nodes
 */
private NodeList xpath(Document document, String path) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new NamespaceContextImpl(NS_PREFIX, NS_URI));

    try {
        return (NodeList) xpath.evaluate(path, document, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Incorrect XPath expression", e);
    }
}

From source file:com.gatf.executor.validator.ResponseValidator.java

public NodeList getNodeByXpath(String xpathStr, Document xmlDocument, String messagePrefix)
        throws XPathExpressionException {
    if (messagePrefix == null) {
        messagePrefix = "Expected Node ";
    }//  w  w  w.j  av a  2  s  . c  o  m
    String oxpathStr = xpathStr;
    xpathStr = xpathStr.replaceAll("\\.", "\\/");
    if (xpathStr.charAt(0) != '/')
        xpathStr = "/" + xpathStr;
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList xmlNodeList = (NodeList) xPath.compile(xpathStr).evaluate(xmlDocument, XPathConstants.NODESET);
    Assert.assertTrue(messagePrefix + oxpathStr + " is null",
            xmlNodeList != null && xmlNodeList.getLength() > 0);
    return xmlNodeList;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

private static ClinicalBean[] processElementGroup(String pathToParent, Document doc, XPath xpath,
        ClinicalBean bean, int parentId)
        throws XPathExpressionException, IllegalAccessException, InstantiationException {
    // the bean knows its XML group name, if any
    if (bean.getXmlGroupName() != null) {
        pathToParent += "/" + bean.getXmlGroupName();
    }//  w  w  w.j a v a 2  s .co  m
    pathToParent += "/" + bean.getXmlElementName();
    // get all child nodes
    NodeList nodes = (NodeList) xpath.evaluate(pathToParent, doc, XPathConstants.NODESET);
    // make a bean for each child node
    ClinicalBean[] beans = new ClinicalBean[nodes.getLength()];
    for (int i = 1; i <= nodes.getLength(); i++) {
        // clone the passed in bean, which has the correct specific class
        ClinicalBean b = bean.makeClone();
        // now process this specific child element
        processElement(pathToParent + "[" + i + "]", doc, xpath, b, parentId);
        beans[i - 1] = b;
    }
    return beans;
}

From source file:be.fgov.kszbcss.rhq.websphere.component.server.WebSphereServerDiscoveryComponent.java

public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ResourceComponent<?>> context)
        throws InvalidPluginConfigurationException, Exception {
    Set<DiscoveredResourceDetails> result = new HashSet<DiscoveredResourceDetails>();
    for (ProcessScanResult process : context.getAutoDiscoveredProcesses()) {
        ProcessInfo processInfo = process.getProcessInfo();
        String[] commandLine = processInfo.getCommandLine();
        if (log.isDebugEnabled()) {
            log.debug("Examining process " + processInfo.getPid());
            log.debug("Command line: " + Arrays.asList(commandLine));
        }//from   w  ww . j a v  a2  s.c o m
        int appOptionIndex = -1; // The index of the -application option
        for (int i = 0; i < commandLine.length; i++) {
            if (commandLine[i].equals("-application")) {
                appOptionIndex = i;
                break;
            }
        }
        if (appOptionIndex == -1) {
            log.debug("No -application option found");
            continue;
        }
        if (commandLine.length - appOptionIndex != 7) {
            if (log.isDebugEnabled()) {
                log.debug("Unexpected number of arguments (" + (commandLine.length - appOptionIndex)
                        + ") after -application");
            }
            continue;
        }
        if (!commandLine[appOptionIndex + 1].equals("com.ibm.ws.bootstrap.WSLauncher")) {
            log.debug("Expected com.ibm.ws.bootstrap.WSLauncher after -application");
            continue;
        }
        if (!commandLine[appOptionIndex + 2].equals("com.ibm.ws.runtime.WsServer")) {
            if (log.isDebugEnabled()) {
                log.debug("Process doesn't appear to be a WebSphere server process; main class is "
                        + commandLine[appOptionIndex + 2]);
            }
            continue;
        }
        File repository = new File(commandLine[appOptionIndex + 3]);
        String cell = commandLine[appOptionIndex + 4];
        String node = commandLine[appOptionIndex + 5];
        String processName = commandLine[appOptionIndex + 6];
        if (processName.equals("nodeagent")) {
            log.debug("Process appears to be a node agent");
            continue;
        }
        if (processName.equals("dmgr")) {
            log.debug("Process appears to be a deployment manager");
            continue;
        }
        log.info("Discovered WebSphere application server process " + cell + "/" + node + "/" + processName);
        if (!repository.exists()) {
            log.error("Configuration repository " + repository + " doesn't exist");
            continue;
        }
        if (!repository.canRead()) {
            log.error("Configuration repository " + repository + " not readable");
            continue;
        }

        // Parse the serverindex.xml file for the node
        File serverIndexFile = new File(repository, "cells" + File.separator + cell + File.separator + "nodes"
                + File.separator + node + File.separator + "serverindex.xml");
        if (log.isDebugEnabled()) {
            log.debug("Attempting to read " + serverIndexFile);
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document serverIndex;
        try {
            serverIndex = builder.parse(serverIndexFile);
        } catch (Exception ex) {
            log.error("Unable to parse " + serverIndexFile, ex);
            continue;
        }

        // Extract the port number
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
        nsContext.setPrefix("serverindex",
                "http://www.ibm.com/websphere/appserver/schemas/5.0/serverindex.xmi");
        xpath.setNamespaceContext(nsContext);
        int port = -1;
        String protocol = null;
        for (PortSpec portSpec : portSpecs) {
            if (log.isDebugEnabled()) {
                log.debug("Attempting to extract " + portSpec.getEndPointName());
            }
            String portString = (String) xpath.evaluate("/serverindex:ServerIndex/serverEntries[@serverName='"
                    + processName + "']/specialEndpoints[@endPointName='" + portSpec.getEndPointName()
                    + "']/endPoint/@port", serverIndex, XPathConstants.STRING);
            if (portString == null || portString.length() == 0) {
                log.debug(portSpec.getEndPointName() + " not found");
                continue;
            }
            int candidatePort;
            try {
                candidatePort = Integer.parseInt(portString);
            } catch (NumberFormatException ex) {
                log.warn("Found non numerical port number in " + serverIndexFile);
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("Port is " + candidatePort);
            }
            if (candidatePort != 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Using " + portSpec.getEndPointName() + "=" + candidatePort + ", protocol "
                            + portSpec.getProtocol());
                }
                port = candidatePort;
                protocol = portSpec.getProtocol();
                break;
            }
        }
        if (port == -1) {
            log.error("Unable to locate usable port in " + serverIndexFile);
            continue;
        }

        // Check if this is a managed server by looking for WebSphere instances of type NODE_AGENT
        boolean unmanaged = ((NodeList) xpath.evaluate(
                "/serverindex:ServerIndex/serverEntries[@serverType='NODE_AGENT']", serverIndex,
                XPathConstants.NODESET)).getLength() == 0;

        Configuration conf = new Configuration();
        conf.put(new PropertySimple("host", "localhost"));
        conf.put(new PropertySimple("port", port));
        conf.put(new PropertySimple("protocol", protocol));
        conf.put(new PropertySimple("loggingProvider", "none")); // TODO: autodetect XM4WAS
        conf.put(new PropertySimple("childJmxServerName", "JVM"));
        conf.put(new PropertySimple("unmanaged", unmanaged));
        result.add(new DiscoveredResourceDetails(context.getResourceType(),
                cell + "/" + node + "/" + processName, processName, null,
                processName + " (cell " + cell + ", node " + node + ")", conf, processInfo));
    }
    return result;
}