Example usage for org.dom4j XPath selectNodes

List of usage examples for org.dom4j XPath selectNodes

Introduction

In this page you can find the example usage for org.dom4j XPath selectNodes.

Prototype

List<Node> selectNodes(Object context);

Source Link

Document

selectNodes performs this XPath expression on the given Node or List of Node s instances appending all the results together into a single list.

Usage

From source file:net.nikr.eve.jeveasset.io.local.update.updates.Update1To2.java

License:Open Source License

private void convertDefaultPriceModes(final Document doc) {
    XPath xpathSelector = DocumentHelper.createXPath("/settings/marketstat");
    List<?> results = xpathSelector.selectNodes(doc);
    for (Iterator<?> iter = results.iterator(); iter.hasNext();) {
        Element elem = (Element) iter.next();
        Attribute attr = elem.attribute("defaultprice");
        if (attr != null) { //May not exist (in early versions)
            String currentValue = attr.getText();
            attr.setText(convertDefaultPriceMode(currentValue));
        }//www.ja va  2s . co m
    }
}

From source file:net.nikr.eve.jeveasset.io.local.update.updates.Update1To2.java

License:Open Source License

private void convertTableSettings(final Document doc) {
    XPath xpathSelector = DocumentHelper.createXPath("/settings/columns/column");
    List<?> results = xpathSelector.selectNodes(doc);
    List<String> tableColumnNames = new ArrayList<String>();
    List<String> tableColumnVisible = new ArrayList<String>();
    for (Iterator<?> iter = results.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();
        Attribute name = element.attribute("name");
        Attribute visible = element.attribute("visible");
        tableColumnNames.add(name.getText());
        if (visible.getText().equals("true")) {
            tableColumnVisible.add(name.getText());
        }/*from w w  w  . ja  va  2  s .  c  o  m*/
    }
    String mode = convertFlag(doc);
    writeTableSettings(doc, mode, tableColumnNames, tableColumnVisible);
}

From source file:net.nikr.eve.jeveasset.io.local.update.updates.Update1To2.java

License:Open Source License

private String convertFlag(final Document doc) {
    XPath flagSelector = DocumentHelper.createXPath("/settings/flags/flag");
    List<?> flagResults = flagSelector.selectNodes(doc);
    boolean text = false;
    boolean window = false;
    for (Iterator<?> iter = flagResults.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();
        Attribute key = element.attribute("key");
        Attribute visible = element.attribute("enabled");
        if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_TEXT")) {
            text = visible.getText().equals("true");
            element.detach();//from  w  w w  .  ja  va2  s. c  o m
        }
        if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_WINDOW")) {
            window = visible.getText().equals("true");
            element.detach();
        }
    }
    if (text) {
        return "TEXT";
    }
    if (window) {
        return "WINDOW";
    }
    return "NONE";
}

From source file:net.sf.jguard.ext.authorization.manager.XmlAuthorizationManager.java

License:Open Source License

private List getElements(String xpath) {
    XPath xp2 = DocumentHelper.createXPath(xpath);
    Map<String, String> uris = new HashMap<String, String>();
    uris.put(STRING_NAMESPACE_PREFIX, HTTP_JGUARD_SOURCEFORGE_NET_XSD_J_GUARD_PRINCIPALS_PERMISSIONS_2_0_0);
    xp2.setNamespaceURIs(uris);/*from w  w  w .j  a v  a2s.c o  m*/

    return xp2.selectNodes(root);
}

From source file:org.alfresco.web.bean.wcm.FilePickerBean.java

License:Open Source License

/**
 * Run a configured search represented by the given node reference, against
 * the web project the XForm is currently within
 * /*from ww w.jav  a  2  s .c  o  m*/
 * @param configuredQueryNodRef
 *           NodeRef of the configured query with which to run the search
 * 
 * @return content nodes returned by the search
 */
