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.microsoft.alm.plugin.external.commands.Command.java

protected NodeList evaluateXPath(final String stdout, final String xpathQuery) {
    if (StringUtils.isEmpty(stdout)) {
        return null;
    }/*from   ww w .j  a  v  a 2  s. co m*/

    // Skip over any lines (like WARNing lines) that come before the xml tag
    // Example:
    // WARN -- Unable to construct Telemetry Client
    // <?xml ...
    final InputSource xmlInput;
    final int xmlStart = stdout.indexOf(XML_PREFIX);
    if (xmlStart > 0) {
        xmlInput = new InputSource(new StringReader(stdout.substring(xmlStart)));
    } else {
        xmlInput = new InputSource(new StringReader(stdout));
    }

    final XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        final Object result = xpath.evaluate(xpathQuery, xmlInput, XPathConstants.NODESET);
        if (result != null && result instanceof NodeList) {
            return (NodeList) result;
        }
    } catch (final XPathExpressionException inner) {
        throw new ToolParseFailureException(inner);
    }

    throw new ToolParseFailureException();
}

From source file:kevin.gvmsgarch.App.java

static String extractInboxJson(String authToken, Worker.ListLocation location, int page)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    String pageData = "";
    try {/*from w  w  w .jav a 2 s.c  o  m*/
        pageData = App.getInboxPage(authToken, location, page);
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(pageData.getBytes()));
        XPathExpression xpr = XPathFactory.newInstance().newXPath().compile("/response/json");
        NodeList nl = (NodeList) xpr.evaluate(doc, XPathConstants.NODESET);
        Node n = nl.item(0);
        return n.getTextContent();
    } catch (Exception ex) {
        throw new RuntimeException("Page data for error:\n\n" + pageData + "\n\n", ex);
    }
}

From source file:cz.mzk.editor.server.fedora.utils.FedoraUtils.java

/**
 * Find first page pid.//from   w  w  w .  ja  v a2 s. c o m
 * 
 * @param pid
 *        the pid
 * @return the string
 */
