Example usage for javax.xml.xpath XPathConstants NODE

List of usage examples for javax.xml.xpath XPathConstants NODE

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODE.

Prototype

QName NODE

To view the source code for javax.xml.xpath XPathConstants NODE.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

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

@Parameters
public static Collection<Object[]> getAllDescriptionUrls()
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    //Checks the ServiceProviderCatalog at the specified baseUrl of the REST service in order to grab all urls
    //to other ServiceProvidersCatalogs contained within it, recursively, in order to find the URLs of all
    //query factories of the REST service.
    String v = "//oslc_v2:QueryCapability/oslc_v2:queryBase/@rdf:resource";
    ArrayList<String> serviceUrls = getServiceProviderURLsUsingXML(null);
    ArrayList<String> capabilityURLsUsingXML = TestsBase.getCapabilityURLsUsingXML(v, serviceUrls, true);

    // Once we have the query URL, look for a resource to validate
    String where = setupProps.getProperty("changeRequestsWhere");
    if (where == null) {
        String queryProperty = setupProps.getProperty("queryEqualityProperty");
        String queryPropertyValue = setupProps.getProperty("queryEqualityValue");
        where = queryProperty + "=\"" + queryPropertyValue + "\"";
    }/*ww w. j a  v  a 2  s .c  om*/

    String additionalParameters = setupProps.getProperty("queryAdditionalParameters");
    String query = (additionalParameters.length() == 0) ? "?" : "?" + additionalParameters + "&";
    query = query + "oslc.where=" + URLEncoder.encode(where, "UTF-8") + "&oslc.pageSize=1";

    ArrayList<String> results = new ArrayList<String>();
    for (String queryBase : capabilityURLsUsingXML) {
        String queryUrl = OSLCUtils.addQueryStringToURL(queryBase, query);
        HttpResponse resp = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, basicCreds,
                OSLCConstants.CT_XML, headers);
        String respBody = EntityUtils.toString(resp.getEntity());
        EntityUtils.consume(resp.getEntity());
        assertTrue("Received " + resp.getStatusLine(),
                (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK));
        //Get XML Doc from response
        Document doc = OSLCUtils.createXMLDocFromResponseBody(respBody);
        //Check for results by reference (rdf:resource)
        Node result = (Node) OSLCUtils.getXPath().evaluate("//rdfs:member/@rdf:resource", doc,
                XPathConstants.NODE);
        if (result == null)
            //No results by reference. Check for inline results (rdf:about)
            result = (Node) OSLCUtils.getXPath().evaluate("//rdfs:member/oslc_cm_v2:ChangeRequest/@rdf:about",
                    doc, XPathConstants.NODE);
        if (result != null)
            results.add(result.getNodeValue());
        if (onlyOnce)
            break;
    }
    return toCollection(results);
}

From source file:com.esri.gpt.server.openls.provider.services.route.DetermineRouteProvider.java

/**
 * Handles an XML based request (normally HTTP POST).
 * /*from w  w  w. jav a 2  s. com*/
 * @param context
 *            the operation context
 * @param root
 *            the root node
 * @param xpath
 *            an XPath to enable queries (properly configured with name
 *            spaces)
 * @throws Exception
 */
public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception {

    // initialize
    LOGGER.finer("Handling xls:DetermineRouteProvider request XML...");
    String locator = "xls:DetermineRouteRequest";

    // service and version are parsed by the parent RequestHandler
    Node ndReq = (Node) xpath.evaluate(locator, root, XPathConstants.NODE);
    if (ndReq != null) {
        parseRequest(context, ndReq, xpath);
    }
    // TODO requestId
    try {
        executeRequest(context);
    } catch (Throwable e) {
        e.printStackTrace();
    }
    generateResponse(context);
}

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;
    }//from  www.ja  va2  s . c  o m
    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.hygenics.parser.ManualReplacement.java

