Example usage for javax.xml.xpath XPath compile

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

Introduction

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

Prototype

public XPathExpression compile(String expression) throws XPathExpressionException;

Source Link

Document

Compile an XPath expression for later evaluation.

Usage

From source file:Main.java

private static XPathExpression createXPathExpression(String expression, NamespaceContext namespaceContext)
        throws XPathExpressionException {
    XPath xpath = getFactory().newXPath();
    if (namespaceContext != null) {
        xpath.setNamespaceContext(namespaceContext);
    }/* ww w  .  j a va2s. c o  m*/
    XPathExpression expr = xpath.compile(expression);
    return expr;
}

From source file:com.github.robozonky.app.version.UpdateMonitor.java

/**
 * Parse XML using XPath and retrieve the version string.
 * @param xml XML in question./*from  w w  w.j  a  va  2  s  .c o  m*/
 * @return The version string.
 * @throws ParserConfigurationException Failed parsing XML.
 * @throws IOException Failed I/O.
 * @throws SAXException Failed reading XML.
 * @throws XPathExpressionException XPath parsing problem.
 */
private static VersionIdentifier parseVersionString(final InputStream xml)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    final DocumentBuilderFactory factory = XmlUtil.getDocumentBuilderFactory();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.parse(xml);
    final XPathFactory xPathfactory = XPathFactory.newInstance();
    final XPath xpath = xPathfactory.newXPath();
    final XPathExpression expr = xpath.compile("/metadata/versioning/versions/version");
    return UpdateMonitor.parseNodeList((NodeList) expr.evaluate(doc, XPathConstants.NODESET));
}

From source file:Main.java

/**
 * Locates the element defined by the XPath expression in the XML file and replaces the child text with the passed value.
 * @param fileName The XML file to update.
 * @param xPathExpression An XPath expression that locates the element to update.
 * @param value The value to update the attribute to.
 *//*www . j  a  va  2  s  . c o m*/
public static void updateElementValueInXMLFile(String fileName, String xPathExpression, String value) {
    try {
        Document document = parseXML(new File(fileName));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression xpathExpression = xpath.compile(xPathExpression);
        Element element = (Element) xpathExpression.evaluate(document, NODE);
        element.getFirstChild().setNodeValue(value);
        writeElement(document.getDocumentElement(), fileName);
    } catch (Exception e) {
        throw new RuntimeException("Failed to extract element from:" + fileName, e);
    }
}

From source file:Main.java

/**
 * Locates the attribute defined by the XPath expression in the XML file and replaces it with the passed value.
 * @param fileName The XML file to update.
 * @param xPathExpression An XPath expression that locates the attribute to update.
 * @param attributeName The name of the attribute to update.
 * @param value The value to update the attribute to.
 *//*from  w ww .  j av a 2 s  .  c om*/
public static void updateAttributeInXMLFile(String fileName, String xPathExpression, String attributeName,
        String value) {
    try {
        Document document = parseXML(new File(fileName));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression xpathExpression = xpath.compile(xPathExpression);
        Element element = (Element) xpathExpression.evaluate(document, NODE);

        element.getAttributeNode(attributeName).setValue(value);
        writeElement(document.getDocumentElement(), fileName);

    } catch (Exception e) {
        throw new RuntimeException("Failed to extract element from:" + fileName, e);
    }
}

From source file:Main.java

/**
 * Returns the string value of the named attribute in an XML file at the coordinates specified by the passed XPath expression 
 * @param fileName The file name/*from   w w  w  .j a va 2s.c o  m*/
 * @param xPathExpression The XPath expression
 * @param attributeName The attribute name
 * @return the attribute valye
 */
public static String getAttribute(String fileName, String xPathExpression, String attributeName) {
    try {
        Document document = parseXML(new File(fileName));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression xpathExpression = xpath.compile(xPathExpression);
        Node node = (Node) xpathExpression.evaluate(document, NODE);
        return getAttributeValueByName(node, attributeName);
    } catch (Exception e) {
        throw new RuntimeException("Failed to extract element from:" + fileName, e);
    }
}

From source file:com.ephesoft.dcma.util.OCREngineUtil.java

/**
 * To format HOCR for Tesseract.//from www. ja  v  a2  s  . c om
 * @param outputFilePath {@link String}
 * @param actualFolderLocation  {@link String}
 * @param pageId {@link String}
 * @throws XPathExpressionException if error occurs
 * @throws TransformerException if error occurs
 * @throws IOException if error occurs
 */