private List<AVMNodeDescriptor> runConfiguredSearch(NodeRef configSearchNodeRef) {
    // get the store id used to run the configured search query
    WebProject webProject = this.getAvmBrowseBean().getWebProject();
    String storeID = webProject.getStoreId();

    // extract the content of configured search node to XML document
    ContentReader contentReader = getContentService().getReader(configSearchNodeRef, ContentModel.PROP_CONTENT);
    InputStream queryInpStream = contentReader.getContentInputStream();
    SAXReader reader = new SAXReader();
    Document queryDoc = null;
    try {
        queryDoc = reader.read(queryInpStream);
    } catch (DocumentException de) {
        // ignore exception and return null
        return null;
    }

    // extract search query from configured search XML document
    String query = null;
    XPath queryXPath = DocumentHelper.createXPath(CONFIGURED_SEARCH_QUERY_XPATH);
    List xpathResult = queryXPath.selectNodes(queryDoc);
    if ((xpathResult != null) && (xpathResult.size() != 0)) {
        // get the text from the query element
        Element queryElement = (Element) xpathResult.get(0);
        String queryElemText = queryElement.getText();

        // now extract the actual search query string from the CDATA section
        // within that text

        int cdataStartDelimIndex = queryElemText.indexOf(CDATA_START_DELIM);
        int cdataEndDelimIndex = queryElemText.indexOf(CDATA_END_DELIM);

        // if the CDATA start delimiter is found in the query element text
        // && there is text between the CDATA start and end delimiters then
        // extract
        // the query string from the CDATA section
        if ((cdataStartDelimIndex > -1)
                && ((cdataStartDelimIndex + CDATA_START_DELIM.length()) < cdataEndDelimIndex)) {
            query = queryElemText.substring(cdataStartDelimIndex + CDATA_START_DELIM.length(),
                    cdataEndDelimIndex);
        } else {
            // otherwise just use the text as is
            query = queryElemText;
        }
    }

    // perform the search against the repository
    // if query was extracted from the configured search successfully
    // (extracted query non-null)
    List<AVMNodeDescriptor> resultNodeDescriptors = null;
    if ((query != null) && (query.length() != 0)) {
        ResultSet results = null;
        try {
            results = this.getSearchService().query(new StoreRef(StoreRef.PROTOCOL_AVM, storeID),
                    SearchService.LANGUAGE_LUCENE, query);

            if (results.length() != 0) {
                resultNodeDescriptors = new ArrayList<AVMNodeDescriptor>();
                for (int i = 0; i < results.length(); i++) {
                    ResultSetRow row = results.getRow(i);
                    NodeRef resultNodeRef = row.getNodeRef();
                    Node resultNode = new Node(resultNodeRef);

                    // only add content type nodes to the search result
                    // as we don't want the user to navigate down into folders
                    // in the search results
                    if (getDictionaryService().isSubClass(resultNode.getType(), ContentModel.TYPE_CONTENT)) {
                        Pair<Integer, String> pair = AVMNodeConverter.ToAVMVersionPath(resultNodeRef);
                        Integer version = pair.getFirst();
                        String path = pair.getSecond();
                        resultNodeDescriptors.add(getAvmService().lookup(version, path));
                    }
                }
            }
        } catch (Throwable err) {
            throw new AlfrescoRuntimeException("Failed to execute search: " + query, err);
        } finally {
            if (results != null) {
                results.close();
            }
        }
    }

    return resultNodeDescriptors;
}

From source file:org.apache.taglibs.xtags.servlet.XPathServlet.java

License:Apache License

