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:com.adaptris.util.text.xml.XPath.java

/**
 * returns the string value contained in an element returned by an XPath
 *
 * @param context the node to apply the XPath to
 * @param xpath the xpath to apply//from ww w  .ja  v a2s  . c o  m
 * @return the string extracted
 * @throws XPathExpressionException on error
 */
public String selectSingleTextItem(Node context, String xpath) throws XPathExpressionException {
    return (String) createXpath().evaluate(xpath, context, XPathConstants.STRING);
}

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

protected String getXACMLAttachmentId(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);// w  w w.j  av a  2  s  .co m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((String) XPathFactory.newInstance().newXPath()
            .compile("//*[local-name() = 'attachment'][@type='security/xacml']/@id")
            .evaluate(doc, XPathConstants.STRING));
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument delete(String id)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;/*from  ww w. j  ava  2  s . c  o m*/

    String urlStr = this.solrHost + "/update?stream.body="
            + URLEncoder.encode("<delete><query>id:" + id + "</query></delete>") + "&commit=true";

    Log.debug("The " + id + " item is going to be deleted");
    // Create a method instance.
    method = new GetMethod(urlStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }

    return solrResponse;
}

From source file:com.amalto.core.storage.datasource.DataSourceFactory.java

private static Map<String, DataSourceDefinition> readDocument(InputStream configurationAsStream) {
    Document document;// w  w w.j  a  v  a2 s .com
    try {
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        document = documentBuilder.parse(configurationAsStream);
    } catch (Exception e) {
        throw new RuntimeException("Exception occurred during data sources XML configuration parsing", e);
    }
    try {
        NodeList datasources = (NodeList) evaluate(document, "/datasources/datasource", XPathConstants.NODESET);
        Map<String, DataSourceDefinition> nameToDataSources = new HashMap<String, DataSourceDefinition>();
        for (int i = 0; i < datasources.getLength(); i++) {
            Node currentDataSourceElement = datasources.item(i);
            String name = (String) evaluate(currentDataSourceElement, "@name", XPathConstants.STRING); //$NON-NLS-1$
            DataSource master = getDataSourceConfiguration(currentDataSourceElement, name, "master"); //$NON-NLS-1$
            if (master == null) {
                throw new IllegalArgumentException(
                        "Data source '" + name + "'does not declare a master data section");
            }
            DataSource staging = getDataSourceConfiguration(currentDataSourceElement, name, "staging"); //$NON-NLS-1$
            DataSource system = getDataSourceConfiguration(currentDataSourceElement, name, "system"); //$NON-NLS-1$
            nameToDataSources.put(name, new DataSourceDefinition(master, staging, system));
        }
        return nameToDataSources;
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Invalid data sources configuration.", e);
    }
}

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

