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:edu.sampleu.bookstore.document.attribs.XPathSearchableAttribute.java

@Override
public List<DocumentAttribute> extractDocumentAttributes(
        @WebParam(name = "extensionDefinition") ExtensionDefinition extensionDefinition,
        @WebParam(name = "documentWithContent") DocumentWithContent documentWithContent) {
    List<DocumentAttribute> attribs = new ArrayList<DocumentAttribute>(1);
    String appContent = documentWithContent.getDocumentContent().getApplicationContent();
    XPath xpath = XPathHelper.newXPath();
    try {//  w w  w  .j  av  a2  s.  c  om
        //InputSource source = new StringReader(appContent);
        Element source = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new BufferedReader(new StringReader(appContent)))).getDocumentElement();
        String result = (String) xpath.evaluate(xpathExpression, source, XPathConstants.STRING);
        // xpath has no concept of null node, missing text values are the empty string
        if (StringUtils.isNotEmpty(result)) {
            try {
                attribs.add(createAttribute(this.key, result, this.dataType));
            } catch (ParseException pe) {
                log.error("Error converting value '" + result + "' to type '" + this.dataType + "'");
            }
        }
    } catch (XPathExpressionException xep) {
        log.error("Error evaluating searchable attribute expression: '" + this.xpathExpression + "'", xep);
    } catch (SAXException se) {
        log.error("Error parsing application content: '" + appContent + "'", se);
    } catch (ParserConfigurationException pce) {
        log.error("Error parsing application content: '" + appContent + "'", pce);
    } catch (IOException ioe) {
        log.error("Error parsing application content: '" + appContent + "'", ioe);
    }
    return attribs;
}

From source file:com.alliander.osgp.platform.cucumber.GetFirmwareVersion.java

@Then("^the firmware version result should be returned$")
public void theFirmwareVersionResultShouldBeReturned() throws Throwable {
    final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, this.deviceId,
            this.organisationId, this.correlationUid, TEST_CASE_NAME_RESPONSE);

    final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName();
    final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults();

    for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) {
        LOGGER.info(TEST_CASE_NAME_RESPONSE + " response {}",
                this.response = ((MessageExchange) tcr).getResponseContent());
    }/*from w  w  w.  ja  v  a 2 s.  c o m*/

    final XpathResult xpathResult = this.xpathResult.runXPathExpression(this.response, PATH_RESULT);
    final XPathExpression expr = xpathResult.getXpathExpression();

    Assert.assertEquals(XPATH_MATCHER_RESULT, expr.evaluate(xpathResult.getDocument(), XPathConstants.STRING));
    Assert.assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus());
}

From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java

/**
 * very useful: {@link http/*from ww w. ja  v  a2s  .  c  om*/
 * ://www.ibm.com/developerworks/library/x-javaxpathapi.html}
 * 
 * @param doc
 * @param path
 * @param scale
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
private String extractTextInternal(Document doc, String path)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    XPathFactory factory = XPathFactory.newInstance();

    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(namespaceContext);
    XPathExpression expr = xpath.compile(path);
    try {
        String result = (String) expr.evaluate(doc, XPathConstants.STRING);
        return result;
    } catch (Exception e) {
        log.error("XML extraction for path " + path + " failed: " + e.getMessage(), e);
        return "XML extraction for path " + path + " failed: " + e.getMessage();
    }
}

From source file:com.jaeksoft.searchlib.util.XPathParser.java

public final String getNodeString(Node parentNode, String query) throws XPathExpressionException {
    return (String) xPath.evaluate(query, parentNode, XPathConstants.STRING);
}

From source file:com.esri.gpt.catalog.search.SearchFilterSpatial.java

/**
 * Instantiates a new search filter spatial.
 *//* w w  w .  ja  v  a 2s  .c  o m*/