private void transform() {
    log.info("Transforming");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    for (String fpath : fpaths) {
        log.info("FILE: " + fpath);
        try {/*from   www  . j a va 2  s .  co m*/
            // TRANSFORM
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(fpath));
            Node root = doc.getFirstChild();
            XPathFactory xfactory = XPathFactory.newInstance();
            XPath xpath = xfactory.newXPath();
            String database = null;
            String path = "//transformation/connection";

            log.info("Removing");
            for (String dbname : remove) {
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                if (conn != null) {
                    root.removeChild(conn);
                }
            }

            log.info("Transforming");
            for (String key : databaseAttributes.keySet()) {
                database = key;
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);

                if (conn != null) {
                    if (remove.contains(key)) {
                        root.removeChild(conn);
                    } else {
                        Map<String, String> attrs = databaseAttributes.get(database);
                        NodeList nl = conn.getChildNodes();
                        Set<String> keys = databaseAttributes.get(key).keySet();

                        for (int i = 0; i < nl.getLength(); i++) {
                            org.w3c.dom.Node n = nl.item(i);

                            if (keys.contains(n.getNodeName().trim())) {
                                n.setNodeValue(attrs.get(n.getNodeName()));
                            }
                        }
                    }
                }

                if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) {
                    log.info("Logging Manipulation");
                    log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null
                            ? "Removing Logging Data"
                            : "Adding Logging data");
                    String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table",
                            "step-log-table", "metrics-log-table" };
                    for (String section : sections) {
                        log.info("Changing Settings for " + section);
                        xepr = xpath.compile("//" + section + "/field/enabled");
                        NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET);
                        log.info("Nodes Found: " + Integer.toString(nodes.getLength()));
                        for (int i = 0; i < nodes.getLength(); i++) {
                            if (!this.log_to_table) {
                                nodes.item(i).setNodeValue("N");
                            } else {
                                nodes.item(i).setNodeValue("Y");
                            }
                        }

                        for (String nodeName : new String[] { "schema", "connection", "table",
                                "size_limit_lines", "interval", "timeout_days" }) {
                            if (!this.log_to_table) {
                                log.info("Changing Settings for Node: " + nodeName);
                                xepr = xpath.compile("//" + section + "/" + nodeName);
                                Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                                if (node != null) {
                                    if (!this.log_to_table) {
                                        node.setNodeValue(null);
                                    } else if (this.loggingTables.containsKey(section)
                                            && this.loggingTables.get(section).containsKey(nodeName)) {
                                        node.setNodeValue(this.loggingTables.get(section).get(nodeName));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // SET MAIN CONNECTION
            if (mainConnection != null) {
                XPathExpression xepr = xpath.compile(path);
                NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of
                // org.w3c it is
                // actually a NodeList
                for (int i = 0; i < conns.getLength(); i++) {
                    if (!conns.item(i).hasChildNodes()) {// only connection
                        // elements
                        // without child
                        // nodes have
                        // text content
                        conns.item(i).setNodeValue(mainConnection);
                    }
                }
            }

            if (this.replacements != null) {
                for (String key : this.replacements.keySet()) {
                    XPathExpression xepr = xpath.compile(key);
                    Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                    if (node != null) {
                        for (String attrVal : this.replacements.get(key).keySet()) {
                            log.info("Replacing Information at " + key + "at " + attrVal);
                            log.info("Replacement Will Be: "
                                    + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));

                            if (attrVal.toLowerCase().trim().equals("text")) {
                                node.setNodeValue(
                                        StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));
                                if (node.getNodeValue() == null) {
                                    node.setTextContent(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                }

                            } else {
                                NamedNodeMap nattrs = node.getAttributes();
                                Node n = nattrs.getNamedItem(attrVal);
                                if (n != null) {
                                    n.setNodeValue(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                } else {
                                    log.warn("Attribute Not Found " + attrVal);
                                }
                            }
                        }
                    } else {
                        log.warn("Node not found for " + key);
                    }
                }
            }

            // WRITE TO FILE
            log.info("Writing to File");
            TransformerFactory tfact = TransformerFactory.newInstance();
            Transformer transformer = tfact.newTransformer();
            DOMSource source = new DOMSource(doc);
            try (FileOutputStream stream = new FileOutputStream(new File(fpath))) {
                StreamResult result = new StreamResult(stream);
                transformer.transform(source, result);
                stream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.opencastproject.remotetest.server.perf.ConcurrentWorkflowTest.java

protected String getWorkflowInstanceId(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from  ww  w  . j ava 2s.co  m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
            .getAttribute("id");
}

From source file:com.esri.gpt.server.openls.provider.services.reversegeocode.ReverseGeocodeProvider.java

/**
 * Parses reverse geocode request./*from   ww w.j  a  va 2 s .  c om*/
 * @param context
 * @param ndReq
 * @param xpath
 * @throws XPathExpressionException
 */
private void parseRequest(OperationContext context, Node ndReq, XPath xpath) throws XPathExpressionException {
    ReverseGeocodeParams reqParams = context.getRequestOptions().getReverseGeocodeOptions();
    Node ndPosition = (Node) xpath.evaluate("xls:Position", ndReq, XPathConstants.NODE);
    if (ndPosition != null) {
        Node ndPoint = (Node) xpath.evaluate("gml:Point", ndPosition, XPathConstants.NODE);
        if (ndPoint != null) {
            Node ndPos = (Node) xpath.evaluate("gml:pos", ndPoint, XPathConstants.NODE);
            if (ndPos != null) {
                String[] vals = ndPos.getTextContent().split(" ");
                reqParams.setLat(vals[0]);
                reqParams.setLng(vals[1]);
            }
        }
    }
    Node ndPreference = (Node) xpath.evaluate("xls:ReverseGeocodePreference", ndReq, XPathConstants.NODE);
    if (ndPreference != null) {
        reqParams.setPreference(ndPreference.getTextContent());
    }
}

From source file:com.esri.gpt.server.openls.provider.services.poi.DirectoryProvider.java

/**
 * Parse directory request//  www  .  j a  va 2s . c  om
 * @param context
 * @param ndReq
 * @param xpath
 * @throws XPathExpressionException
 */
private void parseRequest(OperationContext context, Node ndReq, XPath xpath) throws XPathExpressionException {
    DirectoryParams params = context.getRequestOptions().getDirectoryOptions();
    HashMap<String, String> poiProperties = null;
    HashMap<String, Object> poiLocations = null;

    Node ndPoiLoc = (Node) xpath.evaluate("xls:POILocation", ndReq, XPathConstants.NODE);
    if (ndPoiLoc != null) {
        poiLocations = new HashMap<String, Object>();
        Node ndPos = (Node) xpath.evaluate("xls:Nearest/xls:Position/gml:Point/gml:pos", ndPoiLoc,
                XPathConstants.NODE);
        if (ndPos != null) {
            String[] xy = ndPos.getTextContent().split(" ");
            Point loc = new Point(xy[0], xy[1]);
            poiLocations.put("nearest", loc);
        }
        @SuppressWarnings("unused")
        Node ndWDAL = (Node) xpath.evaluate("xls:WithinDistance/xls:POI/xls:POIAttributeList/xls:POIInfoList",
                ndPoiLoc, XPathConstants.NODE);
        String maxDist = (String) xpath.evaluate("xls:WithinDistance/xls:MaximumDistance/@value", ndPoiLoc,
                XPathConstants.STRING);
        if (maxDist != null) {
            poiLocations.put("withinDistance", maxDist);
        }

    }
    Node ndPoiProp = (Node) xpath.evaluate("xls:POIProperties", ndReq, XPathConstants.NODE);
    if (ndPoiProp != null) {
        NodeList nlProp = (NodeList) xpath.evaluate("xls:POIProperty", ndPoiProp, XPathConstants.NODESET);
        if (nlProp != null) {
            for (int j = 0; j < nlProp.getLength(); j++) {
                Node ndProp = nlProp.item(j);
                poiProperties = new HashMap<String, String>();
                String name = (String) xpath.evaluate("@name", ndProp, XPathConstants.STRING);
                String param = context.getRequestContext().getApplicationConfiguration()
                        .getCatalogConfiguration().getParameters().getValue(name);
                String value = (String) xpath.evaluate("@value", ndProp, XPathConstants.STRING);
                poiProperties.put(param, value);
            }
        }
    }
    params.setPoiLocations(poiLocations);
    params.setPoiProperties(poiProperties);
}

From source file:com.esri.gpt.server.openls.provider.services.geocode.GeocodeProvider.java

/**
 * Handles an XML based request (normally HTTP POST).
 * //from   w  w w .java 2  s . c  o  m
 * @param context
 *            the operation context
 * @param root
 *            the root node
 * @param xpath
 *            an XPath to enable queries (properly configured with name
 *            spaces)
 * @throws Exception
 *             if a processing exception occurs
 */
public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception {

    // initialize
    LOGGER.finer("Handling Geocode request XML...");
    GeocodeParams tOptions = context.getRequestOptions().getGeocodeOptions();
    ServiceProperties svcProps = context.getServiceProperties();
    ParseHelper pHelper = new ParseHelper();
    ValidationHelper vHelper = new ValidationHelper();
    String locator;
    String[] parsed;
    ISupportedValues supported;

    // service and version are parsed by the parent RequestHandler

    // output format
    locator = "@outputFormat";
    parsed = pHelper.getParameterValues(root, xpath, locator);
    supported = svcProps.getSupportedValues(XlsConstants.Parameter_OutputFormat);
    context.getOperationResponse().setOutputFormat(vHelper.validateValue(supported, locator, parsed, false));

    // request ID
    locator = "@requestId";
    parsed = pHelper.getParameterValues(root, xpath, locator);
    tOptions.setRequestId(vHelper.validateValue(locator, parsed, false));

    GeocodeParams reqParams = new GeocodeParams();
    locator = "xls:GeocodeRequest";
    Node ndReq = (Node) xpath.evaluate(locator, root, XPathConstants.NODE);
    if (ndReq != null) {
        parseRequest(reqParams, ndReq, xpath);
    }

    try {
        context.getRequestOptions().getGeocodeOptions().setgAddrList(executeRequest(context, reqParams));

    } catch (Throwable e) {
        e.printStackTrace();
    }
    generateResponse(context);
}

From source file:de.ingrid.iplug.opensearch.converter.IngridRSSConverter.java

private void setPartnerAndProvider(IngridHitDetail hitDetail, Node item) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node node = (Node) xpath.evaluate("provider", item, XPathConstants.NODE);
    if (node != null) {
        hitDetail.put("provider", new String[] { node.getTextContent() });
    }/*  w  w  w .  j  ava2 s .  c om*/
    node = (Node) xpath.evaluate("partner", item, XPathConstants.NODE);
    if (node != null) {
        hitDetail.put("partner", new String[] { node.getTextContent() });
    }
}

From source file:cz.incad.kramerius.security.impl.criteria.MovingWall.java

public EvaluatingResult evaluateDoc(int wallFromConf, Document xmlDoc, String xPathExpression)
        throws XPathExpressionException {
    XPath xpath = xpfactory.newXPath();
    xpath.setNamespaceContext(new FedoraNamespaceContext());
    XPathExpression expr = xpath.compile(xPathExpression);
    Object date = expr.evaluate(xmlDoc, XPathConstants.NODE);
    if (date != null) {
        String patt = ((Text) date).getData();

        try {/*from   w  w  w.ja  va 2s . c  o m*/
            DatesParser dateParse = new DatesParser(new DateLexer(new StringReader(patt)));
            Date parsed = dateParse.dates();

            Calendar calFromMetadata = Calendar.getInstance();
            calFromMetadata.setTime(parsed);

            Calendar calFromConf = Calendar.getInstance();
            calFromConf.add(Calendar.YEAR, -1 * wallFromConf);

            return calFromMetadata.before(calFromConf) ? EvaluatingResult.TRUE : EvaluatingResult.FALSE;

        } catch (RecognitionException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            LOGGER.log(Level.SEVERE, "Returning NOT_APPLICABLE");
            return EvaluatingResult.NOT_APPLICABLE;
        } catch (TokenStreamException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            LOGGER.log(Level.SEVERE, "Returning NOT_APPLICABLE");
            return EvaluatingResult.NOT_APPLICABLE;
        }

    }

    return null;
}