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.oslcv2.ServiceProviderCatalogXmlTests.java

@Test
public void serviceProvidersHaveAtMostOneTitle() throws XPathException {
    // Get all service providers listed
    NodeList nestedSPCs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_v2:serviceProvider", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nestedSPCs.getLength(); i++) {
        NodeList spcChildren = (NodeList) OSLCUtils.getXPath().evaluate("./*/*", nestedSPCs.item(i),
                XPathConstants.NODESET);
        int titleCount = 0;

        // Go through the service provider's children, make sure it contains
        // at most one title.
        for (int j = 0; j < spcChildren.getLength(); j++) {
            if (spcChildren.item(j).getNamespaceURI().equals(OSLCConstants.DC)
                    && spcChildren.item(j).getLocalName().equals("title")) {
                titleCount++;/*from w w w.ja va2 s  .  c o  m*/
            }
        }
        assert (titleCount <= 1);
    }
}

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

private static int processElement(String pathToElement, Document doc, XPath xpath, ClinicalBean bean,
        int parentId) throws XPathExpressionException, InstantiationException, IllegalAccessException {
    // check if element exists... if not, return -1
    NodeList nodes = (NodeList) xpath.evaluate(pathToElement, doc, XPathConstants.NODESET);
    if (nodes.getLength() < 1) {
        return -1;
    }/*from w w w . j a v a  2  s  . c  om*/

    // for each bean attribute, look for the value of the element with that name and set it in the bean
    for (String attribute : bean.getOrderedAttributes()) {
        String value = xpath.evaluate(pathToElement + "/" + attribute + "/text()", doc);
        bean.setAttribute(attribute, value);
    }

    // tell the bean to save itself to the database
    return bean.insertSelf(parentId);
}

From source file:org.alfresco.web.config.XmlUtils.java

/**
 * Checks in under a given root element whether it can find a child elements
 * which match the XPath expression supplied. Returns a {@link List} of
 * {@link Element} if they exist./*from w  ww  . j a  v a  2 s.  c  om*/
 * 
 * Please note that the XPath parser used is NOT namespace aware. So if you
 * want to find a element <beans><sec:http> you need to use the following
 * XPath expression '/beans/http'.
 * 
 * @param xPathExpression the xPathExpression
 * @param root the parent DOM element
 * 
 * @return a {@link List} of type {@link Element} if discovered, otherwise null
 */
public static List<Element> findElements(String xPathExpression, Element root) {
    List<Element> elements = new ArrayList<Element>();

    NodeList nodes = null;

    try {
        XPathExpression expr = xpath.compile(xPathExpression);
        nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Unable evaluate xpath expression", e);
    }

    for (int i = 0; i < nodes.getLength(); i++) {
        elements.add((Element) nodes.item(i));
    }
    return elements;
}

From source file:io.selendroid.server.model.internal.AbstractNativeElementContext.java

public List<AndroidElement> findElementsByXPath(String expression) {
    JSONObject root = null;//from   w w  w .ja  v  a 2  s . c om
    try {
        root = getElementTree();
    } catch (JSONException e1) {
        SelendroidLogger.error("Could not getElementTree", e1);
    }

    Document xmlDocument = JsonXmlUtil.buildXmlDocument(root);
    XPath xPath = XPathFactory.newInstance().newXPath();

    List<AndroidElement> elements = new ArrayList<AndroidElement>();
    NodeList nodeList;
    try {
        // read a nodelist using xpath
        nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        SelendroidLogger.error("Failed to get NodeList for XPath", e);
        return elements;
    }
    if (nodeList != null && nodeList.getLength() > 0) {
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getAttributes() == null) {
                continue;
            }
            Node namedItem = node.getAttributes().getNamedItem("ref");
            if (namedItem != null) {
                elements.add(knownElements.get(namedItem.getTextContent()));
            }
        }
    }

    return elements;
}

From source file:com.sixdimensions.wcm.cq.pack.service.impl.LegacyPackageManagerServiceImpl.java

/**
 * Parses the response from the server using XPath.
 * // w w w  .  java 2  s .com
 * @param response
 *            the response to parse
 * @return a response object representing the response data
 * @throws XPathExpressionException
 * @throws SAXException
 * @throws IOException
 * @throws ParserConfigurationException
 */