public SearchFilterSpatial() {
    super();
    reset();

    // Load a fioel with predefined extents (bookmarks)
    Document domFe;
    XPath xpathFe;
    try {
        String sPredefinedExtents = PREDEFINED_EXTENTS_FILE;
        LogUtil.getLogger().log(Level.FINE, "Loading Predefined extents file: {0}", sPredefinedExtents);
        domFe = DomUtil.makeDomFromResourcePath(sPredefinedExtents, false);
        xpathFe = XPathFactory.newInstance().newXPath();
    } catch (Exception e) {
        LogUtil.getLogger().log(Level.FINE, "No predefined extents file");
        domFe = null;
        xpathFe = null;
    }
    // predefined extent file root
    Node rootFe = null;
    try {
        if (domFe != null)
            rootFe = (Node) xpathFe.evaluate("/extents", domFe, XPathConstants.NODE);
    } catch (Exception e) {
        rootFe = null;
        LogUtil.getLogger().log(Level.FINE, "Xpath problem for predefined extents file");
    }
    /**
     * Reads Bookmarks and load an array
     */
    NodeList extents;
    ArrayList extentsList = new ArrayList();
    if (rootFe != null) {
        try {
            extents = (NodeList) xpathFe.evaluate("extent", rootFe, XPathConstants.NODESET);
            for (Node extent : new NodeListAdapter(extents)) {
                String extPlace = (String) xpathFe.evaluate("@place", extent, XPathConstants.STRING);
                String extValue = (String) xpathFe.evaluate("@ext", extent, XPathConstants.STRING);
                LogUtil.getLogger().log(Level.FINE, "Element added:" + extPlace + "," + extValue);
                SelectItem extElement = new SelectItem(extValue, extPlace);
                extentsList.add(extElement);
            }
        } catch (Exception e) {
            extentsList = null;
            LogUtil.getLogger().log(Level.FINE, "Xpath problem for predefined extents file");
        }
    } else
        extentsList = null;

    this._predefinedExtents = extentsList;
}

From source file:eu.smartfp7.terrier.sensor.ParserUtility.java

public static EdgeNodeSnapShot parseShort(InputStream is) throws Exception {

    DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance();
    xmlfact.setNamespaceAware(true);/*from w ww  .jav a 2  s. c  o  m*/
    Document document = xmlfact.newDocumentBuilder().parse(is);

    XPath xpath = XPathFactory.newInstance().newXPath();

    String time = (String) xpath.compile("//crowd/time/text()").evaluate(document, XPathConstants.STRING);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar c = Calendar.getInstance();
    ;
    c.setTime(df.parse(time));

    String density = (String) xpath.compile("//crowd/density/text()").evaluate(document, XPathConstants.STRING);

    NodeList list = (NodeList) xpath.compile("//crowd/colour").evaluate(document, XPathConstants.NODESET);
    double[] colors = new double[list.getLength()];
    for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node colorNode = list.item(i);
        String v = colorNode.getFirstChild().getTextContent();
        colors[i] = new Double(v);
    }

    String activity = (String) xpath.compile("//activity/name/text()").evaluate(document,
            XPathConstants.STRING);

    CrowdReport crowdReport = new CrowdReport(null, new Double(density), 0.0, colors);

    EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(null, null, c, crowdReport);
    snapShot.setText((activity != null ? activity : StringUtils.EMPTY));

    return snapShot;

}

From source file:com.eviware.soapui.testondemand.TestOnDemandCaller.java

