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.espertech.esper.regression.event.TestNoSchemaXMLEvent.java

public void testNestedXMLXPathGetter() throws Exception {
    Configuration configuration = SupportConfigFactory.getConfiguration();
    ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();
    xmlDOMEventTypeDesc.setRootElementName("a");
    xmlDOMEventTypeDesc.setXPathPropertyExpr(true);
    xmlDOMEventTypeDesc.addXPathProperty("element1", "/a/b/c", XPathConstants.STRING);
    configuration.addEventType("AEvent", xmlDOMEventTypeDesc);

    epService = EPServiceProviderManager.getDefaultProvider(configuration);
    epService.initialize();/*from ww w  .  j av  a  2 s  .  c  om*/
    updateListener = new SupportUpdateListener();

    String stmt = "select b.c as type, element1, result1 from AEvent";
    EPStatement joinView = epService.getEPAdministrator().createEPL(stmt);
    joinView.addListener(updateListener);

    sendXMLEvent("<a><b><c></c></b></a>");
    EventBean theEvent = updateListener.assertOneGetNewAndReset();
    assertEquals("", theEvent.get("type"));
    assertEquals("", theEvent.get("element1"));

    sendXMLEvent("<a><b></b></a>");
    theEvent = updateListener.assertOneGetNewAndReset();
    assertEquals("", theEvent.get("type"));
    assertEquals("", theEvent.get("element1"));

    sendXMLEvent("<a><b><c>text</c></b></a>");
    theEvent = updateListener.assertOneGetNewAndReset();
    assertEquals("text", theEvent.get("type"));
    assertEquals("text", theEvent.get("element1"));
}

From source file:com.mnxfst.testing.client.TSClientPlanResultCollectCallable.java

/**
 * Parses the double value referenced by the given query
 * @param rootNode//w  w w  . j  av a 2 s.co  m
 * @param query
 * @param xpath
 * @return
 * @throws TSClientExecutionException
 */
