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.esri.gpt.server.openls.provider.services.reversegeocode.ReverseGeocodeProvider.java

/**
 * Parses reverse geocode request.//from  w  ww . j  a va  2  s.  c  o m
 * @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:eu.planets_project.tb.impl.services.EvaluationTestbedServiceTemplateImpl.java

/**
 * Method for applying the XPathForBMGoalRootNodes on a given DOM Document
 * @param doc/*from   ww  w  .j a va2 s  .  c o  m*/
 * @return
 * @throws XPathExpressionException
 */
public NodeList getAllEvalResultsRootNodes(Document doc) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate(sXPathForBMGoalRootNodes, doc, XPathConstants.NODESET);
    return nodes;
}

From source file:eu.planets_project.tb.impl.services.EvaluationTestbedServiceTemplateImpl.java

/**
 * @param node a Node obtained by getAllEvalResultsRootNodes()
 * @return/*from ww w . j a va 2s .  c  om*/
 * @throws XPathExpressionException
 */
public NodeList getEvalResultMetricNodes(Node node) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList result = (NodeList) xpath.evaluate(sMetric, node, XPathConstants.NODESET);
    return result;
}

From source file:au.csiro.casda.sodalint.ValidateServiceDescriptor.java

private Node getSodaServiceResource(Reporter reporter, Document document) throws XPathExpressionException {
    // logDocumentContent(document);

    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "*[local-name()= 'RESOURCE' and "
            + "@utype='adhoc:service' and ./*/@value='ivo://ivoa.net/std/SODA#sync-1.0']";
    NodeList svcResList = (NodeList) xpath.evaluate(expression, document.getDocumentElement(),
            XPathConstants.NODESET);

    if (svcResList != null && svcResList.getLength() > 0) {
        return svcResList.item(0);
    }/*from w  w w  .  j av  a  2s  . c om*/
    return null;
}

From source file:eu.europa.ec.markt.dss.validation102853.toolbox.XPointerResourceResolver.java

@Override
public XMLSignatureInput engineResolveURI(ResourceResolverContext context) throws ResourceResolverException {

    final Attr uriAttr = context.attr;
    final String baseUri = context.baseUri;

    String uriNodeValue = uriAttr.getNodeValue();

    if (uriNodeValue.charAt(0) != '#') {
        return null;
    }/* w ww  .j ava  2s.c om*/

    String xpURI;
    try {
        xpURI = URLDecoder.decode(uriNodeValue, "utf-8");
    } catch (UnsupportedEncodingException e) {
        LOG.warn("utf-8 not a valid encoding", e);
        return null;
    }

    String parts[] = xpURI.substring(1).split("\\s");

    int i = 0;

    DSigNamespaceContext nsContext = null;

    if (parts.length > 1) {
        nsContext = new DSigNamespaceContext();

        for (; i < parts.length - 1; ++i) {
            if (!parts[i].endsWith(")") || !parts[i].startsWith(XNS_OPEN)) {
                return null;
            }

            String mapping = parts[i].substring(XNS_OPEN.length(), parts[i].length() - 1);

            int pos = mapping.indexOf('=');

            if (pos <= 0 || pos >= mapping.length() - 1) {
                throw new ResourceResolverException("malformed namespace part of XPointer expression",
                        uriNodeValue, baseUri);
            }

            nsContext.addNamespace(mapping.substring(0, pos), mapping.substring(pos + 1));
        }
    }

    try {
        Node node = null;
        NodeList nodes = null;

        // plain ID reference.
        if (i == 0 && !parts[i].startsWith(XP_OPEN)) {
            node = this.baseNode.getOwnerDocument().getElementById(parts[i]);
        } else {
            if (!parts[i].endsWith(")") || !parts[i].startsWith(XP_OPEN)) {
                return null;
            }

            XPath xp = this.xPathFactory.newXPath();

            if (nsContext != null) {
                xp.setNamespaceContext(nsContext);
            }

            nodes = (NodeList) xp.evaluate(parts[i].substring(XP_OPEN.length(), parts[i].length() - 1),
                    this.baseNode, XPathConstants.NODESET);

            if (nodes.getLength() == 0) {
                return null;
            }
            if (nodes.getLength() == 1) {
                node = nodes.item(0);
            }
        }

        XMLSignatureInput result = null;

        if (node != null) {
            result = new XMLSignatureInput(node);
        } else if (nodes != null) {
            Set<Node> nodeSet = new HashSet<Node>(nodes.getLength());

            for (int j = 0; j < nodes.getLength(); ++j) {
                nodeSet.add(nodes.item(j));
            }

            result = new XMLSignatureInput(nodeSet);
        } else {
            return null;
        }

        result.setMIMEType("text/xml");
        result.setExcludeComments(true);
        result.setSourceURI((baseUri != null) ? baseUri.concat(uriNodeValue) : uriNodeValue);

        return result;

    } catch (XPathExpressionException e) {
        throw new ResourceResolverException("malformed XPath inside XPointer expression", e, uriNodeValue,
                baseUri);
    }
}

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