@NonNull
public List<Location> getLocations() throws Exception {
    Document responseDocument = makeCall(LOCATIONS_URI, generateLocationsRequestXML());
    NodeList locationNodes = (NodeList) xpath.evaluate(LOCATION_XPATH_EXPRESSION, responseDocument,
            XPathConstants.NODESET);

    List<Location> locations = new ArrayList<Location>();
    for (int i = 0; i < locationNodes.getLength(); i++) {
        Node locationNode = locationNodes.item(i);
        String name = (String) xpath.evaluate(LOCATION_NAME_XPATH_EXPRESSION, locationNode,
                XPathConstants.STRING);
        String code = (String) xpath.evaluate(LOCATION_CODE_XPATH_EXPRESSION, locationNode,
                XPathConstants.STRING);
        String unformattedServerIPAddresses = (String) xpath
                .evaluate(LOCATION_SERVER_IP_ADDRESSES_XPATH_EXPRESSION, locationNode, XPathConstants.STRING);

        String[] serverIPAddresses = new String[0];
        if (!unformattedServerIPAddresses.isEmpty()) {
            serverIPAddresses = unformattedServerIPAddresses.split(SERVER_IP_ADDRESSES_DELIMETER);
        }/*from w  w  w.  j  ava 2s.  c  o  m*/

        locations.add(new Location(code, name, serverIPAddresses));
    }

    return locations;
}

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

/**
 * Constructor./*from   w  w w . j a  va2 s . co m*/
 *
 * @param url      URL
 * @param userName Username
 * @param password Password
 * @throws URISyntaxException if URL is wrong
 * @throws IOException if something in IO is wrong
 */
public CatalogService(URL url, String userName, String password) throws URISyntaxException, IOException {
    this.catalogURL = url;
    this.userName = userName;
    this.password = password;
    this.context = new NamespaceContextMap("csw", CSW_NAMESPACE, "gmd", GMD_NAMESPACE, "ows", OWS_NAMESPACE,
            "srv", SRV_NAMESPACE, "gco", GCO_NAMESPACE);
    Document xml = XML.getDocument(this.catalogURL, this.userName, this.password);
    if (xml != null) {
        String getProviderExpr = "//ows:ServiceIdentification/ows:Title";
        Node providerNameNode = (Node) XML.xpath(xml, getProviderExpr, XPathConstants.NODE, context);
        this.providerName = providerNameNode.getTextContent();
        String getRecordsURLExpr = "//ows:OperationsMetadata" + "/ows:Operation[@name='GetRecords']"
                + "/ows:DCP" + "/ows:HTTP" + "/ows:Post";

        NodeList rL = (NodeList) XML.xpath(xml, getRecordsURLExpr, XPathConstants.NODESET, context);

        for (int i = 0; i < rL.getLength(); i++) {
            Node gruNode = rL.item(i);
            String getRecordsValueStr = (String) XML.xpath(gruNode, "ows:Constraint/ows:Value/text()",
                    XPathConstants.STRING, this.context);

            if (getRecordsValueStr == null || getRecordsValueStr.isEmpty()
                    || getRecordsValueStr.equals("XML")) {

                String getRecordsURLStr = (String) XML.xpath(gruNode, "@*[name()='xlink:href']",
                        XPathConstants.STRING, this.context);

                this.getRecordsURL = null;
                this.getRecordsURL = new URL(getRecordsURLStr);
                break;
            }
        }
    }
}

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

@Test
public void testDeleteMediaPackage() throws Exception {
    // get a media package id
    Document r1 = doGetRequest("workflow/instances.xml", HttpStatus.SC_OK, tuple("startPage", 0),
            tuple("count", 1));
    String id = (String) xpath(r1, "//mediapackage/@id", XPathConstants.STRING);

    Document r2 = doGetRequest("episode/episode.xml", HttpStatus.SC_OK, tuple("id", id), tuple("limit", 0),
            tuple("offset", 0));

    // assert is in episode service
    boolean locked = Boolean.parseBoolean((String) xpath(r2, "//ocLocked", XPathConstants.STRING));

    // get ArchiveMP, assert is same and not null
    // archive test getElement, assertOK

    // archive delete assert ok

    // get episode.xml, assert not found or found but marked as deleted

    // get ArchiveMP, assert is null
    // archive test getElement, assert Not found
}

From source file:org.ala.harvester.PpmlHarvester.java

private int getCount(Document currentResDom, String xpathToCount) throws Exception {
    int resultNum = 0;

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

    resultNum = Integer.valueOf((String) xpath.evaluate(xpathToCount, currentResDom, XPathConstants.STRING));

    return resultNum;
}