public static String findFirstPagePid(String pid) {

    ArrayList<String> pids = new ArrayList<String>();
    try {
        String command = configuration.getFedoraHost() + "/get/" + pid + "/RELS-EXT";
        InputStream is = RESTHelper.get(command, configuration.getFedoraLogin(),
                configuration.getFedoraPassword(), true);
        Document contentDom = XMLUtils.parseDocument(is);
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("/RDF/Description/*");
        NodeList nodes = (NodeList) expr.evaluate(contentDom, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node childnode = nodes.item(i);
            String nodeName = childnode.getNodeName();
            if (nodeName.contains(FedoraRelationship.hasPage.getStringRepresentation())
                    || nodeName.contains(FedoraRelationship.isOnPage.getStringRepresentation())) {
                return childnode.getAttributes().getNamedItem("rdf:resource").getNodeValue().split("uuid:")[1];
            } else if (!nodeName.contains("hasModel") && childnode.hasAttributes()
                    && childnode.getAttributes().getNamedItem("rdf:resource") != null) {
                pids.add(childnode.getAttributes().getNamedItem("rdf:resource").getNodeValue().split("/")[1]);
            }
        }
        for (String relpid : pids) {
            return FedoraUtils.findFirstPagePid(relpid);
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}

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

@Test
public void changeRequestHasAtMostOneCloseDate() throws XPathExpressionException {
    NodeList closeDates = (NodeList) OSLCUtils.getXPath()
            .evaluate("//oslc_cm_v2:ChangeRequest/" + "oslc_cm_v2:closeDate", doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), closeDates.getLength() <= 1);
    //If there is a close date, verify the format.
    if (closeDates.getLength() > 0) {
        try {/* w  w w .j a va 2 s .  c  om*/
            DatatypeConverter.parseDateTime(closeDates.item(0).getTextContent());
        } catch (Exception e) {
            fail("Modified date not in valid XSD format");
        }
    }
}

From source file:com.photon.phresco.impl.WindowsApplicationProcessor.java

private static void deleteFeature(File sourceFolderLocation, List<ArtifactGroup> deletedFeatures)
        throws PhrescoException {
    try {/*ww w . j ava2  s  . com*/
        File path = new File(sourceFolderLocation + File.separator + SOURCE_DIR + File.separator + SRC_DIR
                + File.separator + PROJECT_ROOT + File.separator + PROJECT_ROOT + CSPROJ_FILE);
        if (!path.exists() && CollectionUtils.isNotEmpty(deletedFeatures)) {
            return;
        }
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(false);
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(path);
        for (ArtifactGroup deleteFeature : deletedFeatures) {
            String feature = deleteFeature.getName();
            feature = "//Reference[@Include='" + feature + "']";
            XPath xpath = XPathFactory.newInstance().newXPath();
            javax.xml.xpath.XPathExpression expr = xpath.compile(feature);
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                Node item = nodes.item(i).getParentNode();
                item.getParentNode().removeChild(item);
            }
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(path.toURI().getPath());
        transformer.transform(source, result);

    } catch (XPathExpressionException e) {
        throw new PhrescoException(e);
    } catch (DOMException e) {
        throw new PhrescoException(e);
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (SAXException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (TransformerConfigurationException e) {
        throw new PhrescoException(e);
    } catch (TransformerException e) {
        throw new PhrescoException(e);
    }
}

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

@Test
public void fullTextSearchContainsExpectedResults()
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    //Build the fulltext query using oslc.searchTerms
    String query = "?" + additionalParameters + "&oslc.searchTerms="
            + URLEncoder.encode("\"" + fullTextSearchTerm + "\"", "UTF-8");

    String responseBody = runQuery(query, OSLCConstants.CT_XML);

    //Get XML Doc from response
    Document doc = OSLCUtils.createXMLDocFromResponseBody(responseBody);

    NodeList lst = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm_v2:ChangeRequest", doc,
            XPathConstants.NODESET);
    if (lst == null || lst.getLength() == 0) {
        lst = (NodeList) OSLCUtils.getXPath().evaluate("//rdf:Description", doc, XPathConstants.NODESET);
    }/* w  w  w  . ja v  a2s .  co m*/
    assertNotNull(lst);

    //Verify our fulltext search returned a result
    assertTrue("Exptected full text to respond with results", lst.getLength() > 0);
}

From source file:apiconnector.TestDataFunctionality.java

public static String toPrettyString(String xml, int indent) throws Exception {
    // Turn xml string into a document
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

    // Remove whitespaces outside tags
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }// w w  w.j a  va 2  s  . c  o m

    // Setup pretty print options
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", indent);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Return pretty print xml string
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
    return stringWriter.toString();
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Set<UpnpIgdServiceReference> parseServiceReferences(Map<UpnpIgdDevice, byte[]> rootBuffers) {
    Set<UpnpIgdServiceReference> services = new HashSet<>();
    for (Entry<UpnpIgdDevice, byte[]> rootBufferEntry : rootBuffers.entrySet()) {
        try {//from w w w.  j  a va 2s  .  c  o m
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new ByteArrayInputStream(rootBufferEntry.getValue()));

            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList serviceNodes = (NodeList) xPath.compile(".//service").evaluate(doc,
                    XPathConstants.NODESET);

            for (int i = 0; i < serviceNodes.getLength(); i++) {
                Node serviceNode = serviceNodes.item(i);

                String serviceType = StringUtils.trim(xPath.compile("serviceType").evaluate(serviceNode));
                String serviceId = StringUtils.trim(xPath.compile("serviceId").evaluate(serviceNode));
                String controlUrl = StringUtils.trim(xPath.compile("controlURL").evaluate(serviceNode));
                //String eventSubUrl = StringUtils.trim(xPath.compile("eventSubURL").evaluate(serviceNode));
                String scpdUrl = StringUtils.trim(xPath.compile("SCPDURL").evaluate(serviceNode));

                UpnpIgdServiceReference service = new UpnpIgdServiceReference(rootBufferEntry.getKey(),
                        serviceType, serviceId, controlUrl, scpdUrl);
                services.add(service);
            }
        } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException e) { // NOPMD
            // do nothing, just skip
        }
    }
    return services;
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public WebApp(File webAppDefinition) throws Exception {
    logger.info(String.format("Loading webapp definition \"%s\" ...", webAppDefinition.getAbsolutePath()));

    Context context = Context.getInstance();
    this.definition = webAppDefinition;
    this.homeDir = webAppDefinition.getParentFile();
    this.name = this.homeDir.getName();

    this.configuration = new XSLWebConfiguration(this);
    this.processor = new Processor(this.configuration.getConfiguration());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from ww  w .j ava2  s  .  c om
    dbf.setSchema(context.getWebAppSchema());
    dbf.setXIncludeAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(this);

    String defXml = IOUtils.toString(new XmlStreamReader(webAppDefinition));
    Properties vars = new Properties(System.getProperties());
    vars.setProperty("webapp-dir", webAppDefinition.getParentFile().getAbsolutePath().replace('\\', '/'));
    String resolvedDefXml = XSLWebUtils.resolveProperties(defXml, vars);
    // Document webAppDoc = db.parse(webAppDefinition);
    InputSource src = new InputSource(new StringReader(resolvedDefXml));
    src.setSystemId(webAppDefinition.getAbsolutePath());
    Document webAppDoc = db.parse(src);

    XPath xpath = new XPathFactoryImpl().newXPath();
    xpath.setNamespaceContext(XMLUtils.getNamespaceContext("webapp", Definitions.NAMESPACEURI_XSLWEB_WEBAPP));
    Node docElem = webAppDoc.getDocumentElement();
    this.title = (String) xpath.evaluate("webapp:title", docElem, XPathConstants.STRING);
    this.description = (String) xpath.evaluate("webapp:description", docElem, XPathConstants.STRING);
    String devModeValue = (String) xpath.evaluate("webapp:development-mode", docElem, XPathConstants.STRING);
    this.developmentMode = XMLUtils.getBooleanValue(devModeValue, false);
    String maxUploadSizeValue = (String) xpath.evaluate("webapp:max-upload-size", docElem,
            XPathConstants.STRING);
    this.maxUploadSize = XMLUtils.getIntegerValue(maxUploadSizeValue, 10);
    String waitForJobsAtCloseValue = (String) xpath.evaluate("webapp:wait-for-jobs-at-close", docElem,
            XPathConstants.STRING);
    this.waitForJobsAtClose = XMLUtils.getBooleanValue(waitForJobsAtCloseValue, true);

    NodeList resourceNodes = (NodeList) xpath.evaluate("webapp:resources/webapp:resource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < resourceNodes.getLength(); i++) {
        resources.add(new Resource((Element) resourceNodes.item(i)));
    }
    NodeList paramNodes = (NodeList) xpath.evaluate("webapp:parameters/webapp:parameter", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < paramNodes.getLength(); i++) {
        parameters.add(new Parameter(processor, (Element) paramNodes.item(i)));
    }
    NodeList jobNodes = (NodeList) xpath.evaluate("webapp:jobs/webapp:job", docElem, XPathConstants.NODESET);
    if (jobNodes.getLength() > 0) {
        File quartzFile = new File(homeDir, Definitions.FILENAME_QUARTZ);
        quartzFile = (quartzFile.isFile()) ? quartzFile
                : new File(context.getHomeDir(), "config" + File.separatorChar + Definitions.FILENAME_QUARTZ);
        SchedulerFactory sf;
        if (quartzFile.isFile()) {
            logger.info(String.format("Initializing Quartz scheduler using properties file \"%s\" ...",
                    quartzFile.getAbsolutePath()));
            Properties props = XSLWebUtils.readProperties(quartzFile);
            props.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, name);
            sf = new StdSchedulerFactory(props);
        } else {
            logger.info("Initializing Quartz scheduler ...");
            sf = new StdSchedulerFactory();
        }
        scheduler = sf.getScheduler();
        for (int i = 0; i < jobNodes.getLength(); i++) {
            Element jobElem = (Element) jobNodes.item(i);
            String jobName = XMLUtils.getValueOfChildElementByLocalName(jobElem, "name");
            String jobUri = XMLUtils.getValueOfChildElementByLocalName(jobElem, "uri");
            String jobCron = XMLUtils.getValueOfChildElementByLocalName(jobElem, "cron");
            boolean concurrent = XMLUtils
                    .getBooleanValue(XMLUtils.getValueOfChildElementByLocalName(jobElem, "concurrent"), true);
            String jobId = "job_" + name + "_" + jobName;
            JobDetail job = newJob(concurrent ? XSLWebJob.class : NonConcurrentExecutionXSLWebJob.class)
                    .withIdentity(jobId, name).usingJobData("webapp-path", getPath())
                    .usingJobData("uri", jobUri).build();
            Trigger trigger = newTrigger().withIdentity("trigger_" + name + "_" + jobName, name)
                    .withSchedule(cronSchedule(jobCron)).forJob(jobId, name).build();
            logger.info(String.format("Scheduling job \"%s\" of webapp \"%s\" ...", jobName, name));
            scheduler.scheduleJob(job, trigger);
        }
    }

    NodeList dataSourceNodes = (NodeList) xpath.evaluate("webapp:datasources/webapp:datasource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < dataSourceNodes.getLength(); i++) {
        DataSource dataSource = new DataSource((Element) dataSourceNodes.item(i));
        dataSources.put(dataSource.getName(), dataSource);
    }

    NodeList fopConfigNodes = (NodeList) xpath.evaluate("webapp:fop-configs/webapp:fop-config", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < fopConfigNodes.getLength(); i++) {
        Element fopConfig = (Element) fopConfigNodes.item(i);
        Element fopElement = XMLUtils.getFirstChildElement(fopConfig);
        fopConfigs.put(fopConfig.getAttribute("name"), XMLUtils.nodeToString(fopElement));
    }

    // initClassLoader();

    initFileAlterationObservers();
}

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

private List<String> getJourids(final String content) {

    final List<String> result = new ArrayList<String>();

    try {/*from w w w .  j av a  2  s  . co m*/

        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();

            final XPathExpression exprJournals = xpath.compile("//journals/journal");
            final NodeList journals = (NodeList) exprJournals.evaluate(doc, XPathConstants.NODESET);

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

                final String id = journal.getAttribute("jourid");

                if (id != null) {
                    result.add(id);
                }

            }
        }

    } 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 result;
}