@Test
public void testIngestThinClient() throws Exception {

    // Create Media Package
    HttpResponse response = IngestResources.createMediaPackage(client);
    assertEquals("Response code (createMediaPacakge):", 200, response.getStatusLine().getStatusCode());
    mediaPackage = EntityUtils.toString(response.getEntity(), "UTF-8");
    // TODO validate Media Package

    // Add Track//w  ww.j  a  v a 2 s.  c o  m
    response = IngestResources.add(client, "Track", trackUrl, "presenter/source", mediaPackage);
    assertEquals("Response code (addTrack):", 200, response.getStatusLine().getStatusCode());
    mediaPackage = EntityUtils.toString(response.getEntity(), "UTF-8");
    // TODO validate Media Package

    // Add Catalog
    response = IngestResources.add(client, "Catalog", catalogUrl, "dublincore/episode", mediaPackage);
    assertEquals("Response code (addCatalog):", 200, response.getStatusLine().getStatusCode());
    mediaPackage = EntityUtils.toString(response.getEntity(), "UTF-8");
    // TODO validate Media Package

    // Add Attachment
    response = IngestResources.add(client, "Attachment", attachmentUrl, "attachment/txt", mediaPackage);
    assertEquals("Response code (addAttachment):", 200, response.getStatusLine().getStatusCode());
    mediaPackage = EntityUtils.toString(response.getEntity(), "UTF-8");
    // TODO validate Media Package

    // Ingest
    response = IngestResources.ingest(client, mediaPackage);
    assertEquals("Response code (ingest):", 200, response.getStatusLine().getStatusCode());
    mediaPackage = EntityUtils.toString(response.getEntity(), "UTF-8");
    Document xml = Utils.parseXml(IOUtils.toInputStream(mediaPackage, "UTF-8"));
    String workflowId = (String) Utils.xpath(xml, "//*[local-name() = 'workflow']/@id", XPathConstants.STRING);
    String mediaPackageId = (String) Utils.xpath(xml, "//*[local-name() = 'mediapackage']/@id",
            XPathConstants.STRING);

    // Confirm ingest
    response = IngestResources.getWorkflowInstance(client, workflowId);
    assertEquals("Response code (workflow instance):", 200, response.getStatusLine().getStatusCode());

    // Compare Track
    String ingestedTrackUrl = (String) Utils.xpath(xml,
            "//*[local-name() = 'media']/*[local-name() = 'track'][@type='presenter/source']/*[local-name() = 'url']",
            XPathConstants.STRING);
    String ingestedMd5 = Utils.md5(Utils.getUrlAsFile(ingestedTrackUrl));
    String trackMd5 = Utils.md5(Utils.getUrlAsFile(trackUrl));
    assertEquals("Media Track Checksum:", ingestedMd5, trackMd5);

    // Compare Catalog
    String ingestedCatalogUrl = (String) Utils.xpath(xml,
            "//*[local-name() = 'metadata']/*[local-name() = 'catalog'][@type='dublincore/episode']/*[local-name() = 'url']",
            XPathConstants.STRING);
    Document ingestedCatalog = Utils.getUrlAsDocument(ingestedCatalogUrl);
    Document catalog = Utils.getUrlAsDocument(catalogUrl);
    for (String key : catalogKeys) {
        assertEquals("Catalog " + key + ":",
                ((String) Utils.xpath(ingestedCatalog, "//dcterms:" + key, XPathConstants.STRING)).trim(),
                ((String) Utils.xpath(catalog, "//dcterms:" + key, XPathConstants.STRING)).trim());
    }

    // Compare Attachment
    String ingestedAttachmentUrl = (String) Utils.xpath(xml,
            "//*[local-name() = 'attachments']/*[local-name() = 'attachment'][@type='attachment/txt']/*[local-name() = 'url']",
            XPathConstants.STRING);
    ingestedMd5 = Utils.md5(Utils.getUrlAsFile(ingestedAttachmentUrl));
    String attachmentMd5 = Utils.md5(Utils.getUrlAsFile(attachmentUrl));
    assertEquals("Attachment Checksum:", ingestedMd5, attachmentMd5);

    // Confirm search indexing
    int retries = 0;
    int timeout = 20;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check workflow instance status
        response = SearchResources.episode(client, mediaPackageId);
        assertEquals("Response code (episode):", 200, response.getStatusLine().getStatusCode());
        xml = Utils.parseXml(response.getEntity().getContent());
        if (Utils.xpathExists(xml,
                "//*[local-name() = 'result'][@id='" + mediaPackageId + "']/*[local-name() = 'mediapackage']")
                .equals(true)) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("Search Service failed to index file.");
    }

}

From source file:nl.surfnet.sab.SabResponseParser.java

/**
 * Check that response contains the success status. Throw IOException with message otherwise.
 *//*  ww w . j  a  v  a2s. c  o  m*/
private void validateStatus(Document document, XPath xpath) throws XPathExpressionException, IOException {

    XPathExpression statusCodeExpression = xpath.compile(XPATH_STATUSCODE);
    String statusCode = (String) statusCodeExpression.evaluate(document, XPathConstants.STRING);

    if (SAMLP_SUCCESS.equals(statusCode)) {
        // Success, validation returns.
        return;
    } else {
        // Status message is only set if status code not 'success'.
        XPathExpression statusMessageExpression = xpath.compile(XPATH_STATUSMESSAGE);
        String statusMessage = (String) statusMessageExpression.evaluate(document, XPathConstants.STRING);

        if (SAMLP_RESPONDER.equals(statusCode) && statusMessage.startsWith(NOT_FOUND_MESSAGE_PREFIX)) {
            LOG.debug(
                    "Given nameId not found in SAB. Is regarded by us as 'valid' response, although server response indicates a server error.");
            return;
        } else {
            throw new IOException("Unsuccessful status. Code: '" + statusCode + "', message: " + statusMessage);
        }
    }
}

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

