Example usage for javax.xml.xpath XPathConstants STRING

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

Introduction

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

Prototype

QName STRING

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

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:de.bayern.gdi.services.CatalogService.java

/**
 * retrieves a Map of ServiceNames and URLs for a Filter-Word.
 *
 * @param filter the Word to filter to//from   ww  w  .ja va  2 s  .  c o  m
 * @return Map of Service Names and URLs
 * @throws URISyntaxException if URL is wrong
 * @throws IOException if something in IO is wrong
 */
public List<Service> getServicesByFilter(String filter) throws URISyntaxException, IOException {
    List<Service> services = new ArrayList<>();
    if (filter.length() > MIN_SEARCHLENGTH && this.getRecordsURL != null) {
        String search = loadXMLFilter(filter);
        Document xml = XML.getDocument(this.getRecordsURL, this.userName, this.password, search, true);
        Node exceptionNode = (Node) XML.xpath(xml, "//ows:ExceptionReport", XPathConstants.NODE, this.context);
        if (exceptionNode != null) {
            String exceptionCode = (String) XML.xpath(xml, "//ows:ExceptionReport/ows:Exception/@exceptionCode",
                    XPathConstants.STRING, this.context);
            String exceptionlocator = (String) XML.xpath(xml, "//ows:ExceptionReport/ows:Exception/@locator",
                    XPathConstants.STRING, this.context);
            String exceptiontext = (String) XML.xpath(xml,
                    "//ows:ExceptionReport/ows:Exception/ows:ExceptionText", XPathConstants.STRING,
                    this.context);
            String excpetion = "An Excpetion was thrown by the CSW: \n";
            excpetion += "\texceptionCode: " + exceptionCode + "\n";
            excpetion += "\tlocator: " + exceptionlocator + "\n";
            excpetion += "\texceptiontext: " + exceptiontext + "\n";
            LOG.error(excpetion, xml);
            return services;
        }
        String nodeListOfServicesExpr = "//csw:SearchResults//gmd:MD_Metadata";
        NodeList servicesNL = (NodeList) XML.xpath(xml, nodeListOfServicesExpr, XPathConstants.NODESET,
                this.context);
        services = parseServices(servicesNL);
    }
    return services;
}

From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java

/**
 * Close the specified stage.//from  ww w  . ja  va2s  .  c om
 * 
 * @param stage the stage to close.
 * @throws StageException if any issue occurred whilst closing the stage.
 */
public void closeStage(Stage stage, String description) throws StageException {
    performStageAction(StageAction.CLOSE, stage, description);
    if (isAsyncClose()) {
        waitForActionToComplete(stage);
        // check the action completed successfully and no rules failed.
        URL url = getActivityURL(stage);
        Document doc = getDocument(url);
        // last stagingActivity that was a close
        String xpathExpr = "(/list/stagingActivity[name='close'])[last()]";
        Node lastCloseNode = (Node) evaluateXPath(xpathExpr, doc, XPathConstants.NODE);
        if (lastCloseNode == null) {
            throw new StageException("Stage activity completed but no close action was recorded!");
        }
        Node closed = (Node) evaluateXPath("events/stagingActivityEvent[name='repositoryClosed']",
                lastCloseNode, XPathConstants.NODE);
        if (closed != null) {
            // we have successfully closed the repository
            return;
        }
        Node failed = (Node) evaluateXPath("events/stagingActivityEvent[name='repositoryCloseFailed']",
                lastCloseNode, XPathConstants.NODE);
        if (failed == null) {
            throw new StageException(
                    "Close stage action was signalled as completed, but was not recorded as either failed or succeeded!");
        }
        StringBuilder failureMessage = new StringBuilder("Closing stage ").append(stage.getStageID())
                .append(" failed.\n");
        String cause = (String) evaluateXPath("properties/stagingProperty[name='cause']/value", failed,
                XPathConstants.STRING);
        failureMessage.append('\t').append(cause);
        NodeList failedRules = (NodeList) evaluateXPath(
                "events/stagingActivityEvent[name='ruleFailed']/properties/stagingProperty[name='failureMessage']/value",
                lastCloseNode, XPathConstants.NODESET);
        for (int i = 0; i < failedRules.getLength(); i++) {
            failureMessage.append("\n\t");
            failureMessage.append(failedRules.item(i).getTextContent());
        }
        throw new StageException(failureMessage.toString());
    }
}

From source file:org.openremote.foxycart.resources.FoxyCartResource.java

private String evaluateXPath(Document doc, String xPathExpression) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    String text = null;//from   ww w  . j  a  v  a  2  s . c  o m

    try {
        XPathExpression expr = xpath.compile(xPathExpression);
        text = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
    }

    return text;
}

From source file:org.opencastproject.remotetest.util.WorkflowUtils.java