/**
 * Reads Address Information from request
 * @param reqParams//from  w  w w . j a  va 2  s.  com
 * @param ndReq
 * @param xpath
 * @throws XPathExpressionException
 */
public void parseRequest(GeocodeParams reqParams, Node ndReq, XPath xpath) throws XPathExpressionException {
    NodeList ndAddresses = (NodeList) xpath.evaluate("xls:Address", ndReq, XPathConstants.NODESET);
    if (ndAddresses != null) {
        for (int i = 0; i < ndAddresses.getLength(); i++) {
            Node address = ndAddresses.item(i);
            if (address != null) {
                Address addr = new Address();
                Node ndStrAddr = (Node) xpath.evaluate("xls:StreetAddress", address, XPathConstants.NODE);
                if (ndStrAddr != null) {
                    Node ndStr = (Node) xpath.evaluate("xls:Street", ndStrAddr, XPathConstants.NODE);
                    if (ndStr != null) {
                        addr.setStreet(ndStr.getTextContent());
                    }
                }
                Node ndPostalCode = (Node) xpath.evaluate("xls:PostalCode", address, XPathConstants.NODE);
                if (ndPostalCode != null) {
                    addr.setPostalCode(ndPostalCode.getTextContent());
                }
                NodeList ndPlaces = (NodeList) xpath.evaluate("xls:Place", address, XPathConstants.NODESET);
                if (ndPlaces != null) {
                    for (int j = 0; j < ndPlaces.getLength(); j++) {
                        Node ndPlace = ndPlaces.item(j);
                        String type = Val
                                .chkStr((String) xpath.evaluate("@type", ndPlace, XPathConstants.STRING));
                        addr.setPlaceType(type);
                        if (type.equalsIgnoreCase("Municipality")) {
                            addr.setMunicipality(ndPlace.getTextContent());
                        } else if (type.equalsIgnoreCase("CountrySubdivision")) {
                            addr.setCountrySubdivision(ndPlace.getTextContent());
                        } else if (type.equalsIgnoreCase("BuildingNumber")) {
                            addr.setBuildingNumber(ndPlace.getTextContent());
                        } else if (type.equalsIgnoreCase("Intersection")) {
                            addr.setIntersection(ndPlace.getTextContent());
                        } else if (type.equalsIgnoreCase("StreetVec")) {
                            addr.setStreetVec(ndPlace.getTextContent());
                        }
                    }
                }
                reqParams.getAddresses().add(addr);
            }
        }
    }
}

From source file:eu.planets_project.tb.impl.services.EvaluationTestbedServiceTemplateImpl.java

/**
 * @param node a Node obtained by getAllEvalResultsRootNodes()
 * @return LinkedHashMap<MetricName,MetricResult>
 * @throws XPathExpressionException// ww  w  . ja v  a 2 s . co  m
 */
