Example usage for javax.xml.xpath XPath evaluate

List of usage examples for javax.xml.xpath XPath evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPath evaluate.

Prototype

public String evaluate(String expression, InputSource source) throws XPathExpressionException;

Source Link

Document

Evaluate an XPath expression in the context of the specified InputSource and return the result as a String .

Usage

From source file:Main.java

/**
 * Processes the POST request from the client instructing the server to process 
 * a serverStart or serverProxy. Returns the fields in this request as a HashMap for
 * easy handling./*from ww w  . ja va2 s .  c o  m*/
 * 
 * @param xmlStream the InputStream obtained from an HttpServletRequest object. This contains the desired pipeline from the client.
 * @param search a HashMap with arbitrary names as keys and XPath Strings as values, the results of which are assigned as values to the names in the returned HashMap. 
 * @return
 */
public static HashMap<String, String> procPipelineReq(InputStream xmlStream, HashMap<String, String> search) {
    HashMap<String, String> returnHash = new HashMap<String, String>();
    try {
        for (String item : search.keySet()) {
            Document xmlDoc = parse(xmlStream);
            XPath xpath = xpathFactory.newXPath();
            returnHash.put(item, xpath.evaluate(search.get(item), xmlDoc));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return returnHash;
}

From source file:Main.java

/**
 * getStringFromXPath/*from w w  w  .j a  v a  2  s  .  c o m*/
 * Gets a string from an xml.
 * @param expression The XPath expression to evaluate, returns a string
 * @return The result of evaluating the given XPath expression.
 */
public static String getStringFromXPath(Document doc, XPath xpath, String expression) {
    synchronized (xpath) {
        try {
            return xpath.evaluate(expression, doc);
        } catch (Exception e) {
            System.err.println("Error evaluating xpath expression: " + expression);
            e.printStackTrace();
        }
        return "";
    }
}

From source file:edu.lternet.pasta.common.EmlUtility.java

/**
 * Returns the packageId of the provided EML document without parsing it
 * (the packageId). If the document does not contain the attribute
 * {@code //@packageId}, or if it does not have a value, an empty string
 * is returned.//from   ww w.ja  v  a2  s  .  co  m
 *
 * @param emlDocument
 *            an EML document.
 *
 * @return the packageId contained in the provided EML document.
 */
public static String getRawEmlPackageId(Document emlDocument) {

    try {

        XPath xpath = XPathFactory.newInstance().newXPath();
        return xpath.evaluate("//@packageId", emlDocument);

    } catch (XPathExpressionException e) {
        throw new IllegalStateException(e); // Should never be reached
    }

}

From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java

/**
 * Returns the query result or <code>null</code>.
 * /*w w  w .  j  a va 2  s  . co m*/
 * @param node
 *          the context node
 * @param xpathExpression
 *          the xpath expression
 * @param defaultValue
 *          the default value
 * @param processor
 *          the xpath engine
 * 
 * @return the selected string or <code>defaultValue</code> if the query
 *         didn't yield a result
 */
public static String valueOf(Node node, String xpathExpression, String defaultValue, XPath processor) {

    if (node == null || processor == null)
        return null;

    try {
        String value = StringUtils.trimToNull(processor.evaluate(xpathExpression, node));

        // If we are running in test mode, we may neglect namespaces
        if (value == null) {
            NamespaceContext ctx = processor.getNamespaceContext();
            if (ctx instanceof XPathNamespaceContext && ((XPathNamespaceContext) ctx).isTest()) {
                if (xpathExpression.matches("(.*)[a-zA-Z0-9]+\\:[a-zA-Z0-9]+(.*)")) {
                    String xpNs = xpathExpression.replaceAll("[a-zA-Z0-9]+\\:", "");
                    value = StringUtils.trimToNull(processor.evaluate(xpNs, node));
                }
            }
        }
        return (value != null) ? value : defaultValue;
    } catch (XPathExpressionException e) {
        logger.warn("Error when selecting '{}': {}", xpathExpression, e.getMessage());
        return null;
    }
}

From source file:com.opentok.OpenTok.java

private static String readXml(String xpathQuery, String xml) throws XPathExpressionException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    InputSource source = new InputSource(new StringReader(xml));
    return xpath.evaluate(xpathQuery, source);
}

From source file:org.hyperic.plugin.vrealize.automation.DiscoveryVRAIaasWeb.java

private static String getVCO(ConfigResponse config) {
    String vcoFNQ = null;//from w  w w .  j  av a 2  s  .  c  o  m
    String xml = null;

    String user = config.getValue("iaas.http.user", "");
    String pass = config.getValue("iaas.http.pass", "");
    String domain = config.getValue("iaas.http.domain", "");

    try {
        AgentKeystoreConfig ksCFG = new AgentKeystoreConfig();
        HQHttpClient client = new HQHttpClient(ksCFG, new HttpConfig(5000, 5000, null, 0),
                ksCFG.isAcceptUnverifiedCert());

        List<String> authpref = new ArrayList<String>();
        authpref.add(AuthPolicy.NTLM);
        authpref.add(AuthPolicy.BASIC);
        client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

        client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthPolicy.NTLM),
                new NTCredentials(user, pass, "localhost", domain));

        HttpGet get = new HttpGet(
                "https://localhost/Repository/Data/ManagementModelEntities.svc/ManagementEndpoints");
        HttpResponse response = client.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            xml = readInputString(response.getEntity().getContent());
        } else {
            log.debug("[getVCOx] GET failed: " + response.getStatusLine().getReasonPhrase());
        }
    } catch (IOException ex) {
        log.debug("[getVCOx] " + ex, ex);
    }

    if (xml != null) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = (Document) builder.parse(new ByteArrayInputStream(xml.getBytes()));

            log.debug("[getVCOx] xml:" + xml);

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

            String xPath = "//properties[InterfaceType[text()='vCO']]/ManagementEndpointName/text()";

            log.debug("[getVCOx] evaluating XPath:" + xPath);

            vcoFNQ = xpath.evaluate(xPath, doc);

            log.debug("[getVCOx] vcoFNQ:" + vcoFNQ);

        } catch (Exception ex) {
            log.debug("[getVCOx] " + ex, ex);
        }
    }

    return VRAUtils.getFqdn(vcoFNQ);
}

