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:org.sakaiproject.mediasite.tool.MediasiteLTI.java

public static String getConfigValue(Document doc, XPath xpath, String id, String name) {
    String value = null;/*from w w w . j a  v  a  2 s. c  o  m*/
    try {
        XPathExpression expr = xpath
                .compile("/registration/tool[@id='" + id + "']/configuration[@name='" + name + "']/@value");
        value = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return value;
}

From source file:org.sonar.api.utils.XpathParser.java

public String executeXPath(String xPathExpression) {
    return (String) executeXPath(doc, XPathConstants.STRING, xPathExpression);
}

From source file:org.sonar.api.utils.XpathParser.java

public String executeXPath(Node node, String xPathExpression) {
    return (String) executeXPath(node, XPathConstants.STRING, xPathExpression);
}

From source file:org.structr.javaparser.JavaParserModule.java

private void handlePomFile(final File file, final Folder folder, final Folder parentFolder) {

    final XPath xpath = XPathFactory.newInstance().newXPath();
    QName returnType = XPathConstants.STRING;

    final String content = file.getFavoriteContent();
    final String projectName;

    try {//from   www . j  a  v a  2  s . c  o  m
        projectName = (String) xpath.evaluate("/project/name", parseXml(content), returnType);

        final Module newMod = createModule(projectName, folder);

        logger.info("Created module '" + projectName + "' in folder " + folder.getPath());

        // Check if we are child of a parent module
        // Find the closest ancestor folder which has a module
        Module mod = null;

        Folder possibleModuleParentFolder = parentFolder;

        // Continue until root folder or a module was found
        while (possibleModuleParentFolder != null && mod == null) {

            try {
                mod = app.nodeQuery(Module.class).and(Module.folder, possibleModuleParentFolder).getFirst();

            } catch (FrameworkException ignore) {
            }

            if (mod != null) {

                newMod.setProperty(Module.parent, mod);
                break;
            }

            // Continue while loop
            possibleModuleParentFolder = possibleModuleParentFolder.getParent();
        }

    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException
            | FrameworkException ex) {
        logger.warn("Exception exception occured", ex);
    }
}

From source file:org.talend.job.Configer.java

static String getStringValue(String path, String dv) {
    org.w3c.dom.Document doc = loadDocument();
    if (null != doc) {
        try {//from  www .  jav  a  2  s.co  m
            XPathExpression x_path = xpath.compile(path);
            String value = (String) x_path.evaluate(doc, XPathConstants.STRING);
            if (StringUtils.isEmpty(value)) {
                return dv;
            }
            return value;
        } catch (XPathExpressionException e) {
            logger.error(e.getMessage());
        }
    }
    return dv;
}

From source file:org.trustedanalytics.cfbroker.config.HadoopZipConfiguration.java

private Map<String, String> getAsMap() throws IOException, XPathExpressionException {
    InputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(Base64.decodeBase64(encodedZip)));
    ZipEntry zipFileEntry;/*from   w  w w  .  j  av a2 s . c  o m*/
    Map<String, String> map = new HashMap<>();
    while ((zipFileEntry = ((ZipInputStream) zipInputStream).getNextEntry()) != null) {
        if (!zipFileEntry.getName().endsWith("-site.xml")) {
            continue;
        }
        byte[] bytes = IOUtils.toByteArray(zipInputStream);
        InputSource is = new InputSource(new ByteArrayInputStream(bytes));
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate(ConfigConstants.CONF_PROPERTY_XPATH, is,
                XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node propNode = nodeList.item(i);
            String key = (String) xPath.evaluate("name/text()", propNode, XPathConstants.STRING);
            String value = (String) xPath.evaluate("value/text()", propNode, XPathConstants.STRING);
            map.put(key, value);
        }
    }
    return map;
}

From source file:org.wandora.modules.ModuleManager.java

/**
 * Parses a single param element and returns its value. Handles all the
 * different cases of how a param elements value can be determined.
 * //from w w w . j a  v  a 2s . com
 * @param e The xml param element.
 * @return The value of the parameter.
 */
