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:com.microsoftopentechnologies.intellij.helpers.azure.AzureRestAPIManager.java

public void setSelectedSubscriptions(List<UUID> selectedList) throws AzureCmdException {
    try {/*from   w ww.ja  va 2 s.  c  o  m*/
        AzureAuthenticationMode mode = getAuthenticationMode();

        if (mode == AzureAuthenticationMode.SubscriptionSettings) {
            String subscriptionFile = PropertiesComponent.getInstance()
                    .getValue(MSOpenTechToolsApplication.AppSettingsNames.SUBSCRIPTION_FILE, "");

            NodeList subscriptionList = (NodeList) XmlHelper.getXMLValue(subscriptionFile, "//Subscription",
                    XPathConstants.NODESET);
            for (int i = 0; i < subscriptionList.getLength(); i++) {
                UUID id = UUID.fromString(XmlHelper.getAttributeValue(subscriptionList.item(i), "Id"));
                Node node = subscriptionList.item(i).getAttributes().getNamedItem("Selected");

                if (node == null) {
                    node = subscriptionList.item(i).getOwnerDocument().createAttribute("Selected");
                }

                node.setNodeValue(selectedList.contains(id) ? "true" : "false");
                subscriptionList.item(i).getAttributes().setNamedItem(node);
            }

            if (subscriptionList.getLength() > 0) {
                String savedXml = XmlHelper.saveXmlToStreamWriter(subscriptionList.item(0).getOwnerDocument());
                PropertiesComponent.getInstance()
                        .setValue(MSOpenTechToolsApplication.AppSettingsNames.SUBSCRIPTION_FILE, savedXml);
            }
        } else if (mode == AzureAuthenticationMode.ActiveDirectory) {
            for (Subscription subscription : subscriptions) {
                subscription.setSelected(selectedList.contains(subscription.getId()));
            }

            ArrayList<String> selectedIds = new ArrayList<String>();
            for (UUID uuid : selectedList) {
                selectedIds.add(uuid.toString());
            }

            PropertiesComponent.getInstance().setValue(
                    MSOpenTechToolsApplication.AppSettingsNames.SELECTED_SUBSCRIPTIONS,
                    StringUtils.join(selectedIds, ","));
        }
    } catch (Exception e) {
        throw new AzureCmdException("Error getting subscription list", e);
    }
}

From source file:com.mediaworx.xmlutils.XmlHelper.java

/**
 * Retrieves the NodeList for the given XPath from the given ancestor Node.
 * @param ancestorNode the node from which the NodeList is to be read
 * @param xPath        the XPath (relative to the ancestor node)
 * @return the NodeList for the given XPath
 * @throws XPathExpressionException if the given XPath can't be evaluated (e.g. because it does not exist)
 *//*www .  ja  v  a  2 s.c  o m*/
public NodeList getNodeListForXPath(Node ancestorNode, String xPath) throws XPathExpressionException {
    XPath xpath = xPathfactory.newXPath();
    return (NodeList) xpath.evaluate(xPath, ancestorNode, XPathConstants.NODESET);
}

From source file:it.imtech.metadata.MetaUtility.java

public String addClassificationLinkFromid(String id) {
    boolean found = false;
    String link = "";

    if (this.classificationIDS.containsValue(id)) {
        return Utility.getValueFromKey(this.classificationIDS, id);
    } else {//  w w w. j  a  va  2s. c  o  m
        for (String classificationLink : this.availableClassifications.keySet()) {
            try {
                if (found == false && !classificationIDS.containsKey(classificationLink)) {
                    Document doc = Utility.getDocument(classificationLink, true);
                    XPath taxonpath = XPathFactory.newInstance().newXPath();
                    String expression = "//*[local-name()='classification']";

                    NodeList nodeList = (NodeList) taxonpath.evaluate(expression, doc, XPathConstants.NODESET);

                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Element node = (Element) nodeList.item(i);

                        if (node.getAttribute("ID").equals(id)) {
                            classificationIDS.put(classificationLink, id);
                            link = classificationLink;
                            found = true;
                        } else {
                            classificationIDS.put(classificationLink, id);
                        }
                    }
                }
            } catch (ParserConfigurationException ex) {
                logger.error(ex.getMessage());
            } catch (SAXException ex) {
                logger.error(ex.getMessage());
            } catch (IOException ex) {
                logger.error(ex.getMessage());
            } catch (XPathExpressionException ex) {
                logger.error(ex.getMessage());
            }
        }

        return link;
    }
}

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