From source file:Main.java

/**
 * Evaluates the specified expression on the specified node and returns the
 * result as a String.//from   w  ww .jav a  2 s . c  om
 *
 * @param expression
 *            The Xpath expression to evaluate.
 * @param node
 *            The node on which to evaluate the expression.
 *
 * @return The result of evaluating the specified expression, or null if the
 *         evaluation didn't return any result.
 *
 * @throws XPathExpressionException
 *             If there are any problems evaluating the Xpath expression.
 */
private static String evaluateAsString(String expression, Node node, XPath xpath)
        throws XPathExpressionException {
    if (isEmpty(node))
        return null;

    if (!expression.equals(".")) {
        /*
         * If the expression being evaluated doesn't select a node, we want
         * to return null to distinguish between cases where a node isn't
         * present (which should be represented as null) and when a node is
         * present, but empty (which should be represented as the empty
         * string).
         *
         * We skip this test if the expression is "." since we've already
         * checked that the node exists.
         */
        if (asNode(expression, node, xpath) == null)
            return null;
    }

    String s = xpath.evaluate(expression, node);

    return s.trim();
}

From source file:com.taobao.android.builder.tools.manifest.ManifestFileUtils.java

public static String getApplicationName(File manifestFile) {
    XPath xpath = AndroidXPathFactory.newXPath();
    try {//from   w  w  w  .ja  v  a2  s.  c  om
        return xpath.evaluate("/manifest/application/@android:name",
                new InputSource(new FileInputStream(manifestFile)));
    } catch (XPathExpressionException e) {
        // won't happen.
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    return null;
}

From source file:jp.go.nict.langrid.bpel.ProcessAnalyzer.java

/**
 * /* www  .  j a v  a 2s. c o m*/
 * 
 */
public static BPEL analyzeBPEL(byte[] body) throws SAXException, URISyntaxException, XPathExpressionException {
    Document doc;
    try {
        doc = builder.parse(new ByteArrayInputStream(body));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Node root = doc.getDocumentElement();
    NamespaceContextImpl nsc = new NamespaceContextImpl();
    addNamespaceMappings(nsc, root.getAttributes());
    String rootNs = root.getNamespaceURI();
    nsc.addMapping("_", rootNs);
    XPath xpath = DocumentUtil.getDefaultXPath();
    xpath.setNamespaceContext(nsc);
    String processName = NodeUtil.getAttribute(root, "name");
    BPEL bpel = new BPEL();
    bpel.setBody(body);
    if (rootNs.equals(bpel4ws_1_1_ns)) {
        bpel.setBpelVersion(BPELVersion.BPEL4WS_1_1);
    } else if (rootNs.equals(wsbpel_2_0_ns)) {
        bpel.setBpelVersion(BPELVersion.WSBPEL_2_0);
    } else {
        bpel.setBpelVersion(BPELVersion.UNKNOWN);
    }
    bpel.setTargetNamespace(new URI(xpath.evaluate("/_:process/@targetNamespace", root)));
    bpel.setProcessName(processName);
    bpel.setFilename(processName + BPEL_EXTENSION);
    ArrayList<PartnerLink> links = new ArrayList<PartnerLink>();
    NodeList list = (NodeList) xpath.evaluate("/_:process/_:partnerLinks/_:partnerLink", root,
            XPathConstants.NODESET);
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        PartnerLink pl = new PartnerLink(nsc, node);
        links.add(pl);
    }
    bpel.setPartnerLinks(links);
    return bpel;
}

From source file:com.taobao.android.builder.tools.manifest.ManifestFileUtils.java

public static String getPackage(File manifestFile) {

    String version = manifestMap.get(manifestFile.getAbsolutePath());
    if (null != version) {
        return version;
    }/* ww w  .ja  v  a  2  s  .c  om*/

    XPath xpath = AndroidXPathFactory.newXPath();

    try {
        version = xpath.evaluate("/manifest/@package", new InputSource(new FileInputStream(manifestFile)));
        manifestMap.put(manifestFile.getAbsolutePath(), version);
        return version;
    } catch (XPathExpressionException e) {
        // won't happen.
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    return null;
}