/**
 * Registers a new workflow definition//from w w  w . jav  a 2s  . co m
 * 
 * @param workflowDefinition
 *          the new workflow definition
 * @return the id of the workflow definition
 */
public static String registerWorkflowDefinition(String workflowDefinition) throws Exception {
    HttpPut put = new HttpPut(BASE_URL + "/workflow/definition");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("workflowDefinition", workflowDefinition));
    put.setEntity(new UrlEncodedFormEntity(params));
    TrustedHttpClient client = Main.getClient();
    HttpResponse response = client.execute(put);
    assertEquals(HttpStatus.SC_CREATED, response.getStatusLine().getStatusCode());
    String id = (String) Utils.xpath(workflowDefinition,
            "/*[local-name() = 'definition']/*[local-name() = 'id']", XPathConstants.STRING);
    assertNotNull(id);
    Main.returnClient(client);
    return id;
}

From source file:au.gov.ga.earthsci.discovery.csw.CSWDiscoveryResult.java

public CSWDiscoveryResult(CSWDiscovery discovery, int index, Element cswRecordElement)
        throws XPathExpressionException {
    super(discovery, index);

    XPath xpath = WWXML.makeXPath();

    String title = (String) xpath.compile("title/text()").evaluate(cswRecordElement, XPathConstants.STRING); //$NON-NLS-1$
    title = StringEscapeUtils.unescapeXml(title);

    String description = (String) xpath.compile("description/text()").evaluate(cswRecordElement, //$NON-NLS-1$
            XPathConstants.STRING);
    description = StringEscapeUtils.unescapeXml(description);

    //normalize newlines
    description = description.replace("\r\n", "\n").replace("\r", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$

    this.title = title;
    this.description = description;

    NodeList referenceElements = (NodeList) xpath.compile("references/reference").evaluate(cswRecordElement, //$NON-NLS-1$
            XPathConstants.NODESET);
    for (int i = 0; i < referenceElements.getLength(); i++) {
        Element referenceElement = (Element) referenceElements.item(i);
        String scheme = referenceElement.getAttribute("scheme"); //$NON-NLS-1$
        try {//from  w  w w.j  a  va  2 s  .  c  o  m
            URL url = new URL(referenceElement.getTextContent());
            references.add(url);
            referenceSchemes.add(scheme);
        } catch (MalformedURLException e) {
        }
    }

    Sector bounds = null;
    String min = (String) xpath.compile("boundingBox/lowerCorner/text()").evaluate(cswRecordElement, //$NON-NLS-1$
            XPathConstants.STRING);
    String max = (String) xpath.compile("boundingBox/upperCorner/text()").evaluate(cswRecordElement, //$NON-NLS-1$
            XPathConstants.STRING);
    if (!Util.isBlank(min) && !Util.isBlank(max)) {
        min = StringEscapeUtils.unescapeXml(min);
        max = StringEscapeUtils.unescapeXml(max);
        String doubleGroup = "([-+]?(?:\\d*\\.?\\d+)|(?:\\d+\\.))"; //$NON-NLS-1$
        Pattern pattern = Pattern.compile("\\s*" + doubleGroup + "\\s+" + doubleGroup + "\\s*"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        Matcher minMatcher = pattern.matcher(min);
        Matcher maxMatcher = pattern.matcher(max);
        if (minMatcher.matches() && maxMatcher.matches()) {
            double minLon = Double.parseDouble(minMatcher.group(1));
            double minLat = Double.parseDouble(minMatcher.group(2));
            double maxLon = Double.parseDouble(maxMatcher.group(1));
            double maxLat = Double.parseDouble(maxMatcher.group(2));
            bounds = Sector.fromDegrees(minLat, maxLat, minLon, maxLon);
        }
    }
    this.bounds = Bounds.fromSector(bounds);
}

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

private static void assertXpathEquals(Document doc, String path, String expected) {
    try {//from w w  w  . jav a  2  s .  c o m
        assertEquals(expected, ((String) Utils.xpath(doc, path, XPathConstants.STRING)).trim());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * @param node a Node obtained by getAllEvalResultsRootNodes()
 * @return/*from www.j  av a2 s.  c  o m*/
 * @throws XPathExpressionException
 */
public String getEvalResultTarValue(Node node) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String result = (String) xpath.evaluate(sTarXpath, node, XPathConstants.STRING);
    return result;
}

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

/**
 * Reads Address Information from request
 * @param reqParams//from  w ww  . j  a  v  a2 s  .  c  o  m
 * @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:org.opencastproject.remotetest.server.YoutubeDistributionRestEndpointTest.java

private String getYoutubeURL(String mediaPackageElementXML) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w ww  .  ja v a  2s . co  m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(mediaPackageElementXML, "UTF-8"));
    XPath xPath = XPathFactory.newInstance().newXPath();
    return (String) xPath.evaluate("/*[local-name() = 'track']/*[local-name() = 'url']", doc,
            XPathConstants.STRING);
}