protected double parseDoubleValue(Node rootNode, String query, XPath xpath) throws TSClientExecutionException {

    String tmp = null;
    try {
        tmp = (String) xpath.evaluate(query, rootNode, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new TSClientExecutionException("Failed to parse out value for '" + query
                + "' from document received from " + httpHost.getHostName());
    }

    if (tmp != null && !tmp.isEmpty()) {
        try {
            return Double.parseDouble(tmp);
        } catch (NumberFormatException e) {
            throw new TSClientExecutionException("Failed to parse the string '" + tmp
                    + "' into a valid numerical value received through query '" + query + "'. Returning host: "
                    + httpHost.getHostName());
        }
    }

    throw new TSClientExecutionException(
            "No valid value found for '" + query + "' from document received from " + httpHost.getHostName());
}

From source file:net.solarnetwork.support.XmlSupport.java

/**
 * Extract a String value via an XPath expression.
 * // ww w.  ja v  a 2  s .com
 * @param xml
 *        the XML
 * @param xpath
 *        the XPath expression
 * @return the String
 */
public String extractStringFromXml(Node xml, XPathExpression xpath) {
    try {
        return (String) xpath.evaluate(xml, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Unable to extract string from XPath [" + xpath.toString() + "]", e);
    }
}

From source file:net.firejack.platform.api.content.ContentServiceTest.java

@Test
public void exportImportCollectionTest() {
    Folder folder = createFolder(domain.getId());

    Collection collection = new Collection();
    collection.setName(time + "-collection");
    collection.setParentId(folder.getId());
    collection.setType("COLLECTION");
    collection.setDescription("Some Description");

    ServiceResponse<RegistryNodeTree> response2 = OPFEngine.ContentService.createCollection(collection);
    Assert.assertTrue("Collection should be created.", response2.isSuccess());

    RegistryNodeTree registryNodeTree2 = response2.getItem();
    Assert.assertNotNull("Should not be null.", registryNodeTree2);
    collection.setId(registryNodeTree2.getId());

    ServiceResponse<FileInfo> response3 = OPFEngine.ContentService
            .exportCollectionArchiveFile(collection.getId());
    FileInfo fileInfo = response3.getItem();
    Assert.assertNotNull("Should not be null.", fileInfo);

    File contentArchive;//from ww w  .  ja va  2 s.co  m
    try {
        File tempDir = FileUtils.getTempDirectory();
        contentArchive = FileUtils.create(tempDir, "content.zip");
        InputStream stream = fileInfo.getStream();
        FileUtils.writeToFile(contentArchive, stream);
        IOUtils.closeQuietly(stream);

        ArchiveUtils.unZIP(contentArchive, tempDir);

        File contentXml = FileUtils.create(tempDir, "content.xml");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document document = factory.newDocumentBuilder().parse(contentXml);
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        Object evaluate = xpath.evaluate("/content/collection", document, XPathConstants.NODE);
        String collectionName = (String) xpath.evaluate("@name", evaluate, XPathConstants.STRING);
        Assert.assertEquals("Exported collection should be equal name.", collection.getName(), collectionName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    ServiceResponse response4 = OPFEngine.ContentService.deleteCollection(collection.getId());
    Assert.assertTrue("Collection should be deleted.", response4.isSuccess());

    try {
        InputStream contentStream = FileUtils.openInputStream(contentArchive);
        ServiceResponse<FileInfo> response5 = OPFEngine.ContentService
                .importCollectionArchiveFile(contentStream);
        Assert.assertTrue("Import should be completed.", response5.isSuccess());
        IOUtils.closeQuietly(contentStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    ServiceResponse<Collection> response6 = OPFEngine.ContentService
            .readCollectionsByLikeLookup(folder.getLookup());
    Assert.assertTrue("Collections should be retrieved.", response6.isSuccess());

    Collection collection2 = response6.getItem();
    Assert.assertNotNull("Should not be null.", collection2);
    Assert.assertEquals("Should be the same name.", collection.getName(), collection2.getName());

    deleteFolder(folder);
}

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

private void preLoad() throws MalformedURLException, ParserConfigurationException {
    items = new ArrayList<>();
    String getTitle = "//title";
    this.title = (String) XML.xpath(this.mainDoc, getTitle, XPathConstants.STRING, this.nscontext);
    String getSubtitle = "//subtitle";
    this.subTitle = (String) XML.xpath(this.mainDoc, getSubtitle, XPathConstants.STRING, this.nscontext);
    String getID = "//id";
    this.serviceID = (String) XML.xpath(this.mainDoc, getID, XPathConstants.STRING, this.nscontext);
    String getEntriesQuery = "//entry";
    NodeList entries = (NodeList) XML.xpath(this.mainDoc, getEntriesQuery, XPathConstants.NODESET,
            this.nscontext);
    for (int i = 0; i < entries.getLength(); i++) {
        Node entry = entries.item(i);
        String getEntryTitle = "title";
        Node titleN = (Node) XML.xpath(entry, getEntryTitle, XPathConstants.NODE, this.nscontext);
        String getEntryid = "*[local-name()" + "='spatial_dataset_identifier_code']";
        Node id = (Node) XML.xpath(entry, getEntryid, XPathConstants.NODE, this.nscontext);
        if (id == null) {
            getEntryid = "id";
            id = (Node) XML.xpath(entry, getEntryid, XPathConstants.NODE, this.nscontext);
        }//  w  w w  .j  av  a 2 s  . c  o  m
        String summaryExpr = "summary";
        Node description = (Node) XML.xpath(entry, summaryExpr, XPathConstants.NODE, this.nscontext);
        String describedByExpr = "link[@rel='alternate']/@href";
        Node describedBy = (Node) XML.xpath(entry, describedByExpr, XPathConstants.NODE, this.nscontext);
        if (describedBy == null) {
            describedByExpr = "link/@href";
            describedBy = (Node) XML.xpath(entry, describedByExpr, XPathConstants.NODE, this.nscontext);
        }
        String borderPolygonExpr = "*[local-name()" + "='polygon']";
        Node borderPolyGonN = (Node) XML.xpath(entry, borderPolygonExpr, XPathConstants.NODE, this.nscontext);
        if (borderPolyGonN == null) {
            borderPolygonExpr = "*[local-name()" + "='box']";
            borderPolyGonN = (Node) XML.xpath(entry, borderPolygonExpr, XPathConstants.NODE, this.nscontext);
        }
        Item it = new Item(new URL(this.serviceURL));
        if (id != null) {
            it.id = id.getTextContent();
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. ID not found");
        }
        if (title != null) {
            it.title = titleN.getTextContent();
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. Title not found");
        }
        if (description != null) {
            it.description = description.getTextContent();
        } else {
            it.description = it.title;
        }
        if (describedBy != null) {
            it.describedBy = describedBy.getTextContent();
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. DescribedBy not found");
        }
        if (entry != null) {
            it.otherCRSs = getCRS(entry);
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. Entry not found");
        }
        if (it.otherCRSs != null) {
            it.defaultCRS = it.otherCRSs.get(0);
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. CRSs not found");
        }
        it.username = this.username;
        it.password = this.password;

        // XXX: GML, anyone?
        if (borderPolyGonN != null) {
            WKTReader reader = new WKTReader(new GeometryFactory());
            String bboxStr = convertPolygonToWKT(borderPolyGonN.getTextContent());

            Geometry polygon = null;
            try {
                polygon = reader.read(bboxStr);
            } catch (ParseException e) {
                log.log(Level.SEVERE, e.getMessage(), e);
                continue;
            } catch (IllegalArgumentException e) {
                log.log(Level.SEVERE, e.getMessage(), e);
                throw e;
            }

            Envelope env = polygon.getEnvelopeInternal();
            if (env == null || !(polygon instanceof Polygon)) {
                continue;
            }

            it.polygon = (Polygon) polygon;
        } else {
            throw new ParserConfigurationException("Could not Parse " + "Service. Bounding Box not Found");
        }
        items.add(it);
    }
}

From source file:de.conterra.suite.security.portal.gpx.EmbeddedSAMLTokenIntegrationContext.java

@Override
public String getUsernameFromSAMLToken(String base64EncodedToken) throws Exception {
    LOGGER.entering("EmbeddedSAMLTokenIntegrationContext", "getUsernameFromSAMLToken");
    XPath xpath = XPathFactory.newInstance().newXPath();
    Namespaces ns = new Namespaces();
    ns.add("sa", org.opensaml.XML.SAML_NS);
    // ns.add("sp", org.opensaml.XML.SAMLP_NS);
    xpath.setNamespaceContext(new NamespaceContextImpl(ns));
    String userId = (String) xpath.evaluate(
            "//sa:Assertion/sa:AuthenticationStatement/sa:Subject/sa:NameIdentifier/text()",
            createAndVerifySamlResponse(base64EncodedToken), XPathConstants.STRING);
    String s = Val.chkStr(userId);
    LOGGER.finest(MessageFormat.format("Returning userid '{0}' from given token.", s));
    return s;/*from ww w  .  j av  a  2s  .  c  om*/
}

From source file:com.alvexcore.repo.masterdata.getConstraintWork.java

protected List<Map<String, String>> getRestXmlMasterData(NodeRef source) throws Exception {
    NodeService nodeService = serviceRegistry.getNodeService();
    String url = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_REST_URL);
    String rootXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_ROOT_QUERY);
    String labelXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_LABEL);
    String valueXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_VALUE);
    String caching = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_REST_CACHE_MODE);

    // Standard of reading a XML file
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from w ww.  j  av a 2s  .c o  m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(url);

    // Create a XPathFactory
    XPathFactory xFactory = XPathFactory.newInstance();

    // Create a XPath object
    XPath xpath = xFactory.newXPath();

    // Compile the XPath expression
    XPathExpression setExpr = xpath.compile(rootXPath);
    XPathExpression valueExpr = xpath.compile(valueXPath);
    XPathExpression labelExpr = xpath.compile(labelXPath);

    // Run the query and get a nodeset
    Object result = setExpr.evaluate(doc, XPathConstants.NODESET);

    // Cast the result to a list
    NodeList nodes = (NodeList) result;
    List<Map<String, String>> res = new ArrayList<Map<String, String>>();
    for (int i = 0; i < nodes.getLength(); i++) {
        String value = (String) valueExpr.evaluate(nodes.item(i), XPathConstants.STRING);
        String label = (String) labelExpr.evaluate(nodes.item(i), XPathConstants.STRING);
        HashMap<String, String> resItem = new HashMap<String, String>();
        resItem.put("ref", "");
        resItem.put("value", value);
        resItem.put("label", label);
        res.add(resItem);
    }
    return res;
}

From source file:com.mnxfst.testing.client.TSClientPlanResultCollectCallable.java

/**
 * Parses the string value referenced by the given query
 * @param rootNode/*from www.  jav  a  2s . c o  m*/
 * @param query
 * @param xpath
 * @return
 * @throws TSClientExecutionException
 */
protected String parseStringValue(Node rootNode, String query, XPath xpath) throws TSClientExecutionException {

    String result = null;
    try {
        result = (String) xpath.evaluate(query, rootNode, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new TSClientExecutionException("Failed to parse out value for '" + query
                + "' from document received from " + httpHost.getHostName());
    }

    if (result == null || result.isEmpty())
        throw new TSClientExecutionException("Failed to parse out value for '" + query
                + "' from document received from " + httpHost.getHostName());

    return result;

}

From source file:com.esri.geoportal.commons.csw.client.impl.Client.java

/**
 * Reads record from the stream//from  w ww.  ja va 2 s.  c  om
 *
 * @param contentStream content stream
 * @return list of records
 * @throws IOException if reading records fails
 * @throws TransformerConfigurationException if creating transformer fails
 * @throws TransformerException if creating transformer fails
 * @throws ParserConfigurationException if unable to create XML parser
 * @throws SAXException if unable to parse content
 * @throws XPathExpressionException if invalid XPath
 */
private List<IRecord> readRecords(InputStream contentStream)
        throws IOException, TransformerConfigurationException, TransformerException,
        ParserConfigurationException, SAXException, XPathExpressionException {
    ArrayList<IRecord> records = new ArrayList<>();

    // create transformer
    Templates template = TemplatesManager.getInstance().getTemplate(profile.getResponsexslt());
    Transformer transformer = template.newTransformer();

    // perform transformation
    StringWriter writer = new StringWriter();
    transformer.transform(new StreamSource(contentStream), new StreamResult(writer));

    LOG.trace(String.format("Received records:\n%s", writer.toString()));

    try (ByteArrayInputStream transformedContentStream = new ByteArrayInputStream(
            writer.toString().getBytes("UTF-8"))) {

        // create internal request DOM
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document resultDom = builder.parse(new InputSource(transformedContentStream));

        // create xpath
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        NodeList recordNodeList = (NodeList) xpath.evaluate("/Records/Record", resultDom,
                XPathConstants.NODESET);
        for (int i = 0; i < recordNodeList.getLength(); i++) {
            Node recordNode = recordNodeList.item(i);
            String id = (String) xpath.evaluate("ID", recordNode, XPathConstants.STRING);
            String strModifiedDate = (String) xpath.evaluate("ModifiedDate", recordNode, XPathConstants.STRING);
            Date modifedDate = parseIsoDate(strModifiedDate);
            IRecord record = new Record(id, modifedDate);
            records.add(record);
        }
    }

    return records;
}

From source file:se.vgregion.usdservice.USDServiceImpl.java

/**
 * Parse group id's from from a USD-query.
 *
 * @param xml - standard USD query response.
 * @return - a formated (comma separated) string of group handles.
 *//*from   w  w w.j  a va  2  s  .c om*/
private String parseUserGroups(String xml) {
    String groups = "";
    try {
        // Parse the XML to get a DOM to query
        Document doc = parseXml(xml);

        // Extract USDObject's
        String xPath = "/UDSObjectList/UDSObject";
        NodeList udsObjects = evaluate(xPath, doc, XPathConstants.NODESET);

        // Iterate over USDObject's to create Issue's
        for (int i = 1; i < udsObjects.getLength() + 1; i++) {
            if (groups.length() > 0)
                groups += ",";
            groups += "U'" + extractAttribute(i, "group", XPathConstants.STRING, doc) + "'";
        }

        return groups;
    } catch (Exception e) {
        String msg = "Error when parsing group handles from XML";
        log.error(msg);
        throw new RuntimeException(msg, e);
    }
}