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:org.dawb.passerelle.common.utils.XMLUtils.java

public static Map<String, String> getVariables(final Map<?, ?> variables, final String xmlSource,
        final Map<String, String> scalarSource) throws Exception {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(false); // never forget this!
    docFactory.setValidating(false);/*from w w w  .j a  v a2  s  . c om*/
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = null;

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

    final Map<String, String> values = new HashMap<String, String>(variables.size());
    for (Object varName : variables.keySet()) {
        final String varValue = (String) variables.get(varName.toString());
        if (varValue == null || "".equals(varValue)) {
            values.put(varName.toString(), scalarSource.get(varName));
            continue;
        }

        if ("/".equals(varValue)) {
            values.put(varName.toString(), xmlSource);
            continue;
        }

        final XPathExpression exp = xpath.compile(varValue);
        if (doc == null)
            doc = builder.parse(new InputSource(new StringReader(xmlSource)));

        final NodeList nodeList = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
        values.put(varName.toString(), getNodeValue(nodeList));
    }

    // We allow names of variables to expand values of other variables.
    final Map<String, String> all = new HashMap<String, String>(values.size());
    all.putAll(scalarSource);
    all.putAll(values);

    final Map<String, String> ret = new HashMap<String, String>(variables.size());
    final MultiVariableExpander expander = new MultiVariableExpander();
    expander.addSource("$", all);

    // Create a substitutor with the expander
    final VariableSubstitutor substitutor = new VariableSubstitutor(expander);

    for (final String varName : values.keySet()) {

        if (!varName.contains("$")) {
            ret.put(varName, values.get(varName));
        } else {
            ret.put(substitutor.substitute(varName), values.get(varName));
        }
    }

    return ret;
}

From source file:org.dawb.passerelle.common.utils.XMLUtils.java

public static String getXPathValue(IFile file, String xPath) throws Exception {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(false); // never forget this!
    docFactory.setValidating(false);/*  ww  w  .  j a  v a 2 s  .  c  o m*/
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    final XPathExpression exp = xpath.compile(xPath);

    Document doc = builder.parse(new InputSource(file.getContents()));

    final NodeList nodeList = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    return XMLUtils.getNodeValue(nodeList);
}

From source file:org.dawb.passerelle.common.utils.XMLUtils.java

public static String getXPathValue(File file, String xPath) throws Exception {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(false); // never forget this!
    docFactory.setValidating(false);/*  ww w .ja v a 2 s . c  o  m*/
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    final XPathExpression exp = xpath.compile(xPath);

    Document doc = builder.parse(new InputSource(file.getAbsolutePath()));

    final NodeList nodeList = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    return XMLUtils.getNodeValue(nodeList);
}

From source file:org.directwebremoting.drapgen.generate.gi.GiType.java

/**
 * Find implementing functions//  ww  w.j a v  a  2s  .com
 *   <method access="public" id="method:setEnabled" name="setEnabled">...
 * @param name A method name to find in the input document
 * @return the node that matches the given name
 */
