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:com.photon.phresco.impl.WindowsApplicationProcessor.java

private static void deleteFeature(File sourceFolderLocation, List<ArtifactGroup> deletedFeatures)
        throws PhrescoException {
    try {/*ww  w  .jav a 2 s .co  m*/
        File path = new File(sourceFolderLocation + File.separator + SOURCE_DIR + File.separator + SRC_DIR
                + File.separator + PROJECT_ROOT + File.separator + PROJECT_ROOT + CSPROJ_FILE);
        if (!path.exists() && CollectionUtils.isNotEmpty(deletedFeatures)) {
            return;
        }
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(false);
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(path);
        for (ArtifactGroup deleteFeature : deletedFeatures) {
            String feature = deleteFeature.getName();
            feature = "//Reference[@Include='" + feature + "']";
            XPath xpath = XPathFactory.newInstance().newXPath();
            javax.xml.xpath.XPathExpression expr = xpath.compile(feature);
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                Node item = nodes.item(i).getParentNode();
                item.getParentNode().removeChild(item);
            }
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(path.toURI().getPath());
        transformer.transform(source, result);

    } catch (XPathExpressionException e) {
        throw new PhrescoException(e);
    } catch (DOMException e) {
        throw new PhrescoException(e);
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (SAXException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (TransformerConfigurationException e) {
        throw new PhrescoException(e);
    } catch (TransformerException e) {
        throw new PhrescoException(e);
    }
}

From source file:kevin.gvmsgarch.App.java

static String extractInboxJson(String authToken, Worker.ListLocation location, int page)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    String pageData = "";
    try {//from  w  ww.  j a v a2s . com
        pageData = App.getInboxPage(authToken, location, page);
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(pageData.getBytes()));
        XPathExpression xpr = XPathFactory.newInstance().newXPath().compile("/response/json");
        NodeList nl = (NodeList) xpr.evaluate(doc, XPathConstants.NODESET);
        Node n = nl.item(0);
        return n.getTextContent();
    } catch (Exception ex) {
        throw new RuntimeException("Page data for error:\n\n" + pageData + "\n\n", ex);
    }
}

From source file:Main.java

public static Element[] getElements(Element parent, String expression) {

    boolean isSimple = true;
    for (int i = 0; i < expression.length(); i++) {
        if (!Character.isAlphabetic(expression.charAt(i))) {
            isSimple = false;//from  www .jav a  2 s.  c o  m
            break;
        }
    }

    if (isSimple) {
        return getDirectElements(parent, expression);
    } else {
        try {
            XPathExpression xquery;
            if (cache.containsKey(expression)) {
                xquery = cache.get(expression);
            } else {
                xquery = xpath.compile(expression);
                cache.put(expression, xquery);
            }

            return itemsOf((NodeList) xquery.evaluate(parent, XPathConstants.NODESET));
        } catch (XPathExpressionException ex) {
            return null;
        }
    }
}

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

private static void setWordNodeTextContent(XPathExpression xOcrWordExpr, XPathExpression ocrXWordExpr,
        NodeList wordList, int wordNodeIndex) throws XPathExpressionException {
    Node wordNode = wordList.item(wordNodeIndex);
    if (wordNode != null) {
        Node word = (Node) xOcrWordExpr.evaluate(wordNode, XPathConstants.NODE);
        if (word != null) {
            wordNode.setTextContent(word.getTextContent());
        } else {/*from w  w w  .  jav  a 2 s .c  o m*/
            word = (Node) ocrXWordExpr.evaluate(wordNode, XPathConstants.NODE);
            if (word != null) {
                wordNode.setTextContent(word.getTextContent());
            }
        }
    }
}

From source file:com.jaeksoft.searchlib.util.XPathParser.java

final public static Object evaluate(final Node parentNode, final XPathExpression xPathExpression)
        throws XPathExpressionException {
    XPathExpressionException lastError = null;
    for (QName qname : RETURN_TYPES) {
        try {/*  www  . jav a  2  s . co m*/
            Object result = xPathExpression.evaluate(parentNode, qname);
            if (result != null)
                return result;
        } catch (XPathExpressionException e) {
            lastError = e;
        }
    }
    if (lastError != null)
        throw lastError;
    return null;
}

From source file:com.impetus.ankush.common.utils.NmapUtil.java