public Map<String, String> getEvalResultMetricNamesAndValues(Node node) throws XPathExpressionException {
    //get all metric nodes for this property
    NodeList metrics = getEvalResultMetricNodes(node);

    Map<String, String> ret = new LinkedHashMap<String, String>();

    if ((metrics != null) && (metrics.getLength() > 0)) {
        for (int i = 0; i < metrics.getLength(); i++) {
            //metric node
            Node n = metrics.item(i);

            //query the name
            XPath xpathName = XPathFactory.newInstance().newXPath();
            String name = (String) xpathName.evaluate(sMetricName, n, XPathConstants.STRING);
            //query the result
            XPath xpathResult = XPathFactory.newInstance().newXPath();
            String value = (String) xpathResult.evaluate(sMetricResult, n, XPathConstants.STRING);
            ret.put(name, value);

        }
    }
    return ret;
}

From source file:hudson.plugins.plot.XMLSeries.java

/**
 * Load the series from a properties file.
 *//* w ww.  java 2  s . c  om*/
@Override
public List<PlotPoint> loadSeries(FilePath workspaceRootDir, int buildNumber, PrintStream logger) {
    InputStream in = null;
    InputSource inputSource = null;

    try {
        List<PlotPoint> ret = new ArrayList<PlotPoint>();
        FilePath[] seriesFiles = null;

        try {
            seriesFiles = workspaceRootDir.list(getFile());
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Exception trying to retrieve series files", e);
            return null;
        }

        if (ArrayUtils.isEmpty(seriesFiles)) {
            LOGGER.info("No plot data file found: " + getFile());
            return null;
        }

        try {
            if (LOGGER.isLoggable(defaultLogLevel))
                LOGGER.log(defaultLogLevel, "Loading plot series data from: " + getFile());

            in = seriesFiles[0].read();
            // load existing plot file
            inputSource = new InputSource(in);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Exception reading plot series data from " + seriesFiles[0], e);
            return null;
        }

        if (LOGGER.isLoggable(defaultLogLevel))
            LOGGER.log(defaultLogLevel, "NodeType " + nodeTypeString + " : " + nodeType);

        if (LOGGER.isLoggable(defaultLogLevel))
            LOGGER.log(defaultLogLevel, "Loaded XML Plot file: " + getFile());

        XPath xpath = XPathFactory.newInstance().newXPath();
        Object xmlObject = xpath.evaluate(xpathString, inputSource, nodeType);

        /*
         * If we have a nodeset, we need multiples, otherwise we just need
         * one value, and can do a toString() to set it.
         */
        if (nodeType.equals(XPathConstants.NODESET)) {
            NodeList nl = (NodeList) xmlObject;
            if (LOGGER.isLoggable(defaultLogLevel))
                LOGGER.log(defaultLogLevel, "Number of nodes: " + nl.getLength());

            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                if (!new Scanner(node.getTextContent().trim()).hasNextDouble()) {
                    return coalesceTextnodesAsLabelsStrategy(nl, buildNumber);
                }
            }
            return mapNodeNameAsLabelTextContentAsValueStrategy(nl, buildNumber);
        } else if (nodeType.equals(XPathConstants.NODE)) {
            addNodeToList(ret, (Node) xmlObject, buildNumber);
        } else {
            // otherwise we have a single type and can do a toString on it.
            if (xmlObject instanceof NodeList) {
                NodeList nl = (NodeList) xmlObject;

                if (LOGGER.isLoggable(defaultLogLevel))
                    LOGGER.log(defaultLogLevel, "Number of nodes: " + nl.getLength());

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

                    if (n != null && n.getLocalName() != null && n.getTextContent() != null) {
                        addValueToList(ret, label, xmlObject, buildNumber);
                    }
                }

            } else {
                addValueToList(ret, label, xmlObject, buildNumber);
            }
        }
        return ret;

    } catch (XPathExpressionException e) {
        LOGGER.log(Level.SEVERE, "XPathExpressionException for XPath '" + getXpath() + "'", e);
    } finally {
        IOUtils.closeQuietly(in);
    }

    return null;
}

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

