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.hyperic.hq.plugin.jboss7.JBossHostControllerDetector.java

@Override
void setUpExtraProductConfig(ConfigResponse cfg, Document doc) throws XPathException {
    XPathFactory factory = XPathFactory.newInstance();
    XPathExpression expr = factory.newXPath().compile(getConfigRoot());
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodeList = (NodeList) result;
    String name = nodeList.item(0).getAttributes().getNamedItem("name").getNodeValue();
    cfg.setValue(HOST, name);/*from ww w  .ja v a  2  s.  c  o m*/
}

From source file:org.hyperic.hq.plugin.jboss7.JBossManagedDetector.java

private List<String> getServersNames(String config) {
    List<String> names = new ArrayList<String>();
    File cfgFile = new File(config);

    try {/*from  www.j a  v  a  2s. co m*/
        log.debug("[getServerProductConfig] cfgFile=" + cfgFile.getCanonicalPath());
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = (Document) dBuilder.parse(cfgFile);

        XPathFactory factory = XPathFactory.newInstance();
        XPathExpression expr = factory.newXPath().compile("//host/servers/server");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodeList = (NodeList) result;

        for (int i = 0; i < nodeList.getLength(); i++) {
            names.add(nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue());
        }
    } catch (Exception ex) {
        log.debug("Error discovering the servers names : " + ex, ex);
    }
    return names;
}

From source file:org.iish.visualmets.services.TocDaoImp.java

/**
 * Selects child folders that directly fall under the parent folder
 * Each child folder includes all objects ( Mets documents ) that fall under those folders.
 *
 * @param eadId URL to TableOfContents XML file
 * @param group The identity of the parent folder
 * @return An arraylist of all child folders and their objects
 *///from   w ww .j a  v a 2s  .  c o m
