Example usage for javax.xml.xpath XPath evaluate

List of usage examples for javax.xml.xpath XPath evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPath evaluate.

Prototype

public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate an XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:com.cisco.dvbu.ps.common.adapters.config.SoapHttpConfig.java

private void parse(Document doc) throws AdapterException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {/*w  ww  . ja v a2  s  . c om*/
        Element e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_ENDPOINTS, doc, XPathConstants.NODE);
        if (e != null) {
            NodeList nlList = e.getElementsByTagName(AdapterConstants.CONNECTOR_SH_ENDPOINT);
            if (nlList != null && nlList.item(0) != null) {
                for (int i = 0; i < nlList.getLength(); i++) {
                    Element elem = (Element) nlList.item(i);
                    connEndpoints.put(elem.getAttribute(AdapterConstants.CONNECTOR_SE_NAME),
                            elem.getTextContent());
                    log.debug(elem.getAttribute(AdapterConstants.CONNECTOR_SE_NAME) + ": "
                            + elem.getTextContent());
                }
            }
        }
    } catch (Exception e) {
        log.error("Configuration File Error! One or more mandatory configuration options are missing");
        throw new AdapterException(403,
                "Configuration File Error! One or more mandatory configuration options are missing.", e);
    }
    try {
        parseCallbacks((Element) xpath.evaluate(AdapterConstants.XPATH_CALLBACKS, doc, XPathConstants.NODE));
    } catch (AdapterException ae) {
        throw ae;
    } catch (Exception e) {
        log.error("Configuration File Error! One or more mandatory configuration options are missing");
        throw new AdapterException(404,
                "Configuration File Error! One or more mandatory configuration options are missing.", e);
    }
}

From source file:it.isti.cnr.hpc.europeana.hackthon.domain.DbpediaMapper.java