@Test
public void serviceProvidersHaveAtMostOnePublisher() throws XPathExpressionException {
    // Get the listed ServiceProvider elements
    NodeList nestedSPCs = (NodeList) OSLCUtils.getXPath().evaluate("/*/*//oslc_v2:serviceProvider", doc,
            XPathConstants.NODESET);

    // Make sure that for each one it only has at most one Publisher block
    for (int i = 0; i < nestedSPCs.getLength(); i++) {
        NodeList spcChildren = (NodeList) OSLCUtils.getXPath()
                .evaluate("/*/*//oslc_v2:serviceProvider[" + i + "]/*/*", doc, XPathConstants.NODESET);
        int publisherCount = 0;
        for (int j = 0; j < spcChildren.getLength(); j++) {
            if (spcChildren.item(j).getNamespaceURI().equals(OSLCConstants.DC)
                    && spcChildren.item(j).getLocalName().equals("publisher")) {
                publisherCount++;/*from w w  w  . j a  v  a2  s  .  c o  m*/
            }
        }
        assert (publisherCount <= 1);
    }
}

From source file:de.bayern.gdi.services.CatalogService.java

private String getServiceURL(Node serviceNode) {
    String onLineExpr = "gmd:distributionInfo" + "/gmd:MD_Distribution" + "/gmd:transferOptions"
            + "/gmd:MD_DigitalTransferOptions" + "/gmd:onLine";
    NodeList onlineNL = (NodeList) XML.xpath(serviceNode, onLineExpr, XPathConstants.NODESET, context);
    for (int j = 0; j < onlineNL.getLength(); j++) {
        Node onlineN = onlineNL.item(j);
        String urlExpr = "gmd:CI_OnlineResource" + GMD_LINKAGE + GMD_URL;
        String onLineserviceURL = (String) XML.xpath(onlineN, urlExpr, XPathConstants.STRING, context);
        String applicationprofileExpr = "gmd:CI_OnlineResource" + "/gmd:applicationProfile"
                + GCO_CHARACTER_STRING;/*from www .  j  a v  a  2  s.c o m*/
        String applicationProfile = (String) XML.xpath(onlineN, applicationprofileExpr, XPathConstants.STRING,
                context);
        applicationProfile = applicationProfile.toLowerCase();

        if (applicationProfile.equals("wfs-url") || applicationProfile.equals("feed-url")
                || applicationProfile.equals("dienste-url") || applicationProfile.equals("download")) {
            return onLineserviceURL;
        }
    }
    String operationMetaDataExpr = GMD_IDENTIFICATION_INFO + SRV_SV_SERVICE_IDENTIFICATION
            + "/srv:containsOperations";
    NodeList operationsMetadataNL = (NodeList) XML.xpath(serviceNode, operationMetaDataExpr,
            XPathConstants.NODESET, context);
    Node firstNode = null;
    for (int j = 0; j < operationsMetadataNL.getLength(); j++) {
        Node operationMetadataNode = operationsMetadataNL.item(j);
        if (j == 0) {
            firstNode = operationMetadataNode;
        }
        String operationsNameExpr = SV_OPERATION_METADATA + "/srv:operationName" + GCO_CHARACTER_STRING;
        String applicationProfile = (String) XML.xpath(operationMetadataNode, operationsNameExpr,
                XPathConstants.STRING, context);

        if (applicationProfile.equalsIgnoreCase("getcapabilities")) {
            String operationsURLExpr = SV_OPERATION_METADATA + "/srv:connectPoint" + "/gmd:CI_OnlineResource"
                    + GMD_LINKAGE + GMD_URL;
            String operationsURL = (String) XML.xpath(operationMetadataNode, operationsURLExpr,
                    XPathConstants.STRING, context);
            if (!operationsURL.isEmpty()) {
                return operationsURL;
            }
        }
    }
    if (firstNode != null) {
        String operationsURLExpr = SV_OPERATION_METADATA + "/srv:connectPoint" + "/gmd:CI_OnlineResource"
                + GMD_LINKAGE + GMD_URL;
        return (String) XML.xpath(firstNode, operationsURLExpr, XPathConstants.STRING, context);
    }
    return null;
}

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

/**
 *
 * @param job//from  www .  j  av a  2 s.  c o  m
 * @return
 * @throws WorkerException
*/
public List<URI> retrieveLink(String url) throws WorkerException {
    logger.debug("running crawler to: " + url);

    List<URI> urls = new ArrayList<URI>();
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", userAgent);
        HttpResponse response = client.execute(request);

        Header header = response.getFirstHeader("Content-Type");
        String contentType = header.getValue();
        logger.debug("Content-Type: " + contentType);
        if (contentType.toLowerCase().startsWith("text/html")) {
            DocumentBuilderFactory factory = new HTMLDocumentBuilderFactory();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(response.getEntity().getContent());

            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.create(url).resolve(href));
            }
        }
    } catch (Exception ex) {
        throw new WorkerException(ex);
    }
    return urls;
}

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

