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.betfair.testing.utils.cougar.assertions.AssertionUtils.java

private static void doDomSorting(Document doc, XPath xpath, String x)
        throws XPathExpressionException, IOException {
    NodeList parentNodes = (NodeList) xpath.evaluate(x, doc, XPathConstants.NODESET);
    for (int i = 0; i < parentNodes.getLength(); i++) {
        Node n = parentNodes.item(i);
        List<Node> allKids = new ArrayList<>(n.getChildNodes().getLength());
        for (int j = n.getChildNodes().getLength() - 1; j >= 0; j--) {
            allKids.add(n.removeChild(n.getFirstChild()));
        }/* w w  w  . j  a  va 2  s .  c  o m*/
        final Map<Node, String> kidsToString = new HashMap<>();

        for (Node k : allKids) {
            kidsToString.put(k, toString(k));
        }
        Collections.sort(allKids, new Comparator<Node>() {
            @Override
            public int compare(Node o1, Node o2) {
                return kidsToString.get(o1).compareTo(kidsToString.get(o2));
            }
        });
        for (Node k : allKids) {
            n.appendChild(k);
        }
    }
}

From source file:de.egore911.versioning.deployer.performer.PerformReplacement.java

public void perform(Node serverDeploymentsDeploymentNode) throws XPathExpressionException {
    NodeList replacementOperations = (NodeList) replaceXpath.evaluate(serverDeploymentsDeploymentNode,
            XPathConstants.NODESET);
    for (int j = 0; j < replacementOperations.getLength(); j++) {
        Node replacementOperation = replacementOperations.item(j);

        String basepath = (String) basepathXpath.evaluate(replacementOperation, XPathConstants.STRING);
        NodeList wildcardNodes = (NodeList) wildcardsWildcardXpath.evaluate(replacementOperation,
                XPathConstants.NODESET);
        List<String> wildcards = new ArrayList<>();
        for (int k = 0; k < wildcardNodes.getLength(); k++) {
            Node wildcard = wildcardNodes.item(k);
            wildcards.add(wildcard.getNodeValue());
        }//w  w  w. jav a 2  s  .  c om

        NodeList replacementsNodes = (NodeList) replacementsReplacementXpath.evaluate(replacementOperation,
                XPathConstants.NODESET);

        List<ReplacementPair> replacements = new ArrayList<>();
        for (int k = 0; k < replacementsNodes.getLength(); k++) {
            Node replacement = replacementsNodes.item(k);
            String variable = (String) variableXpath.evaluate(replacement, XPathConstants.STRING);
            String value = (String) valueXpath.evaluate(replacement, XPathConstants.STRING);
            replacements.add(new ReplacementPair(variable, value));
        }

        NodeList replacementfilesNodes = (NodeList) replacementfileReplacementfileXpath
                .evaluate(replacementOperation, XPathConstants.NODESET);

        List<File> replacementfiles = new ArrayList<>();
        for (int k = 0; k < replacementfilesNodes.getLength(); k++) {
            Node replacementfile = replacementfilesNodes.item(k);
            File file = new File(replacementfile.getNodeValue());
            if (!file.exists()) {
                LOG.error("Could not find file {}, replacements will be likely incomplete", file);
            }
            replacementfiles.add(file);
        }

        perform(new File(basepath), wildcards, replacements, replacementfiles);

    }
}

From source file:com.fortysevendeg.lab.WeatherTask.java

/**
 * Performs work in the background invoking the weather remote service and parses the xml results into temp values
 * @param strings the place params to search form
 * @return the temperature in celsius//from  w  w w  .  ja v a2  s.c o  m
 */