protected Document createDocument(HttpServletRequest request) throws ServletException {
    Document document = DocumentHelper.createDocument();
    Element element = document.addElement("results");

    try {// w w w. j a  va2  s .  c o  m
        URL url = getDocumentURL(request);
        if (url != null) {
            String path = request.getParameter("path");
            if (path != null && path.length() > 0) {
                Document source = reader.read(url);
                XPath xpath = source.createXPath(path);

                String contextPath = request.getParameter("contextPath");
                if (contextPath == null) {
                    contextPath = ".";
                }
                List context = source.selectNodes(contextPath);

                List results = null;
                if (!getBoolean(request, "sort")) {
                    results = xpath.selectNodes(context);
                } else {
                    String sortPath = request.getParameter("sortPath");
                    if (sortPath == null) {
                        sortPath = ".";
                    }
                    boolean distinct = getBoolean(request, "distinct");
                    XPath sortXPath = source.createXPath(sortPath);
                    results = xpath.selectNodes(context, sortXPath, distinct);
                }
                appendResults(element, results);
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new ServletException("Error parsing document: " + e, e);
    }
    return document;
}

From source file:org.apache.taverna.activities.xpath.XPathActivity.java

License:Apache License

/**
 * This method executes pre-configured instance of XPath activity.
 *//*from   w  w w  .ja  v a 2s . co m*/
@Override
public void executeAsynch(final Map<String, T2Reference> inputs, final AsynchronousActivityCallback callback) {
    // Don't execute service directly now, request to be run asynchronously
    callback.requestRun(new Runnable() {
        @Override
        @SuppressWarnings("unchecked")
        public void run() {

            InvocationContext context = callback.getContext();
            ReferenceService referenceService = context.getReferenceService();

            // ---- RESOLVE INPUT ----

            String xmlInput = (String) referenceService.renderIdentifier(inputs.get(IN_XML), String.class,
                    context);

            // ---- DO THE ACTUAL SERVICE INVOCATION ----

            List<Node> matchingNodes = new ArrayList<Node>();

            // only attempt to execute XPath expression if there is some input data
            if (xmlInput != null && xmlInput.length() > 0) {
                // XPath configuration is taken from the config bean
                try {
                    XPath expr = DocumentHelper.createXPath(json.get("xpathExpression").textValue());
                    Map<String, String> xpathNamespaceMap = new HashMap<>();
                    for (JsonNode namespaceMapping : json.get("xpathNamespaceMap")) {
                        xpathNamespaceMap.put(namespaceMapping.get("prefix").textValue(),
                                namespaceMapping.get("uri").textValue());
                    }
                    expr.setNamespaceURIs(xpathNamespaceMap);
                    Document doc = DocumentHelper.parseText(xmlInput);
                    matchingNodes = expr.selectNodes(doc);
                } catch (InvalidXPathException e) {
                    callback.fail("Incorrect XPath Expression -- XPath processing library "
                            + "reported the following error: " + e.getMessage(), e);

                    // make sure we don't call callback.receiveResult later
                    return;
                } catch (DocumentException e) {
                    callback.fail("XML document was not valid -- XPath processing library "
                            + "reported the following error: " + e.getMessage(), e);

                    // make sure we don't call callback.receiveResult later
                    return;
                } catch (XPathException e) {
                    callback.fail("Unexpected error has occurred while executing the XPath expression. "
                            + "-- XPath processing library reported the following error:\n" + e.getMessage(),
                            e);

                    // make sure we don't call callback.receiveResult later
                    return;
                }
            }

            // --- PREPARE OUTPUTS ---

            List<String> outNodesText = new ArrayList<String>();
            List<String> outNodesXML = new ArrayList<String>();
            Object textValue = null;
            Object xmlValue = null;

            for (Object o : matchingNodes) {
                if (o instanceof Node) {
                    Node n = (Node) o;
                    if (n.getStringValue() != null && n.getStringValue().length() > 0) {
                        outNodesText.add(n.getStringValue());
                        if (textValue == null)
                            textValue = n.getStringValue();
                    }
                    outNodesXML.add(n.asXML());
                    if (xmlValue == null)
                        xmlValue = n.asXML();
                } else {
                    outNodesText.add(o.toString());
                    if (textValue == null)
                        textValue = o.toString();
                }
            }

            // ---- REGISTER OUTPUTS ----

            Map<String, T2Reference> outputs = new HashMap<String, T2Reference>();
            if (textValue == null) {
                ErrorDocumentService errorDocService = referenceService.getErrorDocumentService();
                textValue = errorDocService.registerError("No value produced", 0, callback.getContext());
            }

            if (xmlValue == null) {
                ErrorDocumentService errorDocService = referenceService.getErrorDocumentService();
                xmlValue = errorDocService.registerError("No value produced", 0, callback.getContext());
            }

            T2Reference firstNodeAsText = referenceService.register(textValue, 0, true, context);
            outputs.put(SINGLE_VALUE_TEXT, firstNodeAsText);

            T2Reference firstNodeAsXml = referenceService.register(xmlValue, 0, true, context);
            outputs.put(SINGLE_VALUE_XML, firstNodeAsXml);

            T2Reference outNodesAsText = referenceService.register(outNodesText, 1, true, context);
            outputs.put(OUT_TEXT, outNodesAsText);

            T2Reference outNodesAsXML = referenceService.register(outNodesXML, 1, true, context);
            outputs.put(OUT_XML, outNodesAsXML);

            // return map of output data, with empty index array as this is
            // the only and final result (this index parameter is used if
            // pipelining output)
            callback.receiveResult(outputs, new int[0]);
        }
    });
}

From source file:org.codehaus.cargo.container.weblogic.WebLogic8xConfigXmlInstalledLocalDeployer.java

License:Apache License

/**
 * {@inheritDoc} deploys files by adding their configuration to the config.xml file of the
 * WebLogic server.//from   ww  w. j  a va  2 s  .c  om
 * 
 * @see org.codehaus.cargo.container.spi.deployer.AbstractDeployer#deploy(org.codehaus.cargo.container.deployable.Deployable)
 */
@Override
public void deploy(Deployable deployable) {
    Document configXml = readConfigXml();
    XPath xpathSelector = DocumentHelper.createXPath("//Domain");
    List<Element> results = xpathSelector.selectNodes(configXml);
    Element domain = results.get(0);

    if (deployable.getType() == DeployableType.WAR) {
        addWarToDomain((WAR) deployable, domain);
    } else if (deployable.getType() == DeployableType.EAR) {
        addEarToDomain((EAR) deployable, domain);
    } else {
        throw new ContainerException("Not supported");
    }

    this.writeConfigXml(configXml);
}

From source file:org.codehaus.cargo.container.weblogic.WebLogic8xConfigXmlInstalledLocalDeployer.java

License:Apache License

/**
 * {@inheritDoc} undeploys files by removing their configuration to the config.xml file of the
 * WebLogic server.//from  www .j a  v a 2 s.  c om
 * 
 * @see org.codehaus.cargo.container.spi.deployer.AbstractDeployer#undeploy(org.codehaus.cargo.container.deployable.Deployable)
 */
@Override
public void undeploy(Deployable deployable) {
    Document configXml = readConfigXml();
    XPath xpathSelector = DocumentHelper.createXPath(
            "//Application[@Path='" + getFileHandler().getParent(getAbsolutePath(deployable)) + "']");
    List<Element> results = xpathSelector.selectNodes(configXml);
    for (Element element : results) {
        configXml.remove(element);
    }
    this.writeConfigXml(configXml);

}

From source file:org.codehaus.cargo.util.Dom4JUtil.java

License:Apache License

/**
 * The following will search the given element for the specified xpath and return a list of
 * nodes that match.// w  w  w.  j  av  a  2  s. c  o m
 * 
 * @param xpath - selection criteria
 * @param toSearch - element to start the search at
 * @return List of matching elements
 */
public List<Element> selectElementsMatchingXPath(String xpath, Element toSearch) {
    XPath xpathSelector = DocumentHelper.createXPath(xpath);
    xpathSelector.setNamespaceURIs(getNamespaces());
    List<Element> results = xpathSelector.selectNodes(toSearch);
    return results;
}