@Test
public void testGetAgents() throws Exception {
    String endpoint = "/capture-admin/agents";
    HttpGet get = new HttpGet(BASE_URL + endpoint + ".xml");
    String xmlResponse = EntityUtils.toString(httpClient.execute(get).getEntity());
    Main.returnClient(httpClient);/* w ww .j a v a  2s .  c o  m*/

    // parse the xml and extract the running clients names
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xmlResponse, "UTF-8"));
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList agents = (NodeList) xPath.compile("//*[local-name() = 'agent']").evaluate(doc,
            XPathConstants.NODESET);

    // validate the REST endpoint for each agent state is functional
    for (int i = 0; i < agents.getLength(); i++) {
        try {
            httpClient = Main.getClient();
            String agentName = (String) xPath.evaluate("*[local-name() = 'name']/text()", agents.item(i),
                    XPathConstants.STRING);
            HttpGet agentGet = new HttpGet(BASE_URL + endpoint + "/" + agentName + ".xml");
            int agentResponse = httpClient.execute(agentGet).getStatusLine().getStatusCode();
            assertEquals(HttpStatus.SC_OK, agentResponse);
        } finally {
            Main.returnClient(httpClient);
        }
    }
}

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

/**
 * Set an IngridHitDetail with data that is needed by default.
 * //from  w  ww . j a  va  2 s.  c  o m
 * @param hit
 * @param item
 * @param groupedBy
 * @throws XPathExpressionException
 */
private void setIngridHitDetail(IngridHit hit, Node item, String groupedBy) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();

    // get plug id
    Node node = (Node) xpath.evaluate("plugid", item, XPathConstants.NODE);
    if (node != null) {
        hit.setPlugId(node.getTextContent());
    }

    // get doc id
    hit.setDocumentId(getDocumentId(item));

    // =====================================================================
    // the following must be put into the HitDetail
    // this detail will be put into a cache and returned when getDetail()
    // is called
    // =====================================================================
    IngridHitDetail hitDetail = new IngridHitDetail(hit, (String) hit.get("title"),
            (String) hit.get("abstract"));
    node = (Node) xpath.evaluate("timeReference/start", item, XPathConstants.NODE);
    if (node != null) {
        hitDetail.put("t1", node.getTextContent());
    }
    node = (Node) xpath.evaluate("timeReference/stop", item, XPathConstants.NODE);
    if (node != null) {
        hitDetail.put("t2", node.getTextContent());
    }

    // set partner and provider
    setPartnerAndProvider(hitDetail, item);

    // get box
    node = (Node) xpath.evaluate("box", item, XPathConstants.NODE);
    if (node != null) {
        String[] box = node.getTextContent().split(" ");
        hitDetail.put("x1", box[0]);
        hitDetail.put("y1", box[0]);
        hitDetail.put("x2", box[0]);
        hitDetail.put("y2", box[0]);
    }

    // add grouping information
    if (groupedBy != null) {
        String groupInfos = null;

        if (IngridQuery.GROUPED_BY_PARTNER.equalsIgnoreCase(groupedBy)) {
            String[] partner = (String[]) hitDetail.get("partner");
            if (partner != null && partner.length > 0)
                groupInfos = partner[0];
        } else if (IngridQuery.GROUPED_BY_ORGANISATION.equalsIgnoreCase(groupedBy)) {
            String[] provider = (String[]) hitDetail.get("provider");
            if (provider != null && provider.length > 0)
                groupInfos = provider[0];
        } else if (IngridQuery.GROUPED_BY_DATASOURCE.equalsIgnoreCase(groupedBy)) {
            groupInfos = (String) hit.get("url");
            try {
                groupInfos = new URL(groupInfos).getHost();
            } catch (MalformedURLException e) {
                log.warn("can not group url: " + groupInfos, e);
            }
        }
        if (groupInfos != null) {
            hit.addGroupedField(groupInfos);
        }
    }

    // add some important default values
    hitDetail.setDocumentId(hit.getDocumentId());
    hitDetail.setPlugId(hit.getPlugId());
    hitDetail.setDataSourceId(hit.getDataSourceId());
    hitDetail.put("url", hit.get("url"));

    // put detail into cache
    cache.put(new Element(hit.getDocumentId(), hitDetail));
}