private Response parseResponse(final byte[] response)
        throws XPathExpressionException, IOException, ParserConfigurationException {
    this.log.debug("parseResponse");

    Response responseObj = null;
    try {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this!
        final Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(response));

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

        // Sample response
        //
        // <crx version="2.0" user="admin" workspace="crx.default">
        // <request>
        // <param name="cmd" value="rm"/>
        // <param name="name" value="myPackage"/>
        // </request>
        // <response>
        // <status code="200">ok</status>
        // </response>
        // </crx>

        this.log.debug("Parsing response code");
        final XPathExpression codeXpr = xpath.compile("/crx/response/status/@code");
        int responseCode = -1;
        try {
            responseCode = Integer.parseInt(
                    ((NodeList) codeXpr.evaluate(doc, XPathConstants.NODESET)).item(0).getNodeValue(), 10);
        } catch (final NumberFormatException nfe) {
            this.log.warn("Unable to parse "
                    + ((NodeList) codeXpr.evaluate(doc, XPathConstants.NODESET)).item(0).getNodeValue()
                    + " as a number");
        }

        this.log.debug("Parsing response message");
        final XPathExpression messageXpr = xpath.compile("/crx/response/status");
        final String responseMessage = ((NodeList) messageXpr.evaluate(doc, XPathConstants.NODESET)).item(0)
                .getChildNodes().item(0).getNodeValue();

        responseObj = new Response(HttpStatus.SC_OK == responseCode, responseCode, responseMessage);
        this.log.debug("Response Code: " + responseCode);
        if (HttpStatus.SC_OK == responseCode) {
            this.log.debug("Response Message: " + responseMessage);
        } else {
            this.log.warn("Error Message: " + responseMessage);
        }
    } catch (final SAXException se) {
        final String message = "Exception parsing XML response, assuming failure.  "
                + "This often occurs when an invalid XML file is uploaded as the error message "
                + "is not properly escaped in the response.";
        this.log.warn(message, se);
        this.log.warn("Response contents: " + new String(response, "utf-8"));
        responseObj = new Response(false, 500, message);
    }

    return responseObj;
}

From source file:com.alliander.osgp.adapter.ws.endpointinterceptors.WebServiceMonitorInterceptor.java

/**
 * Search an XML element using an XPath expression.
 *
 * @param document//  w ww. j  a  v  a2  s. c  om
 *            The XML document.
 * @param element
 *            The name of the desired XML element.
 *
 * @return The content of the XML element, or null if the element is not
 *         found.
 *
 * @throws XPathExpressionException
 *             In case the expression fails to compile or evaluate, an
 *             exception will be thrown.
 */
private String evaluateXPathExpression(final Document document, final String element)
        throws XPathExpressionException {
    final String expression = String.format("//*[contains(local-name(), '%s')]", element);

    final XPathFactory xFactory = XPathFactory.newInstance();
    final XPath xPath = xFactory.newXPath();

    final XPathExpression xPathExpression = xPath.compile(expression);
    final NodeList nodeList = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);

    if (nodeList != null && nodeList.getLength() > 0) {
        return nodeList.item(0).getTextContent();
    } else {
        return null;
    }
}

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

@Test
public void serviceDescriptionHasTitle() throws XPathException {
    //Verify that the ServiceDescription has a dc:title child element
    Node title = (Node) OSLCUtils.getXPath().evaluate("/oslc_cm:ServiceDescriptor/dc:title", doc,
            XPathConstants.NODE);
    assertNotNull(title);// w w  w .  j a  v a  2s . c o m
    assertFalse(title.getTextContent().isEmpty());

    //Verify that the dc:title child element has no children
    NodeList children = (NodeList) OSLCUtils.getXPath().evaluate("/oslc_cm:ServiceDescriptor/dc:title/*", doc,
            XPathConstants.NODESET);
    assertTrue(children.getLength() == 0);
}

From source file:de.codesourcery.eve.apiclient.utils.XMLParseHelper.java

public static List<Element> selectElements(Document doc, XPathExpression expr, boolean isRequired) {
    final NodeList result;
    try {//  ww w .  jav a  2s. com
        result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Internal error while evaluating XPath expression " + expr, e);
    }

    if (result.getLength() == 0) {
        if (isRequired) {
            throw new UnparseableResponseException(
                    "Unexpected response XML," + " XPath expression returned nothing: " + expr);
        }
        return Collections.emptyList();
    }

    return new AbstractList<Element>() {

        @Override
        public Element get(int index) {
            return (Element) result.item(index);
        }

        @Override
        public int size() {
            return result.getLength();
        }
    };
}

From source file:org.koiroha.jyro.workers.crawler.Crawler.java

/**
 * Parse content./*from www.  ja v a2  s.c  om*/
 *
 * @param content content to analyze
 * @throws WorkerException if fail to retrieve
*/
private List<URI> parseHtmlContent(URI uri, String type, byte[] content) {
    List<URI> urls = new ArrayList<URI>();

    try {
        // parse html document
        Charset def = Xml.getCharset(type);
        HTMLDocumentBuilderFactory factory = new HTMLDocumentBuilderFactory();
        factory.setNamespaceAware(false);
        factory.setXIncludeAware(false);
        InputSource is = factory.guessInputSource(new ByteArrayInputStream(content), def.name(),
                content.length);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);

        // extract link
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nl = (NodeList) xpath.evaluate("//a/@href", doc, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            String href = ((Attr) nl.item(i)).getValue();
            urls.add(uri.resolve(href));
        }
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
    return urls;
}

From source file:aurelienribon.gdxsetupui.Helper.java

public static List<GwtModule> getGwtModules(File modulesFile) {
    List<GwtModule> modules = new ArrayList<GwtModule>();
    if (!modulesFile.isFile())
        return modules;

    try {/*ww  w.j  a  v a2  s .co m*/
        Document doc = XmlUtils.createParser().parse(modulesFile);
        NodeList nodes = (NodeList) XmlUtils.xpath("module/inherits[@name]", doc, XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            String name = nodes.item(i).getAttributes().getNamedItem("name").getNodeValue();
            modules.add(new GwtModule(name));
        }

    } catch (SAXException ex) {
    } catch (IOException ex) {
    }

    return modules;
}