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:se.vgregion.usdservice.USDServiceImpl.java

private static String extractAttribute(int cnt, String attrName, QName attrType, Document source)
        throws XPathExpressionException {
    String exprTemplate = "/UDSObjectList/UDSObject[%s]/Attributes/Attribute[AttrName='%s']/AttrValue";
    String xPath = String.format(exprTemplate, cnt, attrName);

    return evaluate(xPath, source, XPathConstants.STRING);
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Populate JavaBean properties via XPath extraction.
 * /*from  w  w w  .  j  ava  2s .  c  o m*/
 * <p>
 * This method will call {@link #registerCustomEditors(BeanWrapper)} so
 * custom editors can be registered if desired.
 * </p>
 * 
 * @param obj
 *        the object to set properties on, or a BeanWrapper
 * @param xml
 *        the XML
 * @param xpathMap
 *        the mapping of JavaBean property names to XPaths
 */
protected void extractBeanDataFromXml(Object obj, Node xml, Map<String, XPathExpression> xpathMap) {
    BeanWrapper bean;
    if (obj instanceof BeanWrapper) {
        bean = (BeanWrapper) obj;
    } else {
        bean = PropertyAccessorFactory.forBeanPropertyAccess(obj);
    }
    registerCustomEditors(bean);
    for (Map.Entry<String, XPathExpression> me : xpathMap.entrySet()) {
        try {
            String val = (String) me.getValue().evaluate(xml, XPathConstants.STRING);
            if (val != null && !"".equals(val)) {
                bean.setPropertyValue(me.getKey(), val);
            }
        } catch (XPathExpressionException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java

protected Document sendPostRequest(String url, Document xml) {
    logXmlDocumentToDebug("submitting", xml);
    try {//from w  w  w  . ja  v  a  2  s.co m
        WebResource webResource = httpClient.resource(url);
        Document response = webResource.accept(MediaType.APPLICATION_XML)
                .header("Content-Type", "application/xml").post(Document.class, xml);
        logXmlDocumentToDebug("Got response", response);
        return response;
    } catch (UniformInterfaceException e) {
        ClientResponse resp = e.getResponse();
        Document errorXml = resp.getEntity(Document.class);
        String errormessage = e.getMessage();
        try {
            errormessage = (String) xPath.evaluate("/api-response/errors/error", errorXml,
                    XPathConstants.STRING);
        } catch (XPathExpressionException e1) {
            // ignore
        }
        LOGGER.error("couldn't submit job: {}", errormessage);
        return errorXml;
    } catch (Exception e) {
        if (e instanceof SocketTimeoutException) {
            LOGGER.warn("Connection to Zencoder timed out");
        } else {
            LOGGER.warn(e.getMessage());
        }
    }
    return null;

}

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

/**
 * Determines whether a Flickr photo has geo-coded location with Australia
 * as the country. <br />/*from www  .j a  va 2 s  . c  o m*/
 * 
 * XPath used to extract this information is
 * <code>/rsp/photo/location/country/text()</code> <br />
 * 
 * Non case-sensitive String comparison is performed.
 * 
 * @param photoInfoXmlDom
 *            DOM representation of XML result from calling
 *            <code>flickr.photos.search</code> Flickr method.
 * 
 * @return <code>true</code> if photo has geo-coded location for Australia,
 *         <code>false</code> otherwise.
 * 
 * @throws csiro.diasb.protocolhandlers.Exception
 *             On error.
 * 
 * @since v0.4
 */
private boolean isPhotoFromAustralia(org.w3c.dom.Document photoInfoXmlDom) throws Exception {

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

    if (photoInfoXmlDom == null) {
        String errMsg = "DOM of Photo Info. XML has null reference.";
        logger.error(errMsg);
        throw new Exception(errMsg);
    }

    String photoTitle = (String) xpath.evaluate("/rsp/photo/title/text()", photoInfoXmlDom,
            XPathConstants.STRING);
    String photoDescription = (String) xpath.evaluate("/rsp/photo/description/text()", photoInfoXmlDom,
            XPathConstants.STRING);
    String photoCountry = (String) xpath.evaluate("/rsp/photo/location/country/text()", photoInfoXmlDom,
            XPathConstants.STRING);

    //check the machine tags
    String xPathToTags = "/rsp/photo/tags/tag/text()";
    NodeList nl = (NodeList) xpath.evaluate(xPathToTags, photoInfoXmlDom, XPathConstants.NODESET);
    for (int i = 0; i < nl.getLength(); i++) {
        String content = nl.item(i).getNodeValue();
        if (content != null) {
            content = content.toLowerCase();
            if (content.contains("australia")) {
                return true;
            }
        }
    }

    if ("australia".compareToIgnoreCase(photoCountry) == 0
            || (photoTitle != null && photoTitle.toLowerCase().contains("australia"))
            || (photoDescription != null && photoDescription.toLowerCase().contains("australia"))) {
        return true;
    }

    return false;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

private static void readJARAConfiguration(Document xmlConfiguration, XPath xpath)
        throws XPathExpressionException {
    // jara url//from  w  ww .  j  av  a  2  s  .c  o  m
    jaraUrl = (String) xpath.compile("/configuration/general/jara/url/@value").evaluate(xmlConfiguration,
            XPathConstants.STRING);
    jaraUrl = Utils.removeLastSlash(jaraUrl);

    // jara config directory
    jaraConfigPath = (String) xpath.compile("/configuration/general/jara/config-dir/@value")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
}

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

/**
 * Parses the XML listing of images to obtain data necessary for future data
 * extraction. Specifically, the current page number, current images per
 * page and total number of pages.// w  ww. j  a v  a2s .  c  om
 * 
 * @since v0.4
 */
private int[] parseDataFragmentationInfo(Document currentResDom) throws Exception {

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

    try {
        int currentPageNum = Integer
                .parseInt((String) xpath.evaluate("/rsp/photos/@page", currentResDom, XPathConstants.STRING));
        int totalPages = Integer
                .parseInt((String) xpath.evaluate("/rsp/photos/@pages", currentResDom, XPathConstants.STRING));
        int actualRecordsPerPage = Integer.parseInt(
                (String) xpath.evaluate("count(/rsp/photos/photo)", currentResDom, XPathConstants.STRING));

        logger.debug("Extracted and set current page number to " + currentPageNum);
        logger.debug("Extracted and set total page number to " + totalPages);
        logger.debug("Actual number of records returned is " + actualRecordsPerPage);

        return new int[] { currentPageNum, totalPages, actualRecordsPerPage };

    } catch (XPathExpressionException getPageFragmentationError) {
        String errMsg = "Failed to obtain data fragmentation information from Flickr's REST response.";
        throw new Exception(errMsg, getPageFragmentationError);
    }

}

From source file:com.espertech.esper.regression.event.TestNoSchemaXMLEvent.java

public void testNamespaceXPathAbsolute() throws Exception {
    Configuration configuration = SupportConfigFactory.getConfiguration();
    ConfigurationEventTypeXMLDOM desc = new ConfigurationEventTypeXMLDOM();
    desc.addXPathProperty("symbol_a", "//m0:symbol", XPathConstants.STRING);
    desc.addXPathProperty("symbol_b",
            "//*[local-name(.) = 'getQuote' and namespace-uri(.) = 'http://services.samples/xsd']",
            XPathConstants.STRING);
    desc.addXPathProperty("symbol_c", "/m0:getQuote/m0:request/m0:symbol", XPathConstants.STRING);
    desc.setRootElementName("getQuote");
    desc.setDefaultNamespace("http://services.samples/xsd");
    desc.setRootElementNamespace("http://services.samples/xsd");
    desc.addNamespacePrefix("m0", "http://services.samples/xsd");
    desc.setXPathResolvePropertiesAbsolute(true);
    desc.setXPathPropertyExpr(true);//from   w  w  w.  j av a  2  s  .  co  m
    configuration.addEventType("StockQuote", desc);

    epService = EPServiceProviderManager.getDefaultProvider(configuration);
    epService.initialize();
    updateListener = new SupportUpdateListener();

    String stmt = "select symbol_a, symbol_b, symbol_c, request.symbol as symbol_d, symbol as symbol_e from StockQuote";
    EPStatement joinView = epService.getEPAdministrator().createEPL(stmt);
    joinView.addListener(updateListener);

    String xml = "<m0:getQuote xmlns:m0=\"http://services.samples/xsd\"><m0:request><m0:symbol>IBM</m0:symbol></m0:request></m0:getQuote>";
    //String xml = "<getQuote><request><symbol>IBM</symbol></request></getQuote>";
    StringReader reader = new StringReader(xml);
    InputSource source = new InputSource(reader);
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    Document doc = builderFactory.newDocumentBuilder().parse(source);

    // For XPath resolution testing and namespaces...
    /*
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathNamespaceContext ctx = new XPathNamespaceContext();
    ctx.addPrefix("m0", "http://services.samples/xsd");
    xPath.setNamespaceContext(ctx);
    XPathExpression expression = xPath.compile("/m0:getQuote/m0:request/m0:symbol");
    xPath.setNamespaceContext(ctx);
    System.out.println("result=" + expression.evaluate(doc,XPathConstants.STRING));
    */

    epService.getEPRuntime().sendEvent(doc);
    EventBean theEvent = updateListener.assertOneGetNewAndReset();
    assertEquals("IBM", theEvent.get("symbol_a"));
    assertEquals("IBM", theEvent.get("symbol_b"));
    assertEquals("IBM", theEvent.get("symbol_c"));
    assertEquals("IBM", theEvent.get("symbol_d"));
    assertEquals("", theEvent.get("symbol_e")); // should be empty string as we are doing absolute XPath
}

From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

/**
 * @param pluginXmlDTO// w w w. ja  v a2 s  .  co  m
 * @param xpath
 * @param pluginNodeList
 * @throws
 */
private void extractPluginDependenciesFromXml(PluginXmlDTO pluginXmlDTO, XPath xpath, NodeList pluginNodeList)
        throws UIException {
    NodeList pluginDependenciesNode;
    try {
        pluginDependenciesNode = (NodeList) xpath.evaluate(
                SystemConfigSharedConstants.DEPENDENCIES_LIST_DEPENDENCY, pluginNodeList.item(0),
                XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        String errorMsg = "Invalid xml content. A mandatory field is missing.";
        LOGGER.error(errorMsg, e);
        throw new UIException(errorMsg);
    }
    LOGGER.info("Extracting Dependencies from xml:");

    List<PluginDependencyXmlDTO> pluginDependencyXmlDTOs = new ArrayList<PluginDependencyXmlDTO>(0);
    int numberOfDependencies = pluginDependenciesNode.getLength();
    LOGGER.info(numberOfDependencies + " dependencies found");
    for (int index = 0; index < numberOfDependencies; index++) {
        PluginDependencyXmlDTO pluginDependencyXmlDTO = new PluginDependencyXmlDTO();
        LOGGER.info("Plugin Dependency " + index + ":");
        String dependencyType = SystemConfigSharedConstants.EMPTY_STRING;
        String dependencyValue = SystemConfigSharedConstants.EMPTY_STRING;
        String operation = SystemConfigSharedConstants.EMPTY_STRING;
        try {
            dependencyType = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_DEPENDENCY_TYPE,
                    pluginDependenciesNode.item(index), XPathConstants.STRING);
            dependencyValue = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_DEPENDENCY_VALUE,
                    pluginDependenciesNode.item(index), XPathConstants.STRING);
            operation = (String) xpath.evaluate(SystemConfigSharedConstants.OPERATION,
                    pluginDependenciesNode.item(index), XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            String errorMsg = "Error in xml content. A mandatory field is missing.";
            LOGGER.error(errorMsg, e);
            throw new UIException(errorMsg);
        }

        if (!dependencyType.isEmpty() && !dependencyValue.isEmpty()) {
            LOGGER.info("Type: " + dependencyType);
            LOGGER.info("Value: " + dependencyValue);
            pluginDependencyXmlDTO.setPluginDependencyType(dependencyType);

            pluginDependencyXmlDTO.setPluginDependencyValue(dependencyValue);

            pluginDependencyXmlDTO.setOperation(operation);

            pluginDependencyXmlDTOs.add(pluginDependencyXmlDTO);
        }
    }
    pluginXmlDTO.setDependencyXmlDTOs(pluginDependencyXmlDTOs);
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

/**
 * TODO//from   w ww  . ja  v  a 2s .  c om
 *
 * @return
 * @throws XPathExpressionException 
 */
private static GeosearchFilesVO readGeosearchMasterFiles(Document xmlConfiguration, XPath xpath)
        throws XPathExpressionException {
    GeosearchFilesVO geosearchFilesVO = new GeosearchFilesVO();

    // DATAIMPORT
    String dataImportName = (String) xpath
            .compile("/configuration/general/geosearch/master/files/dataImport/@name")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    String dataImportJavaClass = (String) xpath
            .compile("/configuration/general/geosearch/master/files/dataImport/@class")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    String dataImportFileName = (String) xpath
            .compile("/configuration/general/geosearch/master/files/dataImport/@fileName")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    String dataImportType = (String) xpath
            .compile("/configuration/general/geosearch/master/files/dataImport/@type")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    String dataImportDriver = (String) xpath
            .compile("/configuration/general/geosearch/master/files/dataImport/@driver")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    String dataImportTransformer = (String) xpath
            .compile("/configuration/general/geosearch/master/files/dataImport/@transformer")
            .evaluate(xmlConfiguration, XPathConstants.STRING);

    GeosearchDataImportFileVO dataImportFileVO = new GeosearchDataImportFileVO();
    dataImportFileVO.setName(dataImportName);
    dataImportFileVO.setJavaClass(dataImportJavaClass);
    dataImportFileVO.setFileName(dataImportFileName);
    dataImportFileVO.setType(dataImportType);
    dataImportFileVO.setDriver(dataImportDriver);
    dataImportFileVO.setTransformer(dataImportTransformer);

    // CONFIG  
    String configFileName = (String) xpath
            .compile("/configuration/general/geosearch/master/files/config/@fileName")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    String searchHandler = (String) xpath
            .compile("/configuration/general/geosearch/master/files/config/@searchHandler")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    GeosearchConfigFileVO configFileVO = new GeosearchConfigFileVO();
    configFileVO.setFileName(configFileName);
    configFileVO.setSearchHandler(searchHandler);

    // SCHEMA
    String schemaFileName = (String) xpath
            .compile("/configuration/general/geosearch/master/files/schema/@fileName")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    String defaultSearchField = (String) xpath
            .compile("/configuration/general/geosearch/master/files/schema/@defaultSearchField")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
    GeosearchSchemaFileVO schemaFileVO = new GeosearchSchemaFileVO();
    schemaFileVO.setFileName(schemaFileName);
    schemaFileVO.setDefaultSearchField(defaultSearchField);

    geosearchFilesVO.setDataImport(dataImportFileVO);
    geosearchFilesVO.setConfig(configFileVO);
    geosearchFilesVO.setSchema(schemaFileVO);

    return geosearchFilesVO;
}