public Object parseXMLParamElement(Element e)
        throws ReflectiveOperationException, IllegalArgumentException, ScriptException {
    String instance = e.getAttribute("instance");
    if (instance != null && instance.length() > 0) {
        Class cls = Class.forName(instance);
        HashMap<String, Object> params = parseXMLOptionsElement(e);
        if (!params.isEmpty()) {
            Collection<Object> constructorParams = params.values();
            Constructor[] cs = cls.getConstructors();
            ConstructorLoop: for (int i = 0; i < cs.length; i++) {
                Constructor c = cs[i];
                Class[] paramTypes = c.getParameterTypes();
                if (paramTypes.length != constructorParams.size())
                    continue;

                int j = -1;
                for (Object o : constructorParams) {
                    j++;
                    if (o == null) {
                        if (!paramTypes[j].isPrimitive())
                            continue;
                        else
                            continue ConstructorLoop;
                    }

                    if (paramTypes[j].isPrimitive()) {
                        if (paramTypes[j] == int.class) {
                            if (o.getClass() != Integer.class)
                                continue ConstructorLoop;
                        } else if (paramTypes[j] == long.class) {
                            if (o.getClass() != Long.class)
                                continue ConstructorLoop;
                        } else if (paramTypes[j] == double.class) {
                            if (o.getClass() != Double.class)
                                continue ConstructorLoop;
                        } else if (paramTypes[j] == float.class) {
                            if (o.getClass() != Float.class)
                                continue ConstructorLoop;
                        } else if (paramTypes[j] == byte.class) {
                            if (o.getClass() != Byte.class)
                                continue ConstructorLoop;
                        } else
                            continue ConstructorLoop; //did we forget some primitive type?
                    } else if (!o.getClass().isAssignableFrom(paramTypes[j]))
                        continue ConstructorLoop;
                }

                return c.newInstance(constructorParams.toArray());
            }
            throw new NoSuchMethodException(
                    "Couldn't find a constructor that matches parameters parsed from XML.");
        } else {
            return cls.newInstance();
        }
    }

    String clas = e.getAttribute("class");
    if (clas != null && clas.length() > 0) {
        Class cls = Class.forName(clas);
        return cls;
    }

    if (e.hasAttribute("null"))
        return null;

    if (e.hasAttribute("script")) {
        String engine = e.getAttribute("script");
        if (engine.length() == 0 || engine.equalsIgnoreCase("default"))
            engine = ScriptManager.getDefaultScriptEngine();
        ScriptManager scriptManager = new ScriptManager();
        ScriptEngine scriptEngine = scriptManager.getScriptEngine(engine);
        scriptEngine.put("moduleManager", this);
        scriptEngine.put("element", e);

        try {
            String script = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim();
            return scriptManager.executeScript(script, scriptEngine);
        } catch (XPathExpressionException xpee) {
            throw new RuntimeException(xpee);
        }
    }

    if (e.hasAttribute("module")) {
        String moduleName = e.getAttribute("module").trim();
        return new ModuleDelegate(this, moduleName);
    }

    try {
        String value = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim();
        return replaceVariables(value, variables);
    } catch (XPathExpressionException xpee) {
        throw new RuntimeException(xpee);
    }
}

From source file:org.wandora.modules.ModuleManager.java

/**
 * Parses a variable element and defines that variable for future use.
 * /*from w w w .  java  2 s  . c  om*/
 * @param e The variable element.
 * @param variables The variable map into which the variable is defined.
 */
public void parseXMLVariable(Element e, HashMap<String, String> variables) {
    if (xpath == null)
        xpath = XPathFactory.newInstance().newXPath();

    try {
        String key = e.getAttribute("key");
        String value = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim();
        value = replaceVariables(value, variables);
        setVariable(key, value);
    } catch (XPathExpressionException xpee) {
        throw new RuntimeException(xpee); // hardcoded xpath expressions so this shouldn't really happen
    }
}

From source file:org.wattdepot.client.http.api.collector.NOAAWeatherCollector.java

