Example usage for javax.xml.xpath XPathExpression evaluate

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

Introduction

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

Prototype

public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:de.codesourcery.eve.apiclient.utils.XMLParseHelper.java

public static Node selectNode(Document doc, XPathExpression expr, boolean isRequired) {

    final Node result;
    try {/*from w  w  w  .  ja v  a2s.co  m*/
        result = (Node) expr.evaluate(doc, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Internal error while evaluating XPath expression " + expr, e);
    }

    if (result == null) {
        if (isRequired) {
            throw new UnparseableResponseException(
                    "Unexpected response XML," + " XPath expression returned nothing: " + expr);
        }
        return null;
    }

    return result;
}

From source file:de.codesourcery.eve.apiclient.utils.XMLParseHelper.java

public static String selectAttributeValue(Document doc, XPathExpression expr, boolean isRequired) {

    final String result;
    try {/*  ww  w .ja  v  a  2 s. co  m*/
        result = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Internal error while evaluating XPath expression " + expr, e);
    }

    if (StringUtils.isBlank(result)) {
        if (isRequired) {
            throw new UnparseableResponseException(
                    "Unexpected response XML," + " XPath expression returned nothing: " + expr);
        }
        return null;
    }

    return result;
}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

/**
 * returns the name of a XCAS- document/*from   ww w. j  a v a2s  .  c o  m*/
 * 
 * @param input
 * @param stmts
 * @param vf
 * @param id
 * @param f
 * @throws Exception
 */
public static void getDocumentTitle(String input, Set<Statement> stmts, ValueFactory vf, String id, File f)
        throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(f);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//com.temis.uima.Zone[@name='title']");

    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0, n = nodes.getLength(); i < n; i++) {
        String begin = nodes.item(i).getAttributes().getNamedItem("begin").getTextContent();
        String end = nodes.item(i).getAttributes().getNamedItem("end").getTextContent();

        stmts.add(vf.createStatement(
                vf.createURI(EndpointImpl.api().getNamespaceService().defaultNamespace() + id), RDFS.LABEL,
                vf.createLiteral(input.substring(Integer.parseInt(begin), Integer.parseInt(end)))));
    }
}

From source file:de.codesourcery.eve.apiclient.utils.XMLParseHelper.java

public static List<Element> selectElements(Document doc, XPathExpression expr, boolean isRequired) {
    final NodeList result;
    try {//from   w ww  . j  a  v a 2 s  .  c  o  m
        result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Internal error while evaluating XPath expression " + expr, e);
    }

    if (result.getLength() == 0) {
        if (isRequired) {
            throw new UnparseableResponseException(
                    "Unexpected response XML," + " XPath expression returned nothing: " + expr);
        }
        return Collections.emptyList();
    }

    return new AbstractList<Element>() {

        @Override
        public Element get(int index) {
            return (Element) result.item(index);
        }

        @Override
        public int size() {
            return result.getLength();
        }
    };
}

From source file:eu.europa.esig.dss.XmlDom.java