@Ignore
@Test//from   w  w w .  j  a  v a 2s  . c o  m
public void testScheduledCapture() throws Exception {

    // Agent registered (Capture Admin Agents)
    HttpResponse response = CaptureAdminResources.agents(httpClient);
    assertEquals("Response code (agents):", 200, response.getStatusLine().getStatusCode());
    Document xml = Utils.parseXml(response.getEntity().getContent());
    assertTrue("Agent included? (agents):", Utils.xpathExists(xml,
            "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT + "\']"));

    // Agent registered (Capture Admin Agent)
    response = CaptureAdminResources.agent(httpClient, CaptureResources.AGENT);
    assertEquals("Response code (agent):", 200, response.getStatusLine().getStatusCode());
    xml = Utils.parseXml(response.getEntity().getContent());
    assertTrue("Agent included? (agent):", Utils.xpathExists(xml,
            "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT + "\']"));

    // Agent idle (State)
    response = StateResources.getState(httpClient);
    assertEquals("Response code (getState):", 200, response.getStatusLine().getStatusCode());
    assertEquals("Agent idle? (getState):", "idle", EntityUtils.toString(response.getEntity(), "UTF-8"));

    // Agent idle (Capture Admin Agent)
    response = CaptureAdminResources.agent(httpClient, CaptureResources.AGENT);
    assertEquals("Response code (agent):", 200, response.getStatusLine().getStatusCode());
    assertEquals("Agent idle? (agent):", "idle",
            Utils.xpath(xml, "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT
                    + "\']/*[local-name() = 'state']", XPathConstants.STRING));

    // Get initial recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject initialRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    System.out.println("Initial: " + initialRecordingCount);

    // Generate unique title and create event XML
    String title = UUID.randomUUID().toString();
    String id = UUID.randomUUID().toString();
    String event = Utils.schedulerEvent(10000, title, id);

    // Add event (Scheduler)
    response = SchedulerResources.addEvent(httpClient, event);
    assertEquals("Response code (addEvent):", 200, response.getStatusLine().getStatusCode());

    // Event included? (Scheduler: events)
    response = SchedulerResources.getEvents(httpClient);
    assertEquals("Response code (getEvents):", 200, response.getStatusLine().getStatusCode());
    xml = Utils.parseXml(response.getEntity().getContent());
    assertTrue("Event included? (getEvents):",
            Utils.xpathExists(xml, "//*[local-name() = 'SchedulerEvent'][id=\'" + id + "\']"));

    // Event included? (Scheduler: upcoming events)
    response = SchedulerResources.getUpcomingEvents(httpClient);
    assertEquals("Response code (getUpcomingEvents):", 200, response.getStatusLine().getStatusCode());
    xml = Utils.parseXml(response.getEntity().getContent());
    assertTrue("Event included? (getUpcomingEvents):",
            Utils.xpathExists(xml, "//*[local-name() = 'SchedulerEvent'][id=\'" + id + "\']"));

    // Compare event (Scheduler: event)
    response = SchedulerResources.getEvent(httpClient, id);
    assertEquals("Response code (getEvent):", 200, response.getStatusLine().getStatusCode());
    xml = Utils.parseXml(response.getEntity().getContent());
    assertEquals("Event id (getEvent):", title, Utils.xpath(xml,
            "//*[local-name() = 'item'][@key='title']/*[local-name() = 'value']", XPathConstants.STRING));
    assertEquals("Event title (getEvent):", id,
            Utils.xpath(xml, "//*[local-name() = 'id']", XPathConstants.STRING));

    // Compare event DC metadata (Scheduler)
    response = SchedulerResources.getDublinCoreMetadata(httpClient, id);
    assertEquals("Response code (getDublinCoreMetadata):", 200, response.getStatusLine().getStatusCode());
    xml = Utils.parseXml(response.getEntity().getContent());
    assertEquals("Event id (getDublinCoreMetadata):", title,
            Utils.xpath(xml, "//dcterms:title", XPathConstants.STRING));
    assertEquals("Event title (getDublinCoreMetadata):", id,
            Utils.xpath(xml, "//dcterms:identifier", XPathConstants.STRING));

    // Get post-scheduled recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject scheduledRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    System.out.println("Recording Scheduled: " + scheduledRecordingCount);

    // Compare total recording count
    assertEquals("Total recording count increased by one:", (Long) initialRecordingCount.get("total") + 1,
            scheduledRecordingCount.get("total"));
    // Compare upcoming recording count
    assertEquals("Upcoming recording count increased by one:", (Long) initialRecordingCount.get("upcoming") + 1,
            scheduledRecordingCount.get("upcoming"));

    // Confirm recording started (State)
    int retries = 0;
    int timeout = 60;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check capture agent status
        response = StateResources.getState(httpClient);
        assertEquals("Response code (workflow instance):", 200, response.getStatusLine().getStatusCode());
        if (response.getEntity().getContent().equals("capturing")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("State Service failed to reflect that recording had started.");
    }

    // Confirm recording started (Capture Admin)
    retries = 0;
    timeout = 10;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check capture agent status
        response = CaptureAdminResources.agents(httpClient);
        assertEquals("Response code (agents):", 200, response.getStatusLine().getStatusCode());
        xml = Utils.parseXml(response.getEntity().getContent());
        if (Utils.xpath(xml, "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT
                + "\']/*[local-name() = 'state']", XPathConstants.STRING).equals("capturing")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("Capture Admin failed to reflect that recording had started.");
    }

    // Get capturing recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject capturingRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    System.out.println("Recording Started: " + capturingRecordingCount);

    // Compare total recording count
    assertEquals("Total recording count the same (schedule to capture):",
            (Long) scheduledRecordingCount.get("total"), capturingRecordingCount.get("total"));
    // Compare upcoming recording count
    assertEquals("Upcoming recording count decreased by one:",
            (Long) scheduledRecordingCount.get("upcoming") - 1, capturingRecordingCount.get("upcoming"));
    // Compare capturing recording count
    assertEquals("Capture recording count increased by one:",
            (Long) scheduledRecordingCount.get("capturing") + 1, capturingRecordingCount.get("capturing"));

    // Confirm recording stopped (State)
    retries = 0;
    timeout = 10;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check capture agent status
        response = StateResources.getState(httpClient);
        assertEquals("Response code (workflow instance):", 200, response.getStatusLine().getStatusCode());
        if (response.getEntity().getContent().equals("idle")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("State Service failed to reflect that recording had stopped.");
    }

    // Confirm recording stopped (Capture Admin)
    retries = 0;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check capture agent status
        response = CaptureAdminResources.agents(httpClient);
        assertEquals("Response code (agents):", 200, response.getStatusLine().getStatusCode());
        xml = Utils.parseXml(response.getEntity().getContent());
        if (Utils.xpath(xml, "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT
                + "\']/*[local-name() = 'state']", XPathConstants.STRING).equals("idle")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("Capture Admin Service failed to reflect that recording had stopped.");
    }

    // Get processing recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject processingRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    System.out.println("Process Recording: " + processingRecordingCount);

    // Compare total recording count
    assertEquals("Total recording count the same (capture to process):",
            (Long) capturingRecordingCount.get("total"), processingRecordingCount.get("total"));
    // Compare capturing recording count
    assertEquals("Capture recording count decreased by one:",
            (Long) capturingRecordingCount.get("capturing") - 1, processingRecordingCount.get("capturing"));
    // Compare processing recording count
    assertEquals("Process recording count increased by one:",
            (Long) capturingRecordingCount.get("processing") + 1, processingRecordingCount.get("processing"));

    // Confirm recording indexed
    retries = 0;
    timeout = 60;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check if recording indexed (Search)
        response = SearchResources.all(httpClient, title);
        assertEquals("Response code (search all):", 200, response.getStatusLine().getStatusCode());
        xml = Utils.parseXml(response.getEntity().getContent());
        if (Utils.xpathExists(xml, "//*[local-name() = 'mediapackage'][title=\'" + title + "\']")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("Search Service failed to index recording.");
    }

    // Get finished recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject finishedRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    System.out.println("Finished Recording: " + finishedRecordingCount);

    // Compare total recording count
    assertEquals("Total recording count the same (process to finish):",
            (Long) processingRecordingCount.get("total"), finishedRecordingCount.get("total"));
    // Compare processing recording count
    assertEquals("Process recording count decreased by one:",
            (Long) processingRecordingCount.get("processing") - 1, finishedRecordingCount.get("processing"));
    // Compare finished recording count
    assertEquals("Finished recording count increased by one:",
            (Long) processingRecordingCount.get("finished") + 1, finishedRecordingCount.get("finished"));

}

From source file:com.espertech.esperio.representation.axiom.AxiomXPathPropertyGetter.java

public Class getResultClass() {
    if (resultType.equals(XPathConstants.BOOLEAN)) {
        return Boolean.class;
    }/* w  ww  . j ava2 s  .c  o m*/
    if (resultType.equals(XPathConstants.NUMBER)) {
        return Double.class;
    }
    if (resultType.equals(XPathConstants.STRING)) {
        return String.class;
    }

    return String.class;
}

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

@Test
public void testRetractMediaPackage() 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, "//*[local-name() = 'mediapackage']/@id", XPathConstants.STRING);
    String retractWorkflow = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("retract.xml"),
            "UTF-8");
    System.out.println("Retracting media package " + id);
    doPostRequest("episode/applyworkflow", HttpStatus.SC_NO_CONTENT, tuple("definition", retractWorkflow),
            tuple("id", id));
}

From source file:gov.nih.nci.cabio.RESTAPITest.java

/**
 * Returns the text value of the nodes at the given XPath.
 *//*w  ww.  j a  v  a2s . com*/
private String getValue(Document doc, String path) throws Exception {
    XPathExpression expr = xpath.compile(path);
    Object result = expr.evaluate(doc, XPathConstants.STRING);
    return (String) result;
}