/**
 * @throws ParserConfigurationException//from   ww  w  . java 2 s  .  c  om
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
private static Map<String, String> getHostIPMapping(String filePath)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    // loading the XML document from a file
    DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
    builderfactory.setNamespaceAware(true);

    DocumentBuilder builder = builderfactory.newDocumentBuilder();
    File file = new File(filePath);
    Document xmlDocument = builder.parse(file);

    XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    XPath xPath = factory.newXPath();

    // getting the name of the book having an isbn number == ABCD7327923
    XPathExpression hostXpath = xPath.compile("//host");

    XPathExpression ipXpath = xPath.compile("address[@addrtype='ipv4']/@addr");

    XPathExpression hostNameXpath = xPath.compile("hostnames/hostname[@type='user']/@name");

    NodeList nodeListHost = (NodeList) hostXpath.evaluate(xmlDocument, XPathConstants.NODESET);

    Map<String, String> hostIpMapping = new HashMap<String, String>();
    for (int index = 0; index < nodeListHost.getLength(); index++) {
        String ip = (String) ipXpath.evaluate(nodeListHost.item(index), XPathConstants.STRING);
        String host = (String) hostNameXpath.evaluate(nodeListHost.item(index), XPathConstants.STRING);

        hostIpMapping.put(host, ip);

    }
    // deleting the temporary xml file.
    FileUtils.deleteQuietly(file);
    return hostIpMapping;
}

From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java

private static void setPropertyValue(Document document, String propertyName, String value)
        throws XPathExpressionException {
    XPathExpression compile = pathFactory
            .compile("hibernate-configuration/session-factory/property[@name='" + propertyName + "']"); //$NON-NLS-1$ //$NON-NLS-2$
    Node node = (Node) compile.evaluate(document, XPathConstants.NODE);
    if (node != null) {
        node.setTextContent(value);//ww  w  .j  av a2 s  .c  om
    } else {
        XPathExpression parentNodeExpression = pathFactory.compile("hibernate-configuration/session-factory"); //$NON-NLS-1$
        Node parentNode = (Node) parentNodeExpression.evaluate(document, XPathConstants.NODE);
        // Create a new property element for this datasource-specified property (TMDM-4927).
        Element property = document.createElement("property"); //$NON-NLS-1$
        Attr propertyNameAttribute = document.createAttribute("name"); //$NON-NLS-1$
        property.setAttributeNode(propertyNameAttribute);
        propertyNameAttribute.setValue(propertyName);
        property.setTextContent(value);
        parentNode.appendChild(property);
    }
}

From source file:org.jboss.seam.forge.shell.util.PluginUtil.java

public static File downloadPlugin(final PluginRef ref, final PipeOut out, final String targetPath)
        throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();

    String[] artifactParts = ref.getArtifact().split(":");

    if (artifactParts.length != 3) {
        throw new RuntimeException("malformed artifact identifier "
                + "(format should be: <maven.group>:<maven.artifact>:<maven.version>) encountered: "
                + ref.getArtifact());//from ww w  .j  a  v a2  s  .co m
    }

    String packageLocation = artifactParts[0].replaceAll("\\.", "/");
    String baseUrl;
    if (ref.getHomeRepo().endsWith("/")) {
        baseUrl = ref.getHomeRepo() + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    } else {
        baseUrl = ref.getHomeRepo() + "/" + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    }

    HttpGet httpGetManifest = new HttpGet(baseUrl + "/maven-metadata.xml");
    out.print("Retrieving artifact manifest ... ");

    HttpResponse response = client.execute(httpGetManifest);
    switch (response.getStatusLine().getStatusCode()) {
    case 200:
        out.println("done.");

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getEntity().getContent());

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression checkSnapshotExpr = xpath.compile("//versioning/snapshot");
        XPathExpression findJar = xpath.compile("//snapshotVersion[extension='jar']/value");

        NodeList list = (NodeList) checkSnapshotExpr.evaluate(document, XPathConstants.NODESET);

        out.print("Reading manifest ... ");

        if (list.getLength() != 0) {

            Node n = (Node) findJar.evaluate(document, XPathConstants.NODE);

            if (n == null) {
                out.println("failed: could not determine where to find jar file.");
                return null;
            }

            String version = n.getFirstChild().getTextContent();

            // plugin definition points to a snapshot.
            out.println("good! (maven snapshot found): " + version);

            String fileName = artifactParts[1] + "-" + version + ".jar";

            HttpGet jarGet = new HttpGet(baseUrl + "/" + fileName);

            out.print("Downloading: " + baseUrl + "/" + fileName + " ... ");
            response = client.execute(jarGet);

            try {
                File file = saveFile(targetPath + "/" + fileName, response.getEntity().getContent());
                out.println("done.");
                return file;
            } catch (IOException e) {
                out.println("failed to download: " + e.getMessage());
                return null;
            }

            // do download of snapshot.
        } else {
            out.println("error! (maven snapshot not found)");
            return null;
        }

    case 404:
        String requestUrl = baseUrl + "/" + artifactParts[2] + ".pom";
        httpGetManifest = new HttpGet(requestUrl);
        response = client.execute(httpGetManifest);

        if (response.getStatusLine().getStatusCode() != 200) {
            printError(response.getStatusLine().getStatusCode(), requestUrl, out);
            return null;
        } else {

            // download regular POM here.

        }
        break;
    default:
        out.println("failed! (server returned status code: " + response.getStatusLine().getStatusCode());
        return null;
    }

    return null;

}

From source file:gov.nih.nci.lmp.mimGpml.CommonHelper.java

/**
 * Gets the MIM-Vis XML object by ID./*from   w  w w . j  av  a 2 s .  c  o m*/
 * 
 * TODO: It does not appear possible to use the Saxon engine to process
 * XPath queries within Pathvisio; the plugin fails to load. The approach
 * taken instead relies on JDOM/Jaxen to process XPath.
 * 
 * @param doc
 *            the doc
 * @param elemId
 *            the element id
 * @return the vis xml object by id
 */