private static NodeList getNodeList(final Node xmlNode, final String xpathString) {

    try {/* ww w  .j ava2  s.c  om*/

        final XPathExpression expr = createXPathExpression(xpathString);
        return (NodeList) expr.evaluate(xmlNode, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {

        throw new RuntimeException(e);
    }
}

From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * @param responseString//  w ww .j  a v  a 2 s .  com
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
public static HashMap<String, HashMap<String, String>> responseFactory(String responseString)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    HashMap<String, HashMap<String, String>> returnMap = new HashMap<String, HashMap<String, String>>();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(new InputSource(new StringReader(responseString)));

    //String messageName = document.getFirstChild().getNodeName();

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

    xpath.setNamespaceContext(new SugarCRMNamespaceContext());
    XPathExpression expr = xpath.compile("//ns1:get_entry_listResponse/return/entry_list/item");

    Object result = expr.evaluate(document, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    for (int i = 0; i < nodes.getLength(); i++) {

        NodeList innerNodes = nodes.item(i).getChildNodes();

        String id = innerNodes.item(0).getTextContent();

        HashMap<String, String> elementData = new HashMap<String, String>();

        NodeList infoNodes = innerNodes.item(2).getChildNodes();

        for (int z = 0; z < infoNodes.getLength(); z++) {
            String name = infoNodes.item(z).getFirstChild().getTextContent();
            String value = infoNodes.item(z).getLastChild().getTextContent();

            elementData.put(name, value);
        }
        returnMap.put(id, elementData);
    }
    return returnMap;
}

From source file:de.egore911.versioning.deployer.Main.java

private static void perform(String arg, CommandLine line) throws IOException {
    URL url;/*  w ww . jav a2 s .c o m*/
    try {
        url = new URL(arg);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        System.exit(1);
        return;
    }

    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();
        if (response != HttpURLConnection.HTTP_OK) {
            LOG.error("Could not download {}", url);
            connection.disconnect();
            System.exit(1);
            return;
        }
    } catch (ConnectException e) {
        LOG.error("Error during download from URI {}: {}", url, e.getMessage());
        System.exit(1);
        return;
    }

    XmlHolder xmlHolder = XmlHolder.getInstance();
    DocumentBuilder documentBuilder = xmlHolder.documentBuilder;
    XPath xPath = xmlHolder.xPath;

    try {

        XPathExpression serverNameXpath = xPath.compile("/server/name/text()");
        XPathExpression serverTargetdirXpath = xPath.compile("/server/targetdir/text()");
        XPathExpression serverDeploymentsDeploymentXpath = xPath.compile("/server/deployments/deployment");

        Document doc = documentBuilder.parse(connection.getInputStream());
        connection.disconnect();

        String serverName = (String) serverNameXpath.evaluate(doc, XPathConstants.STRING);
        LOG.info("Deploying {}", serverName);

        boolean shouldPerformCopy = !line.hasOption('r');
        PerformCopy performCopy = new PerformCopy(xPath);
        boolean shouldPerformExtraction = !line.hasOption('r');
        PerformExtraction performExtraction = new PerformExtraction(xPath);
        boolean shouldPerformCheckout = !line.hasOption('r');
        PerformCheckout performCheckout = new PerformCheckout(xPath);
        boolean shouldPerformReplacement = true;
        PerformReplacement performReplacement = new PerformReplacement(xPath);

        String targetdir = (String) serverTargetdirXpath.evaluate(doc, XPathConstants.STRING);
        FileUtils.forceMkdir(new File(targetdir));

        NodeList serverDeploymentsDeploymentNodes = (NodeList) serverDeploymentsDeploymentXpath.evaluate(doc,
                XPathConstants.NODESET);
        int max = serverDeploymentsDeploymentNodes.getLength();
        for (int i = 0; i < serverDeploymentsDeploymentNodes.getLength(); i++) {
            Node serverDeploymentsDeploymentNode = serverDeploymentsDeploymentNodes.item(i);

            // Copy
            if (shouldPerformCopy) {
                performCopy.perform(serverDeploymentsDeploymentNode);
            }

            // Extraction
            if (shouldPerformExtraction) {
                performExtraction.perform(serverDeploymentsDeploymentNode);
            }

            // Checkout
            if (shouldPerformCheckout) {
                performCheckout.perform(serverDeploymentsDeploymentNode);
            }

            // Replacement
            if (shouldPerformReplacement) {
                performReplacement.perform(serverDeploymentsDeploymentNode);
            }

            logPercent(i + 1, max);
        }

        // validate that "${versioning:" is not present
        Collection<File> files = FileUtils.listFiles(new File(targetdir), TrueFileFilter.TRUE,
                TrueFileFilter.INSTANCE);
        for (File file : files) {
            String content;
            try {
                content = FileUtils.readFileToString(file);
            } catch (IOException e) {
                continue;
            }
            if (content.contains("${versioning:")) {
                LOG.error("{} contains placeholders even after applying the replacements",
                        file.getAbsolutePath());
            }
        }

        LOG.info("Done deploying {}", serverName);

    } catch (SAXException | IOException | XPathExpressionException e) {
        LOG.error("Error performing deployment: {}", e.getMessage(), e);
    }
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

protected static byte[] toByteArray(Document doc, boolean prettyPrint)
        throws TransformerException, XPathExpressionException {
    final TransformerFactory transformerFactory = TransformerFactory.newInstance();
    final Transformer transformer = transformerFactory.newTransformer();
    if (prettyPrint) {
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        doc.getDocumentElement().normalize();
        XPathExpression xpath = XPathFactory.newInstance().newXPath()
                .compile("//text()[normalize-space(.) = '']");
        NodeList blankTextNodes = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < blankTextNodes.getLength(); i++) {
            blankTextNodes.item(i).getParentNode().removeChild(blankTextNodes.item(i));
        }//from  w ww  . java 2  s .  com
    }
    final DOMSource source = new DOMSource(doc);

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final StreamResult result = new StreamResult(out);
    transformer.transform(source, result);
    return out.toByteArray();
}

From source file:com.wso2telco.identity.application.authentication.endpoint.util.ReadMobileConnectConfig.java

public static Map<String, String> query(String XpathExpression) {

    Map<String, String> ConfigfileAttributes = new Hashtable<String, String>();

    // standard for reading an XML file
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from  w  w  w.j a va2  s .co m
    DocumentBuilder builder;
    Document doc = null;
    XPathExpression expr = null;
    try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse(CarbonUtils.getCarbonConfigDirPath() + File.separator + "mobile-connect.xml");

        // create an XPathFactory
        XPathFactory xFactory = XPathFactory.newInstance();

        // create an XPath object
        XPath xpath = xFactory.newXPath();

        // compile the XPath expression
        expr = xpath.compile("//" + XpathExpression + "/*");
        // run the query and get a nodeset
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        //        // cast the result to a DOM NodeList
        NodeList nodes = (NodeList) result;

        for (int i = 0; i < nodes.getLength(); i++) {
            ConfigfileAttributes.put(nodes.item(i).getNodeName(), nodes.item(i).getTextContent());
        }
    } catch (SAXException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage());
    } catch (XPathExpressionException e) {
        log.error(e.getMessage());
    }

    return ConfigfileAttributes;
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParser.java

private static Object resolveValueOverXPath(Node xmlDoc, XPathExpression expr, AtomicBoolean formattingNeeded)
        throws XPathExpressionException {
    Object val = null;
    NodeList nodes = null;/*w w w  . ja  v  a2s  .  co m*/
    try {
        nodes = (NodeList) expr.evaluate(xmlDoc, XPathConstants.NODESET);
    } catch (XPathException exc) {
        val = expr.evaluate(xmlDoc);
    }

    int length = nodes == null ? 0 : nodes.getLength();

    if (length > 0) {
        List<Object> valuesList = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            Node node = nodes.item(i);
            valuesList.add(node);
        }

        val = Utils.simplifyValue(valuesList);
        formattingNeeded.set(false);
    }

    return val;
}