public GiMethod getImplementationDeclaration(String name) {
    try {
        XPathExpression implementationFinder = xpath.compile("//method[@name='" + name + "']");
        return new GiMethod((Element) implementationFinder.evaluate(document, XPathConstants.NODE),
                getClassName());
    } catch (XPathExpressionException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.dita.dost.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {/* w w w .  ja va2 s. c o m*/

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        factory.setValidating(false);

        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
    } catch (ParserConfigurationException e) {
    } catch (SAXException e) {
    } catch (IOException e) {
    } catch (XPathExpressionException e) {
    }
    return fileName.toString();
}

From source file:org.dita2indesign.indesign.builders.InDesignFromDitaMapBuilder.java

private void addTopicsToDocument(InDesignDocument inDesignDoc, Document mapDoc, Map2InDesignOptions options)
        throws Exception {
    if (log.isDebugEnabled())
        log.debug("addArticlesToDocument(): Starting...");

    // FIXME: These next lines should be handled by XmlApiManager. Can't use XmlConstants because
    //        it uses RSIConstants, which requires a real RSuite instance (don't ask).
    XPath xpath = getXPathFactory().newXPath();
    XPathExpression topicrefExpression = xpath
            .compile("//*[contains(@class, ' map/topicref ') and @href != '']");

    // Per Saxon docs, when source is a DOM, result of NODESET is a NodeList.
    NodeList topicrefs = (NodeList) topicrefExpression.evaluate(new DOMSource(mapDoc), XPathConstants.NODESET);

    // NOTE: This code assumes chunking has already been applied to the map so that any topicrefs are to
    // top-level topics.

    Spread spread = inDesignDoc.getSpread(0);

    if (log.isDebugEnabled())
        log.debug("addTopicsToDocument(): Found " + topicrefs.getLength() + " articles in content assembly.");
    double yTop = -260.0;
    double height = 120.0;
    // These values are determined by trial and error.
    // Probably a more elegant way to calculate this geometry:
    double xTranslate = -760.0;
    double yTranslate = -156.0;
    double yGap = 24.0;
    double xGap = 24.0;
    double width = 280.0; // Width of an article frame.
    int row = 0;//from   w w w . j a va2s. com
    Page page = spread.getEvenPage(); // Should get only page of the spread.
    if (page == null) {
        page = spread.getOddPage();
    }
    int rowCount = 6;

    for (int i = 0; i < topicrefs.getLength(); i++) {
        Element elem = (Element) topicrefs.item(i);
        if (log.isDebugEnabled())
            log.debug(
                    "addArticlesToDocument(): Topic [" + (i + 1) + "], \"" + elem.getAttribute("href") + "\"");

        // FIXME: Need to handle non-XML topicrefs
        Link link = constructLinkForTopicref(inDesignDoc, elem, options);

        Rectangle frame;
        //         if (mo.isNonXml()) {
        //            continue; // For now, just skip non-XML MOs until we get image creation implemented.
        //            // frame = createFrameForNonXmlMo(inDesignDoc, link);
        //         } else {
        frame = createFrameForArticle(inDesignDoc, elem, link);
        //         }

        frame.getGeometry().getBoundingBox().setCorners(-140, yTop, 140, (yTop + height));
        frame.getGeometry().getTransformationMatrix().setXTranslation(xTranslate);
        frame.getGeometry().getTransformationMatrix().setYTranslation(yTranslate + ((height + yGap) * row));

        spread.addRectangle(frame);
        row++;
        // This ensures all the articles stay in the first-page's pasteboard
        if (i > 0 && (i + 1) % rowCount == 0) {
            xTranslate += (width + xGap);
            row = 0;
        }

        if (i > 0 && (i + 1) % (rowCount * 2) == 0) {
            xTranslate += page.getWidth() + xGap / 2;
        }

    }
}

From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

@Test
public void testIncrementalCompilation() {
    try {/*from  w  w  w.j  av  a  2s  .c o m*/

        OntoModel diamond = factory.buildModel("diamondX",
                ResourceFactory.newClassPathResource("ontologies/diamondProp.manchester.owl"),
                DLFactoryConfiguration.newConfiguration(OntoModel.Mode.OPTIMIZED));

        compiler = new OntoModelCompiler(diamond, folder.getRoot());

        List<Diagnostic<? extends JavaFileObject>> diag1 = compiler
                .compileOnTheFly(OntoModelCompiler.minimalOptions, OntoModelCompiler.MOJO_VARIANTS.JPA2);

        for (Diagnostic<?> dx : diag1) {
            System.out.println(dx);
            assertFalse(dx.getKind() == Diagnostic.Kind.ERROR);
        }

        showDirContent(folder);

        ClassLoader urlKL = new URLClassLoader(new URL[] { compiler.getBinDir().toURI().toURL() },
                Thread.currentThread().getContextClassLoader());

        OntoModel results = factory.buildModel("diamondInc",
                ResourceFactory.newClassPathResource("ontologies/dependency.test.owl"),
                DLFactoryConfiguration.newConfiguration(OntoModel.Mode.OPTIMIZED), urlKL);

        System.out.println(results);

        Class bot = Class.forName("org.jboss.drools.semantics.diamond.BottomImpl", true, urlKL);
        Class botIF = Class.forName("org.jboss.drools.semantics.diamond.Bottom", true, urlKL);
        Assert.assertNotNull(bot);
        Assert.assertNotNull(botIF);
        Object botInst = bot.newInstance();
        Assert.assertNotNull(botInst);

        OntoModelCompiler compiler2 = new OntoModelCompiler(results, folder.getRoot());

        compiler2.fixResolvedClasses();

        compiler2.streamJavaInterfaces(false);
        compiler2.streamXSDsWithBindings(true);

        compiler2.mojo(OntoModelCompiler.defaultOptions, OntoModelCompiler.MOJO_VARIANTS.JPA2);

        showDirContent(folder);

        File unImplBoundLeft = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left.java");
        assertFalse(unImplBoundLeft.exists());
        File implBoundLeft = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "LeftImpl.java");
        assertTrue(implBoundLeft.exists());

        File leftInterface = new File(compiler2.getJavaDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left.java");

        assertTrue(leftInterface.exists());

        List<Diagnostic<? extends JavaFileObject>> diagnostics = compiler2.doCompile();

        for (Diagnostic<?> dx : diagnostics) {
            System.out.println(dx);
            assertFalse(dx.getKind() == Diagnostic.Kind.ERROR);
        }

        showDirContent(folder);

        Document dox = parseXML(new File(compiler2.getBinDir().getPath() + "/META-INF/persistence.xml"), false);
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile("//persistence-unit/@name");
        assertEquals("diamondX", (String) expr.evaluate(dox, XPathConstants.STRING));

        File YInterface = new File(compiler2.getJavaDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "X.java");
        assertTrue(YInterface.exists());

        Class colf = Class.forName("some.dependency.test.ChildOfLeftImpl", true, urlKL);
        Assert.assertNotNull(colf);
        Object colfInst = colf.newInstance();

        List<String> hierarchy = getHierarchy(colf);
        assertTrue(hierarchy.contains("some.dependency.test.ChildOfLeftImpl"));
        assertTrue(hierarchy.contains("some.dependency.test.org.jboss.drools.semantics.diamond.LeftImpl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.LeftImpl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.C0Impl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.TopImpl"));
        assertTrue(hierarchy.contains("org.w3._2002._07.owl.ThingImpl"));

        Set<String> itfHierarchy = getIFHierarchy(colf);

        System.err.println(itfHierarchy.containsAll(
                Arrays.asList("org.jboss.drools.semantics.diamond.C1", "org.jboss.drools.semantics.diamond.C0",
                        "some.dependency.test.org.jboss.drools.semantics.diamond.Left",
                        "some.dependency.test.ChildOfLeft", "org.jboss.drools.semantics.diamond.Left",
                        "org.jboss.drools.semantics.diamond.Top", "com.clarkparsia.empire.EmpireGenerated",
                        "org.w3._2002._07.owl.Thing", "java.io.Serializable", "org.drools.semantics.Thing",
                        "com.clarkparsia.empire.SupportsRdfId")));

        Method getter1 = colf.getMethod("getAnotherLeftProp");
        assertNotNull(getter1);
        Method getter2 = colf.getMethod("getImportantProp");
        assertNotNull(getter2);

        for (Method m : colf.getMethods()) {
            if (m.getName().equals("addImportantProp")) {
                m.getName();
            }
        }

        Method adder = colf.getMethod("addImportantProp", botIF);
        assertNotNull(adder);
        adder.invoke(colfInst, botInst);
        List l = (List) getter2.invoke(colfInst);
        assertEquals(1, l.size());

        File off = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left_Off.java");
        assertFalse(off.exists());

        testPersistenceWithInstance(urlKL, "org.jboss.drools.semantics.diamond.Bottom", diamond.getName());
        System.out.println(" Done");

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

}

From source file:org.drugis.addis.util.ConvertDiabetesDatasetUtil.java

private void renameStudies() throws IOException {
    for (Study study : d_domain.getStudies()) {
        PubMedIdList pubmed = (PubMedIdList) study.getCharacteristic(BasicStudyCharacteristic.PUBMED);

        try {//www .jav a 2  s .  c  o  m
            Document doc = getPubMedXML(pubmed);

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

            XPathExpression yearExpr = xpath
                    .compile("/PubmedArticleSet/PubmedArticle[1]/MedlineCitation[1]/DateCreated[1]/Year[1]");
            Object yearResults = yearExpr.evaluate(doc, XPathConstants.NODESET);

            String year = ((NodeList) yearResults).item(0).getTextContent();

            XPathExpression authorExpr = xpath.compile(
                    "/PubmedArticleSet/PubmedArticle[1]/MedlineCitation[1]/Article[1]/AuthorList[1]/Author/LastName");
            Object authorResults = authorExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList authorNodes = (NodeList) authorResults;

            List<String> authors = new ArrayList<String>();

            for (int i = 0; i < authorNodes.getLength(); i++) {
                authors.add(authorNodes.item(i).getTextContent());
            }
            String title = "";
            if (authors.size() > 2) {
                title = authors.get(0) + " et al, " + year;
            } else {
                title = StringUtils.join(authors, ", ") + ", " + year;
            }
            study.setName(title);

        } catch (Exception e) {
            continue;
        }
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.asset.UsageCaseXmlTests.java

private Node getBestAsset(Document document) throws XPathExpressionException {

    String getAssets = "/rdf:RDF/oslc_asset:Asset";
    XPath xPath = OSLCUtils.getXPath();
    XPathExpression assetsExpr = xPath.compile(getAssets);
    NodeList assets = (NodeList) assetsExpr.evaluate(document, XPathConstants.NODESET);

    Node bestAsset = null;//from w  w  w.  j  ava 2 s.c  o m
    String highestVersion = "";
    for (int i = 0; i < assets.getLength(); i++) {
        NodeList nodeKids = assets.item(i).getChildNodes();
        for (int j = 0; j < nodeKids.getLength(); j++) {
            Node node = nodeKids.item(j);
            if (node.getNodeName().equals("oslc_asset:version")) {
                String version = node.getTextContent();
                if (version.compareTo(highestVersion) > 0) {
                    highestVersion = version;
                    bestAsset = assets.item(i);
                }
                break;
            }
        }
    }
    return bestAsset;
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {//from  w  w  w  .  j  a v a  2s.c  o  m

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        factory.setValidating(false);

        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println();
    }
    return fileName.toString();
}