@Override
protected final Integer doInBackground(String... strings) {
    int temp = ERROR;
    try {
        String xml = fetchWeatherData(strings[0]);
        if (xml != null) {
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(context.getString(R.string.xpath_weather_service_temperature));
            Object result = expr.evaluate(new InputSource(new StringReader(xml)), XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            if (nodes.getLength() > 0) {
                temp = Integer.valueOf(nodes.item(0).getAttributes().getNamedItem("data").getNodeValue());
            }
        }
    } catch (XPathExpressionException e) {
        Log.wtf(WeatherTask.class.toString(), e);
    } catch (IOException e) {
        Log.wtf(WeatherTask.class.toString(), e);
    }
    return temp;
}

From source file:org.opencastproject.remotetest.server.MaintenanceModeTest.java

@Test
public void testMaintenanceMode() throws Exception {
    // Ensure that there is a service available
    HttpGet availableServicesGet = new HttpGet(
            Main.BASE_URL + "/services/available.xml?serviceType=" + SERVICE_TYPE);
    HttpResponse availableServicesResponse = client.execute(availableServicesGet);
    Assert.assertEquals(HttpStatus.SC_OK, availableServicesResponse.getStatusLine().getStatusCode());
    String availableServicesXml = EntityUtils.toString(availableServicesResponse.getEntity());
    NodeList availableServicesNodes = (NodeList) Utils.xpath(availableServicesXml,
            "//*[local-name() = 'service']", XPathConstants.NODESET);
    Assert.assertTrue(availableServicesNodes.getLength() == 1);

    // Start a job
    HttpPost postJob = new HttpPost(Main.BASE_URL + "/services/job");
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    formParams.add(new BasicNameValuePair("jobType", SERVICE_TYPE));
    formParams.add(new BasicNameValuePair("host", Main.BASE_URL));
    formParams.add(new BasicNameValuePair("operation", "test"));
    formParams.add(new BasicNameValuePair("start", "false"));
    postJob.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

    // Ensure that the job was created successfully
    HttpResponse jobResponse = client.execute(postJob);
    EntityUtils.toString(jobResponse.getEntity()); // read the response so the connection can be closed
    Assert.assertEquals(HttpStatus.SC_CREATED, jobResponse.getStatusLine().getStatusCode());

    // Put the server into maintenance mode
    HttpPost postMaintenance = new HttpPost(Main.BASE_URL + "/services/maintenance");
    List<NameValuePair> maintenanceParams = new ArrayList<NameValuePair>();
    maintenanceParams.add(new BasicNameValuePair("host", Main.BASE_URL));
    maintenanceParams.add(new BasicNameValuePair("maintenance", "true"));
    postMaintenance.setEntity(new UrlEncodedFormEntity(maintenanceParams, "UTF-8"));

    // Ensure that the server was put into maintenance mode
    HttpResponse maintenanceResponse = client.execute(postMaintenance);
    Assert.assertEquals(HttpStatus.SC_NO_CONTENT, maintenanceResponse.getStatusLine().getStatusCode());

    // The service should no longer be "available"
    availableServicesResponse = client.execute(availableServicesGet);
    Assert.assertEquals(HttpStatus.SC_OK, availableServicesResponse.getStatusLine().getStatusCode());
    availableServicesXml = EntityUtils.toString(availableServicesResponse.getEntity());
    availableServicesNodes = (NodeList) Utils.xpath(availableServicesXml, "//*[local-name() = 'service']",
            XPathConstants.NODESET);
    Assert.assertTrue(availableServicesNodes.getLength() == 0);

    // Try to start another job on this server. This should still be possible, even in maintenance mode, because the job
    // will be dispatched elsewhere.

    HttpResponse maintenanceModeJobCreationResponse = client.execute(postJob);
    EntityUtils.toString(maintenanceModeJobCreationResponse.getEntity());
    Assert.assertEquals(HttpStatus.SC_CREATED,
            maintenanceModeJobCreationResponse.getStatusLine().getStatusCode());

    // Restore the server to normal mode
    HttpPost postNormal = new HttpPost(Main.BASE_URL + "/services/maintenance");
    maintenanceParams.remove(1);/*from   ww  w .java2  s  . c  om*/
    maintenanceParams.add(new BasicNameValuePair("maintenance", "false"));
    postNormal.setEntity(new UrlEncodedFormEntity(maintenanceParams, "UTF-8"));

    // Ensure that the server was put into normal mode
    HttpResponse normalResponse = client.execute(postNormal);
    Assert.assertEquals(HttpStatus.SC_NO_CONTENT, normalResponse.getStatusLine().getStatusCode());
}

From source file:com.vitembp.services.imaging.OverlayDefinition.java

/**
 * Initializes a new instance of the OverlayDefinition class.
 * @param toBuildFrom //from w w  w .j a  va  2  s.c om
 */
private OverlayDefinition(String toBuildFrom) throws IOException {
    // load the definition from XML using xpath methods
    // first parse the document
    Document def;
    try {
        def = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(toBuildFrom.getBytes(Charsets.UTF_8)));
    } catch (ParserConfigurationException | SAXException | IOException ex) {
        throw new IOException("Could not parse XML input.", ex);
    }
    // prevents issues caused by parser returning multiple text elements for
    // a single text area
    def.getDocumentElement().normalize();

    // get the overlay type
    XPath xPath = XPathFactory.newInstance().newXPath();
    try {
        Node type = (Node) xPath.evaluate("/overlay/type", def, XPathConstants.NODE);
        this.overlayType = OverlayType.valueOf(type.getTextContent());
    } catch (XPathExpressionException | IllegalArgumentException ex) {
        throw new IOException("Exception parsing type.", ex);
    }

    // get element definitions
    try {
        NodeList elements = (NodeList) xPath.evaluate("/overlay/elements/element", def, XPathConstants.NODESET);

        this.elementDefinitions = new ArrayList<>();
        for (int i = 0; i < elements.getLength(); i++) {
            this.elementDefinitions.add(new ElementDefinition(elements.item(i)));
        }
    } catch (XPathExpressionException | IllegalArgumentException ex) {
        throw new IOException("Exception parsing elements.", ex);
    }
}