public static XmlObject getVisXmlObjectById(DiagramDocument doc, String elemId) {

    // TODO: Account for bioId
    // String queryExpression =
    // "/mimVis:Diagram/mimVis:InteractionGlyph[@visId='" + elemId + "']";
    String queryExpression = "//*[@visId='" + elemId + "']";

    Logger.log.debug("elemId:" + elemId);
    Logger.log.debug("queryExpression:" + queryExpression);

    try {
        org.w3c.dom.Document wDoc = (org.w3c.dom.Document) doc.getDomNode();
        javax.xml.xpath.XPathFactory factory = XPathFactory.newInstance();
        javax.xml.xpath.XPath wXpath = factory.newXPath();
        javax.xml.xpath.XPathExpression expr = wXpath.compile(queryExpression);

        Object result = expr.evaluate(wDoc, javax.xml.xpath.XPathConstants.NODESET);
        org.w3c.dom.NodeList nodes = (org.w3c.dom.NodeList) result;

        Logger.log.debug("NodeList size: " + nodes.getLength());

        /**
         * If the size is not one, then there is a duplicate key issue that
         * needs to be dealt with. Treat it as an error and return null.
         */
        if (nodes.getLength() == 1) {
            XmlObject xmlObj = XmlObject.Factory.parse(nodes.item(0));
            Logger.log.debug("glyph.xmlText: " + xmlObj.xmlText(getXmlOptions()));

            // Logger.log.debug("doc.xmlText: " +
            // doc.xmlText(getXmlOptions()));

            String elemStr = xmlObj.xmlText(getXmlOptions());

            Logger.log.debug("getVisXmlObjectById XML String:" + elemStr);

            /**
             * Sample of the way an XML fragment is represented with
             * <xml-fragment> tags. This necessitates a modification from
             * the nodes returned by selectNodes.
             * 
             * <xml-fragment mimVis:visId="ca53d" mimVis:displayName="CAMK"
             * centerX="166.0" centerY="167.0" mimVis:width="80.0"
             * mimVis:height="20.0"
             * xmlns:mimVis="http://lmp.nci.nih.gov/mim/mimVisLevel1">
             * <mimVis:mimBioRef>b9044</mimVis:mimBioRef></xml-fragment>
             */
            // Pattern/matcher
            Pattern mimStartElemTag = Pattern.compile("mimVis:[A-Z][A-Za-z]+");
            Matcher matcherStart = mimStartElemTag.matcher(elemStr);

            // System.out.println("matcherStart count: "
            // + matcherStart.groupCount());

            String match = null;

            // Find all matches
            while (matcherStart.find()) {
                // Get the matching string
                match = matcherStart.group();
                // System.out.println("matcherStart.group(): "
                // + matcherStart.group());
            }

            final int prefixLength = "mimVis:".length();

            // String localPart = xmlFrag + "Type";
            String localPart = match.substring(prefixLength) + "Type";

            // Match: mimVis:SimplePhysicalEntityGlyph
            // SPE URI QName: http://lmp.nci.nih.gov/mim/mimVisLevel1
            // SPE Local QName: SimplePhysicalEntityGlyphType

            QName objQName = new QName(MIM_VIS_NS, localPart);

            SchemaTypeLoader schemaTypeLoader = XmlBeans.getContextTypeLoader();
            SchemaType objType = schemaTypeLoader.findType(objQName);

            XmlOptions opts = new XmlOptions();
            opts.setLoadReplaceDocumentElement(null);

            /**
             * Taken from the XMLBeans autogenerated code of a XSD complex
             * type. For parsing a XML fragment given the SchemaType.
             */
            xmlObj = XmlBeans.getContextTypeLoader().parse(elemStr, objType, opts);

            return xmlObj;
        } else {
            Logger.log.info("ERROR: Most likely a duplicate ID.");
        }
    } catch (XmlException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.twentyn.patentExtractor.PatentDocument.java

/**
 * Extracts the text content from text fields in a patent XML document.
 *
 * @param docBuilder A document builder to use when constructing intermediate XML/HTML documents in the extraction
 *                   process.// www  .  j  a v  a 2  s.  co m
 * @param paths      A list of XPath paths from which to exactract text.
 * @param xpath      An XPath instance to use when running XPath queries.
 * @param doc        The XML document from which to extract text.
 * @return A list of strings representing the textual content of the document.  These could be sentences,
 * paragraphs, or larger text units, but should represent some sort of structure in the document's text.
 * @throws ParserConfigurationException
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws XPathExpressionException
 */
private static List<String> getRelevantDocumentText(DocumentBuilder docBuilder, String[] paths, XPath xpath,
        Document doc) throws ParserConfigurationException, TransformerConfigurationException,
        TransformerException, XPathExpressionException {
    List<String> allTextList = new ArrayList<>(0);
    for (String path : paths) {
        XPathExpression exp = xpath.compile(path);
        NodeList textNodes = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
        allTextList.addAll(extractTextFromHTML(docBuilder, textNodes));
    }

    return allTextList;
}