@Override
public void run() {
    Measurement meas = null;/*from  ww w.j av  a  2s  .c  o  m*/
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        // Have to make HTTP connection manually so we can set proper timeouts
        URL url = new URL(noaaWeatherUri);
        URLConnection httpConnection;
        httpConnection = url.openConnection();
        // Set both connect and read timeouts to 15 seconds. No point in long
        // timeouts since the
        // sensor will retry before too long anyway.
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(15 * 1000);
        httpConnection.connect();

        // Record current time as close approximation to time for reading we are
        // about to make
        Date timestamp = new Date();

        Document doc = builder.parse(httpConnection.getInputStream());

        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        // path to the data
        String valString = "/current_observation/" + this.registerName + "/text()";
        XPathExpression exprValue = xPath.compile(valString);
        Object result = new Double(0);
        if (this.registerName.equals("weather")) {
            Object cloudCoverage = exprValue.evaluate(doc, XPathConstants.STRING);
            String cloudStr = cloudCoverage.toString();
            if (cloudStr.equalsIgnoreCase("sunny") || cloudStr.equalsIgnoreCase("clear")) {
                // 0 to 1/8 cloud coverage
                result = new Double(6.25);
            } else if (cloudStr.equalsIgnoreCase("mostly sunny") || cloudStr.equalsIgnoreCase("mostly clear")) {
                // 1/8 to 2/8 cloud coverage
                result = new Double(18.75);
            } else if (cloudStr.equalsIgnoreCase("partly sunny")
                    || cloudStr.equalsIgnoreCase("partly cloudy")) {
                // 3/8 to 5/8 cloud coverage
                result = new Double(50.0);
            } else if (cloudStr.equalsIgnoreCase("mostly cloudy")) {
                // 6/8 to 7/8 cloud coverage
                result = new Double(81.25);
            } else if (cloudStr.equalsIgnoreCase("cloudy")) {
                // 7/8 to 100% cloud coverage
                result = new Double(93.75);
            }
        } else {
            result = exprValue.evaluate(doc, XPathConstants.NUMBER);
        }

        Double value = (Double) result;
        meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit);
    } catch (MalformedURLException e) {
        System.err.format("URI %s was invalid leading to malformed URL%n", noaaWeatherUri);
    } catch (XPathExpressionException e) {
        System.err.println("Bad XPath expression, this should never happen.");
    } catch (ParserConfigurationException e) {
        System.err.println("Unable to configure XML parser, this is weird.");
    } catch (SAXException e) {
        System.err.format("%s: Got bad XML from eGauge sensor %s (%s), hopefully this is temporary.%n",
                Tstamp.makeTimestamp(), sensor.getName(), e);
    } catch (IOException e) {
        System.err.format(
                "%s: Unable to retrieve data from eGauge sensor %s (%s), hopefully this is temporary.%n",
                Tstamp.makeTimestamp(), sensor.getName(), e);
    }

    if (meas != null) {
        try {
            this.client.putMeasurement(depository, meas);
        } catch (MeasurementTypeException e) {
            System.err.format("%s does not store %s measurements%n", depository.getName(),
                    meas.getMeasurementType());
        }
        if (debug) {
            System.out.println(meas);
        }
    }
}

From source file:org.wso2.carbon.andes.utils.MBDatabaseConfig.java

/**
 * Construct MB database config. This will load config values
 * reading from file/*from   w  ww.  ja  v  a 2s.  co  m*/
 *
 * @param filePath path of the file containing configs of data source jndi names
 */
public MBDatabaseConfig(String filePath) {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

    try {
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document dDoc = builder.parse(filePath);
        XPath xPath = XPathFactory.newInstance().newXPath();

        String messageStoreXpath = "/broker/persistence/messageStore/property[@name='dataSource']";
        String contextStoreXpath = "/broker/persistence/contextStore/property[@name='dataSource']";

        messageStoreJndiName = (String) xPath.evaluate(messageStoreXpath, dDoc, XPathConstants.STRING);
        contextStoreJndiName = (String) xPath.evaluate(contextStoreXpath, dDoc, XPathConstants.STRING);

    } catch (ParserConfigurationException | IOException | XPathExpressionException | SAXException e) {

        log.error("Error when parsing file " + filePath + " to get MB data source JNDI names", e);

    }

}