From source file:nl.surfnet.sab.SabResponseParser.java

public SabRoleHolder parse(InputStream inputStream) throws IOException {

    String organisation = null;//from w w w.ja  v  a2 s . c  o  m
    List<String> roles = new ArrayList<String>();
    XPath xpath = getXPath();
    try {
        Document document = createDocument(inputStream);
        validateStatus(document, xpath);

        // Extract organisation
        XPathExpression organisationExpr = xpath.compile(XPATH_ORGANISATION);
        NodeList nodeList = (NodeList) organisationExpr.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; nodeList != null && i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node != null) {
                organisation = StringUtils.trimWhitespace(node.getTextContent());
                node.getParentNode().getTextContent();
            }
        }

        // Extract roles
        XPathExpression rolesExpr = xpath.compile(XPATH_ROLES);
        NodeList rolesNodeList = (NodeList) rolesExpr.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; rolesNodeList != null && i < rolesNodeList.getLength(); i++) {
            Node node = rolesNodeList.item(i);
            if (node != null) {
                roles.add(StringUtils.trimWhitespace(node.getTextContent()));
            }
        }

    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new IOException(e);
    }
    return new SabRoleHolder(organisation, roles);
}

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

private static NodeList getNodeList(final Node xmlNode, final String xpathString) {

    try {//from  ww w  .ja v a 2 s  . c  om

        final XPathExpression expr = createXPathExpression(xpathString);
        return (NodeList) expr.evaluate(xmlNode, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {

        throw new RuntimeException(e);
    }
}

From source file:com.espertech.esper.event.xml.XPathPropertyGetter.java

/**
 * Ctor./* ww w.  j a  v a2  s.c  o m*/
 * @param propertyName is the name of the event property for which this getter gets values
 * @param expressionText is the property expression itself
 * @param xPathExpression is a compile XPath expression
 * @param resultType is the resulting type
 * @param optionalCastToType if non-null then the return value of the xpath expression is cast to this value
 * @param fragmentFactory for creating fragments, or null in none to be created
 */
public XPathPropertyGetter(String propertyName, String expressionText, XPathExpression xPathExpression,
        QName resultType, Class optionalCastToType, FragmentFactory fragmentFactory) {
    this.expression = xPathExpression;
    this.expressionText = expressionText;
    this.property = propertyName;
    this.resultType = resultType;
    this.fragmentFactory = fragmentFactory;

    if ((optionalCastToType != null) && (optionalCastToType.isArray())) {
        isCastToArray = true;
        if (!resultType.equals(XPathConstants.NODESET)) {
            throw new IllegalArgumentException(
                    "Array cast-to types require XPathConstants.NODESET as the XPath result type");
        }
        optionalCastToType = optionalCastToType.getComponentType();
    } else {
        isCastToArray = false;
    }

    if (optionalCastToType != null) {
        simpleTypeParser = SimpleTypeParserFactory.getParser(optionalCastToType);
    } else {
        simpleTypeParser = null;
    }
    if (optionalCastToType == Node.class) {
        this.optionalCastToType = null;
    } else {
        this.optionalCastToType = optionalCastToType;
    }
}

From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java

public void perform(Node serverDeploymentsDeploymentNode) throws XPathExpressionException {
    NodeList extractionOperations = (NodeList) extractXpath.evaluate(serverDeploymentsDeploymentNode,
            XPathConstants.NODESET);
    for (int j = 0; j < extractionOperations.getLength(); j++) {
        Node extractionOperation = extractionOperations.item(j);
        String uri = (String) urlXpath.evaluate(extractionOperation, XPathConstants.STRING);
        NodeList extractions = (NodeList) extractionsExtractionXpath.evaluate(extractionOperation,
                XPathConstants.NODESET);
        List<ExtractionPair> exts = new ArrayList<>();
        for (int k = 0; k < extractions.getLength(); k++) {
            Node extraction = extractions.item(k);
            String source = (String) sourceXpath.evaluate(extraction, XPathConstants.STRING);
            String destination = (String) destinationXpath.evaluate(extraction, XPathConstants.STRING);
            exts.add(new ExtractionPair(source, destination));
        }// w ww .j  a v a2s  .co  m
        extract(uri, exts);
    }
}

From source file:ch.dbs.actions.bestellung.EZBVascoda.java

/**
 * This class uses the EZB API from//  w w w . j a  va  2s.  c  om
 * http://ezb.uni-regensburg.de/ezeit/vascoda/openURL?pid=format%3Dxml. This
 * API differs from the EZB/ZDB API (http://services.dnb.de). It brings back
 * no print information and other information for electronic holdings. It
 * seems to be more stable.
 */
public EZBForm read(final String content) {

    final EZBForm ezbform = new EZBForm();

    try {

        if (content != null) {

            final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            final DocumentBuilder builder = domFactory.newDocumentBuilder();
            final Document doc = builder.parse(new InputSource(new StringReader(content)));

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

            // issns
            final XPathExpression exprRefE = xpath.compile("//OpenURLResponse");
            final NodeList resultListRefE = (NodeList) exprRefE.evaluate(doc, XPathConstants.NODESET);

            String title = null;
            String levelAvailable = null;

            for (int i = 0; i < resultListRefE.getLength(); i++) {
                final Node firstResultNode = resultListRefE.item(i);
                final Element result = (Element) firstResultNode;

                // First ISSN
                //                    final String issn = getValue(result.getElementsByTagName("issn"));
                //                    System.out.println(issn);

                // title
                // unfortunately this will bring back the title sent by OpenURL, unless if not
                // specified in the OpenURL request. It then brings back the title form the EZB...!
                title = getValue(result.getElementsByTagName("title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    title = Jsoup.parse(title).text();
                }

                // this is the overall level of the best match and not the level of each individual result
                final NodeList levelNode = result.getElementsByTagName("available");
                final Element levelElement = (Element) levelNode.item(0);
                if (levelElement != null) {
                    levelAvailable = levelElement.getAttribute("level");
                }

            }

            // electronic data
            final XPathExpression exprE = xpath.compile("//OpenURLResponse/OpenURLResult/Resultlist/Result");
            final NodeList resultListE = (NodeList) exprE.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListE.getLength(); i++) {
                final Node firstResultNode = resultListE.item(i);
                final Element result = (Element) firstResultNode;

                final NodeList state = result.getElementsByTagName("access");
                final Element stateElement = (Element) state.item(0);
                int color = 0;
                if (stateElement != null) {
                    color = Integer.valueOf(stateElement.getAttribute("color"));
                }

                final EZBDataOnline online = new EZBDataOnline();

                // state
                // 1 free accessible
                if (color == EZBState.FREE.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.free");
                    online.setState(JOPState.FREE.getValue()); // translate state to EZB/ZDB-API
                    // 2 licensed ; 3 partially licensed
                } else if (color == EZBState.LICENSED.getValue()
                        || color == EZBState.LICENSED_PARTIALLY.getValue()) {
                    online.setAmpel("yellow");
                    online.setComment("availresult.abonniert");
                    online.setState(JOPState.LICENSED.getValue()); // translate state to EZB/ZDB-API
                    // not licensed
                } else if (color == EZBState.NOT_LICENSED.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                    online.setState(JOPState.NOT_LICENSED.getValue()); // translate state to EZB/ZDB-API
                } else {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                    online.setState(JOPState.NOT_LICENSED.getValue()); // translate state to EZB/ZDB-API
                }

                // LinkToArticle not always present
                String url = getValue(result.getElementsByTagName("LinkToArticle"));
                // LinkToJournal always present
                if (url == null) {
                    url = getValue(result.getElementsByTagName("LinkToJournal"));
                }
                online.setUrl(url);

                // try to get level from link
                String levelLinkToArticle = null;
                final NodeList levelNode = result.getElementsByTagName("LinkToArticle");
                final Element levelElement = (Element) levelNode.item(0);
                if (levelElement != null) {
                    levelLinkToArticle = levelElement.getAttribute("level");
                }

                if (levelLinkToArticle != null) {
                    online.setLevel(levelLinkToArticle); // specific level of each result
                } else {
                    online.setLevel(levelAvailable); // overall level of best match
                }

                if (title != null) {
                    online.setTitle(title);
                } else {
                    online.setTitle(url);
                }
                online.setReadme(getValue(result.getElementsByTagName("LinkToReadme")));

                ezbform.getOnline().add(online);
            }

            // Title not found
            if (resultListE.getLength() == 0) {
                final EZBDataOnline online = new EZBDataOnline();
                online.setAmpel("red");
                online.setComment("availresult.nohits");
                online.setState(JOPState.NO_HITS.getValue()); // translate state to EZB/ZDB-API

                ezbform.getOnline().add(online);
            }

        }

    } catch (final XPathExpressionException e) {
        LOG.error(e.toString());
    } catch (final SAXParseException e) {
        LOG.error(e.toString());
    } catch (final SAXException e) {
        LOG.error(e.toString());
    } catch (final IOException e) {
        LOG.error(e.toString());
    } catch (final ParserConfigurationException e) {
        LOG.error(e.toString());
    } catch (final Exception e) {
        LOG.error(e.toString());
    }

    return ezbform;
}