public static void formatHOCRForTesseract(final String outputFilePath, final String actualFolderLocation,
        final String pageId) throws XPathExpressionException, TransformerException, IOException {
    LOGGER.info("Entering format HOCR for tessearct . outputfilepath : " + outputFilePath);
    InputStream inputStream = new FileInputStream(outputFilePath);
    XPathFactory xFactory = new org.apache.xpath.jaxp.XPathFactoryImpl();
    XPath xpath = xFactory.newXPath();
    XPathExpression pageExpr = xpath.compile("//div[@class=\"ocr_page\"]");
    XPathExpression wordExpr = xpath.compile("//span[@class=\"ocr_word\"]");

    // Output format supported by Tesseract 3.00
    XPathExpression xOcrWordExpr = xpath.compile("//span[@class=\"xocr_word\"]");

    // Output format supported by Tesseract 3.01
    XPathExpression ocrXWordExpr = xpath.compile("//span[@class=\"ocrx_word\"]");

    org.w3c.dom.Document doc2 = null;
    try {
        doc2 = XMLUtil.createDocumentFrom(inputStream);
    } catch (Exception e) {
        LOGGER.info("Premature end of file for " + outputFilePath + e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    if (doc2 != null) {
        LOGGER.info("document is not null.");
        NodeList wordList = (NodeList) wordExpr.evaluate(doc2, XPathConstants.NODESET);
        for (int wordNodeIndex = 0; wordNodeIndex < wordList.getLength(); wordNodeIndex++) {
            setWordNodeTextContent(xOcrWordExpr, ocrXWordExpr, wordList, wordNodeIndex);
        }

        NodeList pageList = (NodeList) pageExpr.evaluate(doc2, XPathConstants.NODESET);
        for (int pageNodeIndex = 0; pageNodeIndex < pageList.getLength(); pageNodeIndex++) {
            Node pageNode = pageList.item(pageNodeIndex);
            if (pageNode != null
                    && ((Node) pageNode.getAttributes().getNamedItem(UtilConstants.ID_ATTR)) != null) {
                String pageID = ((Node) pageNode.getAttributes().getNamedItem(UtilConstants.ID_ATTR))
                        .getTextContent();
                wordExpr = xpath.compile("//div[@id='" + pageID + "']//span[@class='ocr_word']");
                NodeList wordInPageList = (NodeList) wordExpr.evaluate(pageNode, XPathConstants.NODESET);

                Node pageNodeClone = pageNode.cloneNode(false);
                for (int i = 0; i < wordInPageList.getLength(); i++) {
                    pageNodeClone.appendChild(wordInPageList.item(i));
                }
                pageNode.getParentNode().appendChild(pageNodeClone);
                pageNode.getParentNode().removeChild(pageNode);
            }
        }

        XMLUtil.flushDocumentToFile(doc2.getDocumentElement().getOwnerDocument(), outputFilePath);
        File tempFile = new File(actualFolderLocation + File.separator + pageId + "_tempFile_hocr.html");
        FileUtils.copyFile(new File(outputFilePath), tempFile);

        XMLUtil.htmlOutputStream(tempFile.getAbsolutePath(), outputFilePath);
        boolean isTempFileDeleted = tempFile.delete();
        if (!isTempFileDeleted) {
            tempFile.delete();
        }
    }
    LOGGER.info("Exiting format HOCR for tessearct . outputfilepath : " + outputFilePath);
}

From source file:org.opencastproject.remotetest.util.Utils.java

public static Object xpath(InputStream is, String path, QName returnType) throws XPathExpressionException {
    try {//from   w  w w.j  av a 2 s.co m
        XPath xPath = XPathFactory.newInstance().newXPath();
        return xPath.compile(path).evaluate(is, returnType);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java

public static void configurePackage(String env, File configFile) throws Exception {
    Transformer transformer = tltf.get();

    // get the list of files in proxies folder
    XMLFileListUtil listFileUtil = new XMLFileListUtil();

    ConfigTokens conf = FileReader.getBundleConfigs(configFile);

    Map<String, List<File>> filesToProcess = new HashMap<String, List<File>>();
    filesToProcess.put("proxy", listFileUtil.getProxyFiles(configFile));
    filesToProcess.put("policy", listFileUtil.getPolicyFiles(configFile));
    filesToProcess.put("target", listFileUtil.getTargetFiles(configFile));

    doTokenReplacement(env, conf, filesToProcess);

    // special case ...
    File proxyFile = listFileUtil.getAPIProxyFiles(configFile).get(0);
    Document xmlDoc = FileReader.getXMLDocument(proxyFile); // there would be only one file, at least one file

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expression = xpath.compile("/APIProxy/Description");

    NodeList nodes = (NodeList) expression.evaluate(xmlDoc, XPathConstants.NODESET);
    if (nodes.item(0).hasChildNodes()) {
        // sets the description to whatever is in the <proxyname>.xml file
        nodes.item(0).setTextContent(expression.evaluate(xmlDoc));
    } else {//from  ww w .java  2 s  . c om
        // if Description is empty, then it reverts back to appending the username, git hash, etc
        nodes.item(0).setTextContent(getComment(proxyFile));
    }

    DOMSource source = new DOMSource(xmlDoc);
    StreamResult result = new StreamResult(proxyFile);
    transformer.transform(source, result);
}

From source file:com.thinkbiganalytics.feedmgr.nifi.NifiTemplateParser.java

public static String updateTemplateName(String nifiTemplate, String newName) throws Exception {

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    Document doc = stringToDocument(nifiTemplate);

    InputSource source = new InputSource(new StringReader(nifiTemplate));

    Element element = (Element) xpath.compile("//template/name").evaluate(doc, XPathConstants.NODE);

    element.setTextContent(newName);//  w ww .j  av  a  2s  .c om
    return documentToString(doc);
}

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

private static void perform(String arg, CommandLine line) throws IOException {
    URL url;//  www.  j a v a 2 s . co 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);
    }
}