private boolean load(String query) throws EntityException, NoResultException {

    boolean success = true;

    label = "";/*from w w w.  ja  v a2s  .c  o  m*/
    description = "";
    String queryUrl = produceQueryUrl(query);

    try {
        Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(queryUrl);

        if (response != null) {

            XPathFactory factory = XPathFactory.newInstance();
            XPath xPath = factory.newXPath();

            NodeList nodes = (NodeList) xPath.evaluate("/ArrayOfResult/Result", response,
                    XPathConstants.NODESET);

            if (nodes.getLength() != 0) {

                // WE TAKE THE FIRST ENTITY FROM DBPEDIA
                label = ((String) xPath.evaluate("Label", nodes.item(0), XPathConstants.STRING));

                description = ((String) xPath.evaluate("Description", nodes.item(0), XPathConstants.STRING))
                        .toLowerCase();

                NodeList classesList = (NodeList) xPath.evaluate("Classes/Class", nodes.item(0),
                        XPathConstants.NODESET);

                classes = new ArrayList<String>(classesList.getLength());
                for (int i = 0; i < classesList.getLength(); i++) {
                    Node n = classesList.item(i);
                    String clazz = (String) xPath.evaluate("Label", n, XPathConstants.STRING);
                    classes.add(clazz);
                }
            }
            if (label.isEmpty()) {
                success = false;
                label = query;
            }

        }
    } catch (Exception e) {
        logger.error("Error during the mapping of the query " + query + " on dbPedia (" + e.toString() + ")");

        if (e.toString().contains("sorry")) {
            try {
                Thread.sleep(60000 * 5);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        success = false;

    } catch (Error e) {
        logger.error("Error during the mapping of the query " + query + " on dbPedia (" + e.toString() + ")");
        if (e.toString().contains("sorry")) {
            try {
                Thread.sleep(60000 * 5);
            } catch (InterruptedException e1) {
                throw new EntityException("Error during the mapping of the query " + query + " on dbPedia ("
                        + e.toString() + ")");
            }
        }
        success = false;

    }

    if (!success) {
        throw new NoResultException("mapping to dbpedia failed for query " + query);
    }
    return success;
}

From source file:com.oracle.tutorial.jdbc.RSSFeedsTable.java

public void addRSSFeed(String fileName) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, TransformerConfigurationException, TransformerException, SQLException {
    // Parse the document and retrieve the name of the RSS feed

    String titleString = null;//from   w  ww. j a va2s.  co  m

    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    Node titleElement = (Node) xPath.evaluate("/rss/channel/title[1]", doc, XPathConstants.NODE);

    if (titleElement == null) {
        System.out.println("Unable to retrieve title element");
        return;
    } else {
        titleString = titleElement.getTextContent().trim().toLowerCase().replaceAll("\\s+", "_");
        System.out.println("title element: [" + titleString + "]");
    }

    System.out.println(JDBCTutorialUtilities.convertDocumentToString(doc));

    PreparedStatement insertRow = null;
    SQLXML rssData = null;

    System.out.println("Current DBMS: " + this.dbms);

    try {
        if (this.dbms.equals("mysql")) {
            // For databases that support the SQLXML data type, this creates a
            // SQLXML object from org.w3c.dom.Document.

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values" + " (?, ?)";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);

            System.out.println("Creating SQLXML object with MySQL");
            rssData = con.createSQLXML();
            System.out.println("Creating DOMResult object");
            DOMResult dom = (DOMResult) rssData.setResult(DOMResult.class);
            dom.setNode(doc);

            insertRow.setSQLXML(2, rssData);
            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

        else if (this.dbms.equals("derby")) {

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values"
                    + " (?, xmlparse(document cast (? as clob) preserve whitespace))";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);
            String convertedDoc = JDBCTutorialUtilities.convertDocumentToString(doc);
            insertRow.setClob(2, new StringReader(convertedDoc));

            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } catch (Exception ex) {
        System.out.println("Another exception caught:");
        ex.printStackTrace();
    }

    finally {
        if (insertRow != null) {
            insertRow.close();
        }
    }
}

From source file:com.act.lcms.LCMSmzMLParser.java

protected LCMSSpectrum handleSpectrumEntry(Document doc) throws XPathException {
    XPath xpath = getXPathFactory().newXPath();

    Double spectrumIndexD = (Double) xpath.evaluate(SPECTRUM_PATH_INDEX, doc, XPathConstants.NUMBER);
    if (spectrumIndexD == null) {
        System.err.format("WARNING: found spectrum document without index attribute.\n");
        return null;
    }/* w w  w. j a  v a  2s .  com*/
    Integer spectrumIndex = spectrumIndexD.intValue();

    if (xpath.evaluate(SPECTRUM_PATH_EXPECTED_VERSION, doc, XPathConstants.NODE) == null) {
        // if it is not MS1 Spectrum data then we will skip from the output.

        // check if it entry we see here is the diode array data, those we expect to silently skip
        // if on the other hand, even that is not matched; we truly have some unexpected entries, so report to user
        if (xpath.evaluate(SPECTRUM_PATH_EXPECTED_VERSION_DIODE_ARRAY, doc, XPathConstants.NODE) == null) {
            System.err.format(
                    "WARNING: found unexpected MS spectrum version in spectrum document %d.  Skipping.\n",
                    spectrumIndex);
        }

        return null;
    }

    String spectrumId = (String) xpath.evaluate(SPECTRUM_PATH_ID, doc, XPathConstants.STRING);
    if (spectrumId == null) {
        System.err.format("WARNING: no spectrum id found for documnt %d\n", spectrumIndex);
        return null;
    }

    Matcher matcher = SPECTRUM_EXTRACTION_REGEX.matcher(spectrumId);
    if (!matcher.find()) {
        System.err.format("WARNING: spectrum id for documnt %d did not match regex: %s\n", spectrumIndex,
                spectrumId);
        return null;
    }
    Integer spectrumFunction = Integer.parseInt(matcher.group(1));
    Integer spectrumScan = Integer.parseInt(matcher.group(3));

    Integer scanListCount = ((Double) xpath.evaluate(SPECTRUM_PATH_SCAN_LIST_COUNT, doc, XPathConstants.NUMBER))
            .intValue();
    if (!Integer.valueOf(1).equals(scanListCount)) {
        System.err.format("WARNING: unexpected number of scan entries in spectrum document %d: %d",
                spectrumIndex, scanListCount);
        return null;
    }

    Integer binaryDataCount = ((Double) xpath.evaluate(SPECTRUM_PATH_BINARY_DATA_ARRAY_LIST_COUNT, doc,
            XPathConstants.NUMBER)).intValue();
    if (!Integer.valueOf(2).equals(binaryDataCount)) {
        System.err.format("WARNING: unexpected number of binary data entries in spectrum document %d: %d",
                spectrumIndex, binaryDataCount);
        return null;
    }

    Double basePeakMz = (Double) xpath.evaluate(SPECTRUM_PATH_BASE_PEAK_MZ, doc, XPathConstants.NUMBER);
    if (basePeakMz == null) {
        System.err.format("WARNING: no base peak m/z found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    Double basePeakIntensity = (Double) xpath.evaluate(SPECTRUM_PATH_BASE_PEAK_INTENSITY, doc,
            XPathConstants.NUMBER);
    if (basePeakIntensity == null) {
        System.err.format("WARNING: no base peak intensity found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    Double scanStartTime = (Double) xpath.evaluate(SPECTRUM_PATH_SCAN_START_TIME, doc, XPathConstants.NUMBER);
    if (scanStartTime == null) {
        System.err.format("WARNING: no scan start time found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    String scanStartTimeUnit = (String) xpath.evaluate(SPECTRUM_PATH_SCAN_START_TIME_UNIT, doc,
            XPathConstants.STRING);
    if (scanStartTimeUnit == null) {
        System.err.format("WARNING: no scan start time unit found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    String mzData = (String) xpath.evaluate(SPECTRUM_PATH_MZ_BINARY_DATA, doc, XPathConstants.STRING);
    if (mzData == null) {
        System.err.format("WARNING: no m/z data found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    String intensityData = (String) xpath.evaluate(SPECTRUM_PATH_INTENSITY_BINARY_DATA, doc,
            XPathConstants.STRING);
    if (intensityData == null) {
        System.err.format("WARNING: no intensity data found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    List<Double> mzs = base64ToDoubleList(mzData);
    List<Double> intensities = base64ToDoubleList(intensityData);
    List<Pair<Double, Double>> mzIntensityPairs = zipLists(mzs, intensities);

    return new LCMSSpectrum(spectrumIndex, scanStartTime, scanStartTimeUnit, mzIntensityPairs, basePeakMz,
            basePeakIntensity, spectrumFunction, spectrumScan, null);
}

From source file:com.sixsq.slipstream.DeploymentController.java

private String[] extractRunStatusAndState(String xml) {

    try {/*from w w  w  .  ja v  a2  s . c o m*/

        InputSource xmlSource = new InputSource(new StringReader(xml));

        XPathFactory xpfactory = XPathFactory.newInstance();
        XPath xpath = xpfactory.newXPath();
        Object result = xpath.evaluate(STATUS_ATTRS, xmlSource, STRING);
        String data = result.toString();
        return data.split(",");

    } catch (XPathExpressionException consumed) {
        return new String[] { "", "" };
    }
}

From source file:com.mirth.connect.plugins.datatypes.xml.XMLBatchAdaptor.java

private String getMessageFromReader() throws Exception {
    SplitType splitType = batchProperties.getSplitType();

    if (splitType == SplitType.Element_Name || splitType == SplitType.Level
            || splitType == SplitType.XPath_Query) {
        if (nodeList == null) {
            StringBuilder query = new StringBuilder();
            if (splitType == SplitType.Element_Name) {
                query.append("//*[local-name()='");
                query.append(batchProperties.getElementName());
                query.append("']");
            } else if (splitType == SplitType.Level) {
                query.append("/*");

                for (int i = 0; i < batchProperties.getLevel(); i++) {
                    query.append("/*");
                }//from  w w  w  .j  av  a2s  . c  om
            } else if (splitType == SplitType.XPath_Query) {
                query.append(batchProperties.getQuery());
            }

            XPath xpath = xPathFactory.newXPath();

            nodeList = (NodeList) xpath.evaluate(query.toString(), new InputSource(bufferedReader),
                    XPathConstants.NODESET);
        }

        if (currentNode < nodeList.getLength()) {
            Node node = nodeList.item(currentNode++);

            if (node != null) {
                return toXML(node);
            }
        }
    } else if (splitType == SplitType.JavaScript) {
        if (StringUtils.isEmpty(batchProperties.getBatchScript())) {
            throw new BatchMessageException("No batch script was set.");
        }

        try {
            final String batchScriptId = ScriptController.getScriptId(ScriptController.BATCH_SCRIPT_KEY,
                    sourceConnector.getChannelId());

            MirthContextFactory contextFactory = contextFactoryController
                    .getContextFactory(sourceConnector.getChannel().getResourceIds());
            if (!factory.getContextFactoryId().equals(contextFactory.getId())) {
                synchronized (factory) {
                    contextFactory = contextFactoryController
                            .getContextFactory(sourceConnector.getChannel().getResourceIds());
                    if (!factory.getContextFactoryId().equals(contextFactory.getId())) {
                        JavaScriptUtil.recompileGeneratedScript(contextFactory, batchScriptId);
                        factory.setContextFactoryId(contextFactory.getId());
                    }
                }
            }

            String result = JavaScriptUtil
                    .execute(new JavaScriptTask<String>(contextFactory, "XML Batch Adaptor", sourceConnector) {
                        @Override
                        public String doCall() throws Exception {
                            Script compiledScript = CompiledScriptCache.getInstance()
                                    .getCompiledScript(batchScriptId);

                            if (compiledScript == null) {
                                logger.error("Batch script could not be found in cache");
                                return null;
                            } else {
                                Logger scriptLogger = Logger
                                        .getLogger(ScriptController.BATCH_SCRIPT_KEY.toLowerCase());

                                try {
                                    Scriptable scope = JavaScriptScopeUtil.getBatchProcessorScope(
                                            getContextFactory(), scriptLogger, sourceConnector.getChannelId(),
                                            sourceConnector.getChannel().getName(),
                                            getScopeObjects(bufferedReader));
                                    return (String) Context.jsToJava(executeScript(compiledScript, scope),
                                            String.class);
                                } finally {
                                    Context.exit();
                                }
                            }
                        }
                    });

            if (StringUtils.isEmpty(result)) {
                return null;
            } else {
                return result;
            }
        } catch (JavaScriptExecutorException e) {
            logger.error(e.getCause());
        } catch (Throwable e) {
            logger.error(e);
        }
    } else {
        throw new BatchMessageException("No valid batch splitting method configured");
    }

    return null;
}

From source file:de.avanux.livetracker.statistics.TrackingStatistics.java

private void setCountryCode(float lat, float lon) {
    Document doc = null;//from  w ww  . j av  a 2 s  . c  o  m
    HttpMethod method = null;
    InputStream responseBodyStream = null;
    String responseBodyString = null;
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        String uri = "http://www.geoplugin.net/extras/location.gp?lat=" + lat + "&long=" + lon + "&format=xml";
        log.debug("Retrieving country from " + uri);

        HttpClient client = new HttpClient();
        method = new GetMethod(uri);
        client.executeMethod(method);
        byte[] responseBodyBytes = method.getResponseBody();

        responseBodyString = new String(responseBodyBytes);
        log.debug("Content retrieved: " + responseBodyString);

        // the content is declared as UTF-8 but it seems to be iso-8859-1
        responseBodyString = new String(responseBodyBytes, "iso-8859-1");

        responseBodyStream = new StringBufferInputStream(responseBodyString);
        doc = builder.parse(responseBodyStream);

        XPath xpath = XPathFactory.newInstance().newXPath();
        this.countryCode = ((Node) xpath.evaluate("/geoPlugin/geoplugin_countryCode/text()", doc,
                XPathConstants.NODE)).getNodeValue();
        log.debug("countryCode=" + this.countryCode);
    } catch (Exception e) {
        if (responseBodyString != null) {
            log.error("unparsed xml=" + responseBodyString);
        }
        if (doc != null) {
            log.error("parsed xml=" + getDocumentAsString(doc));
        }
        log.error("Error getting country code.", e);
    } finally {
        try {
            if (responseBodyStream != null) {
                responseBodyStream.close();
            }
            if (method != null) {
                method.releaseConnection();
            }
        } catch (IOException e) {
            log.error("Error releasing resources: ", e);
        }
    }
}

From source file:pl.psnc.synat.wrdz.zmkd.format.UdfrSparqlEndpointAccessBean.java

/**
 * Retrieves the nodes from the given document using the given XPath path.
 * //from   w  ww.  j  a  va  2s .  c om
 * @param document
 *            the document to retrieve the nodes from
 * @param path
 *            XPath
 * @return list of matching nodes
 */
private NodeList xpath(Document document, String path) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContextImpl(NS_PREFIX, NS_URI));

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

From source file:com.mnxfst.testing.client.TSClientPlanExecCallable.java

/**
 * Parses the response code from the returned test plan execution result
 * @param rootNode/*from   w ww  . ja  va  2  s. com*/
 * @return
 * @throws TSClientExecutionException
 */
protected int parseResponseCode(Node rootNode, XPath xpath) throws TSClientExecutionException {

    String responseCode = null;
    try {
        responseCode = (String) xpath.evaluate(TEST_EXEC_RESPONSE_CODE, rootNode, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new TSClientExecutionException(
                "Failed to parse out response code from document received from " + httpHost.getHostName());
    }

    if (responseCode != null && !responseCode.isEmpty()) {
        try {
            return Integer.parseInt(responseCode);
        } catch (NumberFormatException e) {
            throw new TSClientExecutionException("Failed to parse response code '" + responseCode
                    + "' into a valid numerical value. Returning host: " + httpHost.getHostName());
        }
    }

    throw new TSClientExecutionException("No valid response code received from " + httpHost.getHostName());
}

From source file:com.mnxfst.testing.client.TSClientPlanExecCallable.java

/**
 * Parses the result identifier from the returned result
 * @param rootNode/*  w ww  .  ja  v a 2 s  .  c o  m*/
 * @return
 * @throws TSClientExecutionException
 */
protected String parseResultIdentifier(Node rootNode, XPath xpath) throws TSClientExecutionException {

    String resultIdentifier = null;
    try {
        resultIdentifier = (String) xpath.evaluate(TEST_EXEC_RESULT_IDENTIFIER, rootNode,
                XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new TSClientExecutionException(
                "Failed to parse out result identifier from document received from " + httpHost.getHostName());
    }

    if (resultIdentifier == null || resultIdentifier.isEmpty())
        throw new TSClientExecutionException(
                "Failed to parse out result identifier from document received from " + httpHost.getHostName());

    return resultIdentifier;
}