@Test
public void changeManagementServiceDescriptionHasValidSimpleQuery() throws XPathException {
    //If ServiceDescription is oslc_cm, make sure it has a valid simple query child element
    Node cmRequest = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:changeRequests", doc, XPathConstants.NODE);
    if (cmRequest != null) {
        NodeList sQ = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm:changeRequests/oslc_cm:simpleQuery",
                doc, XPathConstants.NODESET);
        assertTrue(sQ.getLength() == 1);
        Node url = (Node) OSLCUtils.getXPath()
                .evaluate("//oslc_cm:changeRequests/oslc_cm:simpleQuery/oslc_cm:url", doc, XPathConstants.NODE);
        assertNotNull(url);//from   w w  w  . j  ava  2  s .  c  om
        Node title = (Node) OSLCUtils.getXPath()
                .evaluate("//oslc_cm:changeRequests/oslc_cm:simpleQuery/dc:title", doc, XPathConstants.NODE);
        assertNotNull(title);
        assertFalse(title.getTextContent().isEmpty());
    }
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

private static void deleteCSE(String authtoken, String cseName)
        throws IOException, ParserConfigurationException, XPathExpressionException {
    // see http://code.google.com/apis/customsearch/docs/api.html

    String url = "http://www.google.com/cse/api/default/annotations/?num=5000"; // w/o num param, returns only top 20 results
    GetMethod get = new GetMethod(url);
    get.addRequestHeader("Content-type", "text/xml");
    get.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);
    int statusCode = new HttpClient().executeMethod(get);
    if (statusCode != HttpStatus.SC_OK) {
        log.warn(//w  w w. j  a va  2  s .  c  om
                "Unable to read Google CSE annotations, and therefore unable to delete existing annotations! HTTP status = "
                        + statusCode);
        return;
    }

    /* sample xml: 
    <?xml version="1.0" encoding="UTF-8" ?>
    <Annotations start="0" num="2182" total="2182">
    <Annotation about="visualizing.stanford.edu/*" score="0.000810373" timestamp="0x0004b2a4c7d271fd" href="Chp2aXN1YWxpemluZy5zdGFuZm9yZC5lZHUvKhD948m-zNSsAg">
    <Label name="_cse_testengine" />
    <AdditionalData attribute="original_url" value="http://visualizing.stanford.edu/*" />
       </Annotation>
    ...
     */

    // parse xml and get href's for the annotations for this cse.
    String responseBody = IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8");
    InputSource is = new InputSource(new StringReader(responseBody));
    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "/Annotations/Annotation/Label[@name='_cse_" + cseName + "']";
    NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET);
    List<String> hrefs = new ArrayList<String>();
    log.info(nodes.getLength() + " existing annotation(s) for search engine " + cseName
            + ". They will be deleted.");
    for (int i = 0; i < nodes.getLength(); i++) {
        Node label = nodes.item(i);
        Node annotation = label.getParentNode();
        Node hrefNode = annotation.getAttributes().getNamedItem("href");
        String href = hrefNode.getNodeValue();
        hrefs.add(href);
    }

    // hrefs now has all the existing href's for this CSE. send a remove command with these href's.
    StringBuilder removeXML = new StringBuilder("<Batch><Remove><Annotations>");
    int batchCount = 0;
    for (Iterator<String> it = hrefs.iterator(); it.hasNext();) {
        String href = it.next();
        removeXML.append(" <Annotation href=\"" + href + "\" />");
        batchCount++;
        if (batchCount == ANNOTATION_UPLOAD_BATCH_SIZE || !it.hasNext()) {
            removeXML.append("</Annotations></Remove></Batch>");
            boolean success = pushAnnotations(authtoken, removeXML.toString());
            if (!success)
                log.warn("Failed to delete " + batchCount + " existing annotations for search engine " + cseName
                        + " xml = " + removeXML);
            else
                log.info("Successfully deleted " + batchCount + " existing annotations for search engine "
                        + cseName);
            removeXML = new StringBuilder("<Batch><Remove><Annotations>");
            batchCount = 0;
        }
    }
}

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

@Test
public void changeRequestHasAtMostInProgressElement() throws XPathExpressionException {
    NodeList inProgressEles = (NodeList) OSLCUtils.getXPath()
            .evaluate("//oslc_cm_v2:ChangeRequest/" + "oslc_cm_v2:inprogress", doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), inProgressEles.getLength() <= 1);
}

From source file:io.cloudslang.dependency.impl.services.DependencyServiceImpl.java

private void removeByXpathExpression(String pomFilePath, String expression) throws SAXException, IOException,
        ParserConfigurationException, XPathExpressionException, TransformerException {
    File xmlFile = new File(pomFilePath);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nl = (NodeList) xpath.compile(expression).evaluate(doc, XPathConstants.NODESET);

    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            node.getParentNode().removeChild(node);
        }/* ww w .j av  a  2s  . c  o m*/

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        // need to convert to file and then to path to override a problem with spaces
        Result output = new StreamResult(new File(pomFilePath).getPath());
        Source input = new DOMSource(doc);
        transformer.transform(input, output);
    }
}