@Override
public List<TocFolderItem> getEADFolders(String eadId, String group, int namespace) {

    if (namespace == 1) {
        namespaceName = "mets:";
    } else {
        namespaceName = "";
    }

    if (group.equals("0")) {
        group = "";
    }
    List<TocFolderItem> list = new ArrayList<TocFolderItem>();
    TocFolderItem folderItem = null;
    TocFolderItem folderItem2 = null;

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!

    DocumentBuilder builder = null;
    try {
        builder = domFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document doc = null;

    try {
        doc = builder.parse(eadId);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    XPathExpression expr = null;
    try {
        // als geen group pak dan root mets:div directory
        if (group.equals("")) {
            //                if ( namespaceName.equals("") ) {
            ////                    expr = xpath.compile("/mets/structMap");
            //                    expr = xpath.compile("/mets");
            //                } else {
            expr = getXPathExpression("/" + namespaceName + "mets/" + namespaceName + "structMap");
            //                expr = getXPathExpression("//" + namespaceName + "structMap");
            //                }
        } else {
            expr = getXPathExpression("/" + namespaceName + "mets/" + namespaceName + "structMap//"
                    + namespaceName + "div[@ID='" + group + "']");
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    //System.out.println(eadId);
    //System.out.println("/" + namespaceName + "mets/" + namespaceName + "structMap");
    Object result = null;
    try {
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    ArrayList<TocFolderItem> breadCrumbs = new ArrayList<TocFolderItem>();
    NodeList nodes = (NodeList) result;
    //System.out.println("Found: " + nodes.getLength());
    // use first found node
    if (nodes.getLength() > 0) {

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

        // try to find breadcrumbs
        breadCrumbs = findBreadCrumbs(breadCrumbs, nodes.item(i));

        // if found multiple breadcrumbs
        if (breadCrumbs.size() > 1) {
            // reverse order of found breadcrumbs (root parent als eerst, dan sub parent, dan sub sub parent)
            Collections.reverse(breadCrumbs);
        }

        // if there are breadcrumbs add to result list
        if (breadCrumbs.size() > 0) {
            folderItem = new TocFolderItem();
            folderItem.setBreadcrumbs(breadCrumbs);
            list.add(folderItem);
        }

        // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

        // try to find XML files in current directory
        folderItem2 = new TocFolderItem();

        // acherhaal alle xml files in huidige directory
        ArrayList<TocMetsItem> lijst = new ArrayList<TocMetsItem>();
        String nodeId = "";
        try {
            nodeId = nodes.item(i).getAttributes().getNamedItem("ID").getNodeValue();
        } catch (NullPointerException e) {
            nodeId = "";
        }
        System.out.println("ID: " + nodeId);
        lijst = getFilesRecursive(doc, lijst, nodeId, 0);

        for (TocMetsItem tocMetsItem : lijst) {
            folderItem2.addDocs(tocMetsItem);
        }

        list.add(folderItem2);

        // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

        // try to find subdirectories, if found, create for each one a mets folder item
        ArrayList<String> listOfSubDirectories = getArrayOfSubDirectories(nodes.item(i));
        if (listOfSubDirectories.size() > 0) {
            for (String id : listOfSubDirectories) {
                folderItem = createFolder(doc, id, 1); // recursive on
                //                    folderItem = createFolder(doc, id, 0); // recursive off
                //
                list.add(folderItem);
            }
        }

        // DEZE HELE IF BLOCK MOET EIGENLIJK WEG, DE FRONT END CODE MOET ANDERS
        //            if ( areThereSubs == 0 ) {
        //                folderItem = new TocFolderItem();
        //
        //                folderItem.setIndex(nodes.item(0).getAttributes().getNamedItem("ID").getNodeValue());
        //                folderItem.setTitle(nodes.item(0).getAttributes().getNamedItem("LABEL").getNodeValue());
        //                //folderItem.setTitle("---");
        //                // does node (directory) have subdirectories (also a node, but watch out, files are also nodes)
        //                folderItem.setHaschildren("false");
        //
        //
        //                // acherhaal alle xml files in huidige directory
        //                ArrayList<TocMetsItem> lijst3 = new ArrayList<TocMetsItem>();
        //                System.out.println("ID: " + nodes.item(0).getAttributes().getNamedItem("ID").getNodeValue());
        //                lijst3 = getFilesRecursive(doc, lijst3, nodes.item(0).getAttributes().getNamedItem("ID").getNodeValue(), 0);
        //
        //                for (TocMetsItem tocMetsItem : lijst3) {
        //                    folderItem.add(tocMetsItem);
        //                }
        //
        //                //
        //                list.add(folderItem);
        //            }

        // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

        //            }
    }

    return list;
}

From source file:org.iish.visualmets.services.TocDaoImp.java

private TocFolderItem createFolder(Document doc, String group, int recursive) {
    XPathExpression expr = null;
    try {/*  w w  w. j a va  2  s.  com*/
        // als geen group pak dan root mets:div directory
        if (group.equals("")) {
            //                expr = getXPathExpression("/mets:mets/mets:structMap/mets:div");
            expr = getXPathExpression("/" + namespaceName + "mets/" + namespaceName + "structMap");
        } else {
            expr = getXPathExpression("/" + namespaceName + "mets/" + namespaceName + "structMap//"
                    + namespaceName + "div[@ID='" + group + "']");
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    Object result = null;
    try {
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    NodeList nodes = (NodeList) result;

    //        System.out.println("++++ " + "/mets:mets/mets:structMap//mets:div[@ID='" + group +"']");

    TocFolderItem folderItem = new TocFolderItem();

    folderItem.setIndex(nodes.item(0).getAttributes().getNamedItem("ID").getNodeValue());
    folderItem.setTitle(nodes.item(0).getAttributes().getNamedItem("LABEL").getNodeValue());

    // does node (directory) have subdirectories (also a node, but watch out, files are also nodes)
    String hasDirs = "false";
    ArrayList<String> listOfSubDirectories = getArrayOfSubDirectories(nodes.item(0));
    if (listOfSubDirectories.size() > 0) {
        hasDirs = "true";
    }
    folderItem.setHaschildren(hasDirs);

    //
    ArrayList<TocMetsItem> lijst = new ArrayList<TocMetsItem>();
    System.out.println("ID: " + nodes.item(0).getAttributes().getNamedItem("ID").getNodeValue());
    lijst = getFilesRecursive(doc, lijst, nodes.item(0).getAttributes().getNamedItem("ID").getNodeValue(),
            recursive);

    for (TocMetsItem tocMetsItem : lijst) {
        folderItem.add(tocMetsItem);
    }

    return folderItem;
}

From source file:org.iish.visualmets.services.TocDaoImp.java

private ArrayList<TocMetsItem> getFilesRecursive(Document doc, ArrayList<TocMetsItem> lijst, String group,
        int recursive) {
    XPathExpression expr = null;
    try {/*  w ww.ja  v a  2s. c  o  m*/
        // als geen group pak dan root mets:div directory
        if (group.equals("")) {
            //                expr = getXPathExpression("/mets:mets/mets:structMap/mets:div");
            expr = getXPathExpression("/" + namespaceName + "mets/" + namespaceName + "structMap");
        } else {
            expr = getXPathExpression("/" + namespaceName + "mets/" + namespaceName + "structMap//"
                    + namespaceName + "div[@ID='" + group + "']");
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    Object result = null;
    try {
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    NodeList nodes = (NodeList) result;

    //        System.out.println("++++ " + "/mets:mets/mets:structMap//mets:div[@ID='" + group +"']");

    for (int j = 0; j < nodes.item(0).getChildNodes().getLength(); j++) {
        if (nodes.item(0).getChildNodes().item(j).getNodeName().equals(namespaceName + "div")) {
            int somethingFound = 0;
            String xlink_href = "";
            String thumbnail_href = "";
            String FILEID = "";

            for (int k = 0; k < nodes.item(0).getChildNodes().item(j).getChildNodes().getLength(); k++) {
                if (nodes.item(0).getChildNodes().item(j).getChildNodes().item(k).getNodeName()
                        .equals(namespaceName + "mptr")) {
                    somethingFound = 1;
                    xlink_href = nodes.item(0).getChildNodes().item(j).getChildNodes().item(k).getAttributes()
                            .getNamedItem("xlink:href").getNodeValue();
                }

                if (nodes.item(0).getChildNodes().item(j).getChildNodes().item(k).getNodeName()
                        .equals(namespaceName + "fptr")) {
                    somethingFound = 1;
                    FILEID = nodes.item(0).getChildNodes().item(j).getChildNodes().item(k).getAttributes()
                            .getNamedItem("FILEID").getNodeValue();
                }
            }

            if (somethingFound == 1) {
                String title = null;
                try {
                    title = nodes.item(0).getChildNodes().item(j).getAttributes().getNamedItem("LABEL")
                            .getNodeValue();
                } catch (NullPointerException e) {
                    title = "BIJ FILE DIV MOET OOK EEN LABEL!";
                }
                if (!FILEID.equals("")) {
                    thumbnail_href = getThumbnailUrl(doc, FILEID);
                }

                // add doc to list
                TocMetsItem ttt = addItem(xlink_href, title, thumbnail_href);
                lijst.add(ttt);
            }
        }
    }

    if (recursive == 1) {
        // find if current directory has subdirectories
        ArrayList<String> listOfSubDirectories = getArrayOfSubDirectories(nodes.item(0));
        if (listOfSubDirectories.size() > 0) {
            for (String s : listOfSubDirectories) {
                lijst = getFilesRecursive(doc, lijst, s, recursive);
            }
        }
    }

    return lijst;
}

From source file:org.iish.visualmets.services.TocDaoImp.java

private String getThumbnailUrl(Document doc, String FILEID) {
    String url = "";

    //        XPathFactory factory = XPathFactory.newInstance();
    XPathExpression expr = null;
    try {/*from   w ww .j a v  a  2  s  . c o m*/
        expr = getXPathExpression("/" + namespaceName + "mets/" + namespaceName + "fileSec/" + namespaceName
                + "fileGrp/" + namespaceName + "file[@ID='" + FILEID + "']/" + namespaceName + "FLocat");
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    Object result = null;
    try {
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    NodeList nodes = (NodeList) result;
    if (nodes.getLength() > 0) {
        url = nodes.item(0).getAttributes().getNamedItem("xlink:href").getNodeValue();
    }

    return url;
}

From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Gets a {@link NodeList} of {@link Node}s that contain information about the web
 * modules in the EAR.//  w ww  . ja  va 2  s  .  c  om
 * 
 * @param descriptorDom The EAR descriptor.
 * @return A NodeList of web module nodes.
 */
protected NodeList getWebModules(Document descriptorDom) {
    final XPathFactory xpathFactory = XPathFactory.newInstance();
    final XPath xpath = xpathFactory.newXPath();

    final XPathExpression xpathExpr;
    try {
        xpathExpr = xpath.compile(WEB_MODULE_XPATH);
    } catch (XPathExpressionException xpee) {
        throw new RuntimeException("Failed to compile XPathExpression from '" + WEB_MODULE_XPATH + "'", xpee);
    }

    try {
        final NodeList nodes = (NodeList) xpathExpr.evaluate(descriptorDom, XPathConstants.NODESET);

        if (this.getLogger().isDebugEnabled()) {
            this.getLogger()
                    .debug("Found " + nodes.getLength() + " '" + WEB_MODULE_XPATH + "' nodes in descriptor.");
        }

        return nodes;
    } catch (XPathExpressionException xpee) {
        throw new RuntimeException("Failed to evaluate XPathExpression='" + xpathExpr + "'", xpee);
    }
}

From source file:org.jasig.portal.security.provider.saml.XPathExpressionPool.java

public <T> T evaluate(String expression, final Object item, final QName returnType)
        throws XPathExpressionException {
    return this.doWithExpression(expression, new XPathExpressionCallback<T>() {
        @SuppressWarnings("unchecked")
        public T doWithExpression(XPathExpression xPathExpression) throws XPathExpressionException {
            return (T) xPathExpression.evaluate(item, returnType);
        }//from   w  w w.ja va2 s .  co m
    });
}

From source file:org.jboss.as.test.integration.management.cli.ModuleTestCase.java

private void checkModuleXml(String slotName, File modulesPath, boolean checkResources,
        boolean checkAbsoluteResources, boolean checkProperties, boolean checkDependencies,
        boolean checkMainClass) throws Exception {
    File testModuleRoot = new File(modulesPath, MODULE_NAME.replace('.', File.separatorChar));
    File slot = new File(testModuleRoot, slotName);
    File moduleXml = new File(slot, "module.xml");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(moduleXml);

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

    // check resource-root
    XPathExpression pathAttrExpr = xpath.compile("/module/resources/resource-root/@path");
    NodeList nl = (NodeList) pathAttrExpr.evaluate(doc, XPathConstants.NODESET);
    List<String> paths = new ArrayList<>(2);
    for (int i = 0; i < nl.getLength(); i++) {
        paths.add(nl.item(i).getNodeValue());
    }/*from  w ww .  j a v a 2  s .  c  om*/
    if (checkResources && checkAbsoluteResources) {
        assertTrue("module.xml should contain two resource-root elements", nl.getLength() == 2);
        assertTrue("module.xml should contain resource-root element with atrribute path=\"Dummy.jar\"",
                paths.contains("Dummy.jar"));
        assertTrue("module.xml should contain resource-root element with atrribute path=\""
                + jarFile2.getCanonicalPath() + "\"", paths.contains(jarFile2.getCanonicalPath()));
    } else if (checkResources && !checkAbsoluteResources) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain resource-root element with atrribute path=\"Dummy.jar\"",
                paths.contains("Dummy.jar"));
    } else if (!checkResources && checkAbsoluteResources) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain resource-root element with atrribute path=\""
                + jarFile2.getCanonicalPath() + "\"", paths.contains(jarFile2.getCanonicalPath()));
    }

    // check properties
    XPathExpression propertiesExpr = xpath.compile("/module/properties/property");
    nl = (NodeList) propertiesExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkProperties) {
        assertTrue("module.xml should contain one property but it has " + nl.getLength() + " properties",
                nl.getLength() == 1);
        NamedNodeMap attributes = nl.item(0).getAttributes();
        String name = attributes.getNamedItem("name").getNodeValue();
        String value = attributes.getNamedItem("value").getNodeValue();
        assertTrue("module.xml should contain property bat=man", name.equals("bat") && value.equals("man"));
    } else {
        assertTrue("module.xml shouldn't contain any properties but it has " + nl.getLength() + " properties",
                nl.getLength() == 0);
    }

    // check dependencies
    XPathExpression dependenciesNameAttrExpr = xpath.compile("/module/dependencies/module/@name");
    nl = (NodeList) dependenciesNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkDependencies) {
        assertTrue("module.xml should contain two resource-root elements", nl.getLength() == 2);
        assertTrue("module.xml should contain module element with atrribute name=\"org.jboss.logging\"",
                nl.item(0).getNodeValue().equals("org.jboss.logging"));
        assertTrue("module.xml should contain module element with atrribute name=\"org.jboss.logmanager\"",
                nl.item(1).getNodeValue().equals("org.jboss.logmanager"));
    } else {
        assertTrue(
                "module.xml shouldn't contain any dependencies but it has " + nl.getLength() + " dependencies",
                nl.getLength() == 0);
    }

    XPathExpression exportDependenciesNameAttrExpr = xpath.compile("/module/dependencies/module/@export");
    nl = (NodeList) exportDependenciesNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkDependencies) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain module element with atrribute export=true",
                nl.item(0).getNodeValue().equals("true"));
    } else {
        assertTrue(
                "module.xml shouldn't contain any dependencies but it has " + nl.getLength() + " dependencies",
                nl.getLength() == 0);
    }

    // check main class
    XPathExpression mainClassNameAttrExpr = xpath.compile("/module/main-class/@name");
    nl = (NodeList) mainClassNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkMainClass) {
        assertTrue("module.xml should contain main-class element", nl.getLength() == 1);
        assertTrue("module.xml should contain main-class element with atrribute name=\"org.jboss.Test\"",
                nl.item(0).getNodeValue().equals("org.jboss.Test"));
    } else {
        assertTrue("module.xml shouldn't contain main-class element", nl.getLength() == 0);
    }

}

From source file:org.jboss.qa.jcontainer.tomcat.TomcatContainer.java

protected void configureServer() {
    try {/*from w  ww .  j  a v a  2  s.  c o m*/
        final File file = new File(configuration.getDirectory(), "conf" + File.separator + "server.xml");
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document doc = docBuilder.parse(file);

        final XPathFactory xPathfactory = XPathFactory.newInstance();
        final XPath xpath = xPathfactory.newXPath();
        final XPathExpression expr = xpath.compile("/Server/Service/Connector[@protocol='HTTP/1.1']");

        final Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        node.getAttributes().getNamedItem("port").setNodeValue(Integer.toString(configuration.getHttpPort()));

        // Write the content into xml file
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(doc);
        final StreamResult result = new StreamResult(file);
        transformer.transform(source, result);
    } catch (Exception e) {
        log.error("Ports was not configured", e);
    }
}