Example usage for org.dom4j Node selectNodes

List of usage examples for org.dom4j Node selectNodes

Introduction

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

Prototype

List<Node> selectNodes(String xpathExpression);

Source Link

Document

selectNodes evaluates an XPath expression and returns the result as a List of Node instances or String instances depending on the XPath expression.

Usage

From source file:org.ballproject.knime.base.config.CTDFileNodeConfigurationReader.java

License:Open Source License

private Parameter<?> getMultiParameterFromNode(Node node) throws Exception {
    String type = node.valueOf("@type");
    String name = node.valueOf("@name");
    String restrs = node.valueOf("@restrictions");
    String descr = node.valueOf("@description");
    String tags = node.valueOf("@tags");

    Set<String> tagset = tokenSet(tags);

    @SuppressWarnings("unchecked")
    List<Node> subnodes = node.selectNodes("LISTITEM");

    List<String> values = new ArrayList<String>();
    for (Node n : subnodes) {
        values.add(n.valueOf("@value"));
    }/*from  ww w.ja v a2 s . c  o m*/

    Parameter<?> param = null;

    if (type.toLowerCase().equals("double") || type.toLowerCase().equals("float")) {
        param = this.processDoubleListParameter(name, values, restrs, tags);
    } else {
        if (type.toLowerCase().equals("int")) {
            param = this.processIntListParameter(name, values, restrs, tags);
        } else {
            if (type.toLowerCase().equals("string")) {
                param = this.processStringListParameter(name, values, restrs, tags);
            }
        }
    }

    param.setDescription(descr);

    if (tagset.contains("mandatory") || tagset.contains("required")) {
        param.setIsOptional(false);
    }

    if (tagset.contains("advanced")) {
        param.setAdvanced(true);
    }

    return param;
}

From source file:org.ballproject.knime.base.config.CTDNodeConfigurationWriter.java

License:Open Source License

@SuppressWarnings("unchecked")
private void cleanItemLists() {
    List<Node> itemlists = doc.selectNodes("//ITEMLIST");
    for (Node itemlist : itemlists) {
        List<Node> listitems = itemlist.selectNodes("LISTITEM");
        for (Node item : listitems) {
            item.detach();//  w ww.ja  va  2  s . c o m
        }
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

License:Educational Community License

/**
 * return list view of items including hard deleted
 * @param root/*from  w  ww. ja  v a  2  s  .c  o  m*/
 * @param creds
 * @param cache
 * @param path
 * @param nodeName
 * @param matchlistitem
 * @param csidfield
 * @param fullcsid
 * @param view_map
 * @return
 * @throws ConnectionException
 * @throws JSONException
 */
// CSPACE-5988: Allow view_map to be passed as a parameter, instead of using the instance variable.
protected JSONObject getRepeatableHardListView(ContextualisedStorage root, CSPRequestCredentials creds,
        CSPRequestCache cache, String path, String nodeName, String matchlistitem, String csidfield,
        Boolean fullcsid, Map<String, String> view_map) throws ConnectionException, JSONException {
    JSONObject out = new JSONObject();
    JSONObject pagination = new JSONObject();
    Document list = null;
    List<JSONObject> listitems = new ArrayList<JSONObject>();
    ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
    if (all.getStatus() != 200) {
        //throw new StatusException(all.getStatus(),path,"Bad request during identifier cache map update: status not 200");
        throw new ConnectionException("Bad request during identifier cache map update: status not 200 is "
                + Integer.toString(all.getStatus()), all.getStatus(), path);
    }
    list = all.getDocument();

    List<Node> nodes = list.selectNodes(nodeName);
    if (matchlistitem.equals("roles_list/*") || matchlistitem.equals("permissions_list/*")) {
        //XXX hack to deal with roles being inconsistent
        //XXX CSPACE-1887 workaround
        for (Node node : nodes) {
            if (node.matches(matchlistitem)) {
                String csid = node.valueOf("@csid");
                JSONObject test = new JSONObject();
                test.put("csid", csid);
                listitems.add(test);
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
    } else {
        String[] allfields = null;
        String fieldsReturnedName = r.getServicesFieldsPath();
        for (Node node : nodes) {
            if (node.matches(matchlistitem)) {
                List<Node> fields = node.selectNodes("*");
                String csid = "";
                String urlPlusCSID = null;
                if (node.selectSingleNode(csidfield) != null) {
                    csid = node.selectSingleNode(csidfield).getText();
                    urlPlusCSID = r.getServicesURL() + "/" + csid;
                }
                JSONObject test = new JSONObject();
                for (Node field : fields) {
                    if (csidfield.equals(field.getName())) {
                        if (!fullcsid) {
                            int idx = csid.lastIndexOf("/");
                            if (idx != -1) {
                                csid = csid.substring(idx + 1);
                                urlPlusCSID = r.getServicesURL() + "/" + csid;
                            }
                        }
                        test.put("csid", csid);
                    } else {
                        String json_name = view_map.get(field.getName());
                        if (json_name != null) {
                            String value = field.getText();
                            // XXX hack to cope with multi values      
                            if (value == null || "".equals(value)) {
                                List<Node> inners = field.selectNodes("*");
                                for (Node n : inners) {
                                    value += n.getText();
                                }
                            }
                            String gleanname = urlPlusCSID;
                            if (csidfield.equals("uri")) {
                                gleanname = csid;
                            }
                            setGleanedValue(cache, gleanname, json_name, value);
                            test.put(json_name, value);
                        }
                    }
                }
                listitems.add(test);
                if (allfields == null || allfields.length == 0) {
                    if (log.isWarnEnabled()) {
                        log.warn(
                                "getRepeatableHardListView(): Missing fieldsReturned value - may cause fan-out!\nRecord:"
                                        + r.getID() + " request to: " + path);
                    }
                } else {
                    // Mark all the fields not yet found as gleaned - 
                    String gleanname = urlPlusCSID;
                    if (csidfield.equals("uri")) {
                        gleanname = csid;
                    }
                    for (String s : allfields) {
                        String gleaned = getGleanedValue(cache, gleanname, s);
                        if (gleaned == null) {
                            setGleanedValue(cache, gleanname, s, "");
                        }
                    }
                }
            } else if (fieldsReturnedName.equals(node.getName())) {
                String myfields = node.getText();
                allfields = myfields.split("\\|");
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
    }
    out.put("pagination", pagination);
    out.put("listItems", listitems);
    return out;
}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

License:Educational Community License

/**
 * return list view of items/*from www.  ja  va2s. co  m*/
 * TODO make getHardListView and getRepeatableHardListView to share more code as they aren't different enough to warrant the level of code repeat
 * @param creds
 * @param cache
 * @param path
 * @param nodeName
 * @param matchlistitem
 * @param csidfield
 * @param fullcsid
 * @return
 * @throws ConnectionException
 * @throws JSONException
 */
protected JSONObject getHardListView(CSPRequestCredentials creds, CSPRequestCache cache, String path,
        String nodeName, String matchlistitem, String csidfield, Boolean fullcsid)
        throws ConnectionException, JSONException {
    JSONObject out = new JSONObject();
    JSONObject pagination = new JSONObject();
    Document list = null;
    List<String> listitems = new ArrayList<String>();
    ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
    if (all.getStatus() != 200) {
        //throw new StatusException(all.getStatus(),path,"Bad request during identifier cache map update: status not 200");
        throw new ConnectionException("Bad request during identifier cache map update: status not 200 is "
                + Integer.toString(all.getStatus()), all.getStatus(), path);
    }
    list = all.getDocument();

    List<Node> nodes = list.selectNodes(nodeName);
    if (matchlistitem.equals("roles_list/*") || matchlistitem.equals("permissions_list/*")) {
        //XXX hack to deal with roles being inconsistent
        //XXX CSPACE-1887 workaround
        for (Node node : nodes) {
            if (node.matches(matchlistitem)) {
                String csid = node.valueOf("@csid");
                listitems.add(csid);
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
    } else {
        String[] allfields = null;
        String fieldsReturnedName = r.getServicesFieldsPath();
        for (Node node : nodes) {
            if (node.matches(matchlistitem)) {
                List<Node> fields = node.selectNodes("*");
                String csid = "";
                String urlPlusCSID = null;
                if (node.selectSingleNode(csidfield) != null) {
                    csid = node.selectSingleNode(csidfield).getText();
                    urlPlusCSID = r.getServicesURL() + "/" + csid;
                    setGleanedValue(cache, urlPlusCSID, "csid", csid);
                }
                for (Node field : fields) {
                    if (csidfield.equals(field.getName())) {
                        if (!fullcsid) {
                            int idx = csid.lastIndexOf("/");
                            if (idx != -1) {
                                csid = csid.substring(idx + 1);
                                urlPlusCSID = r.getServicesURL() + "/" + csid;
                            }
                        }
                        listitems.add(csid);
                    } else {
                        String json_name = view_map.get(field.getName());
                        if (json_name != null) {
                            String value = field.getText();
                            // XXX hack to cope with multi values      
                            if (value == null || "".equals(value)) {
                                List<Node> inners = field.selectNodes("*");
                                for (Node n : inners) {
                                    value += n.getText();
                                }
                            }
                            setGleanedValue(cache, urlPlusCSID, json_name, value);
                        }
                    }
                }
                if (allfields == null || allfields.length == 0) {
                    if (log.isWarnEnabled()) {
                        log.warn("getHardListView(): Missing fieldsReturned value - may cause fan-out!\nRecord:"
                                + r.getID() + " request to: " + path);
                    }
                } else {
                    // Mark all the fields not yet found as gleaned - 
                    for (String s : allfields) {
                        String gleaned = getGleanedValue(cache, urlPlusCSID, s);
                        if (gleaned == null) {
                            setGleanedValue(cache, urlPlusCSID, s, "");
                        }
                    }
                }
            } else if (fieldsReturnedName.equals(node.getName())) {
                String myfields = node.getText();
                allfields = myfields.split("\\|");
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
    }
    out.put("pagination", pagination);
    out.put("listItems", listitems.toArray(new String[0]));
    return out;

}

From source file:org.collectionspace.chain.csp.persistence.services.RecordStorage.java

License:Educational Community License

/**
 * Gets a list of csids of a certain type of record
 * /*from   w w  w  . java 2 s .  c  o m*/
 * XXX should not be used...
 */
@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        Document list = null;
        List<String> out = new ArrayList<String>();

        String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), "",
                false, "");

        ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
        if (all.getStatus() != 200) {
            throw new ConnectionException("Bad request during identifier cache map update: status not 200");
        }
        list = all.getDocument();
        List<Node> objects = list.selectNodes(r.getServicesListPath());
        if (r.getServicesListPath().equals("roles_list/*")) {
            //XXX hack to deal with roles being inconsistent
            // XXX CSPACE-1887 workaround
            for (Node object : objects) {
                String csid = object.valueOf("@csid");
                out.add(csid);
            }

        } else {
            for (Node object : objects) {
                List<Node> fields = object.selectNodes("*");
                String csid = object.selectSingleNode("csid").getText();
                for (Node field : fields) {
                    if ("csid".equals(field.getName())) {
                        int idx = csid.lastIndexOf("/");
                        if (idx != -1)
                            csid = csid.substring(idx + 1);
                        out.add(csid);
                    } else if ("uri".equals(field.getName())) {
                        // Skip!
                    } else {
                        String json_name = view_map.get(field.getName());
                        if (json_name != null) {
                            String value = field.getText();
                            // XXX hack to cope with multi values      
                            if (value == null || "".equals(value)) {
                                List<Node> inners = field.selectNodes("*");
                                for (Node n : inners) {
                                    value += n.getText();
                                }
                            }
                            setGleanedValue(cache, r.getServicesURL() + "/" + csid, json_name, value);
                        }
                    }
                }
            }
        }
        return out.toArray(new String[0]);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("Service layer exception:UnsupportedEncodingException", e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Service layer exception:JSONException", e);
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.user.UserStorage.java

License:Educational Community License

@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {//ww  w .  j  a v  a  2 s .  c o m
        List<String> out = new ArrayList<String>();
        Iterator rit = restrictions.keys();
        StringBuffer args = new StringBuffer();
        while (rit.hasNext()) {
            String key = (String) rit.next();
            FieldSet fs = r.getFieldTopLevel(key);
            if (!(fs instanceof Field))
                continue;
            String filter = ((Field) fs).getServicesFilterParam();
            if (filter == null)
                continue;
            args.append('&');
            args.append(filter);
            args.append('=');
            args.append(URLEncoder.encode(restrictions.getString(key), "UTF-8"));
        }
        // pagination

        String tail = args.toString();
        String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), tail,
                false, "");

        ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
        if (doc.getStatus() < 200 || doc.getStatus() > 399)
            throw new UnderlyingStorageException("Cannot retrieve account list", doc.getStatus(), path);
        Document list = doc.getDocument();
        List<Node> objects = list.selectNodes(r.getServicesListPath());
        for (Node object : objects) {
            List<Node> fields = object.selectNodes("*");
            String csid = object.selectSingleNode("csid").getText();
            for (Node field : fields) {
                if ("csid".equals(field.getName())) {
                    int idx = csid.lastIndexOf("/");
                    if (idx != -1)
                        csid = csid.substring(idx + 1);
                    out.add(csid);
                } else if ("uri".equals(field.getName())) {
                    // Skip!
                } else {
                    String json_name = view_map.get(field.getName());
                    if (json_name != null) {
                        String value = field.getText();
                        // XXX hack to cope with multi values
                        if (value == null || "".equals(value)) {
                            List<Node> inners = field.selectNodes("*");
                            for (Node n : inners) {
                                value += n.getText();
                            }
                        }
                        setGleanedValue(cache, r.getServicesURL() + "/" + csid, json_name, value);
                    }
                }
            }
        }
        return out.toArray(new String[0]);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("Exception building query" + e.getLocalizedMessage(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Exception building query" + e.getLocalizedMessage(), e);
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.vocab.ConfiguredVocabStorage.java

License:Educational Community License

/**
 * Returns JSON containing pagenumber, pagesize, itemsinpage, totalitems and the list of items itself 
 *///from   w w  w . j a va2s . c om
@SuppressWarnings("unchecked")
public JSONObject getPathsJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        JSONObject out = new JSONObject();
        List<String> list = new ArrayList<String>();
        String url;
        if (rootPath.isEmpty()) {
            url = "/" + r.getServicesURL() + ALL_VOCAB_ITEMS;
        } else {
            String vocab = RefName.shortIdToPath(rootPath);
            url = "/" + r.getServicesURL() + "/" + vocab + ITEMS_SUFFIX;
        }

        String path = getRestrictedPath(url, restrictions, r.getServicesSearchKeyword(), "", true,
                getDisplayNameKey());

        boolean excludeSoftDeleted = true;

        if (restrictions.has("deleted")) {
            excludeSoftDeleted = !restrictions.getBoolean("deleted");
        }

        if (excludeSoftDeleted && r.hasSoftDeleteMethod()) {
            path = softpath(path);
        }

        ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
        Document doc = data.getDocument();

        if (doc == null)
            throw new UnderlyingStorageException("Could not retrieve vocabulary items", data.getStatus(), path);
        String[] tag_parts = r.getServicesListPath().split(",", 2);

        JSONObject pagination = new JSONObject();
        String[] allfields = null;
        String fieldsReturnedName = r.getServicesFieldsPath();
        List<Node> nodes = doc.selectNodes("/" + tag_parts[1].split("/")[0] + "/*");
        for (Node node : nodes) {
            if (node.matches("/" + tag_parts[1])) {
                // Risky hack - assumes displayName must be at root. Really should
                // understand that the list results are a different schema from record GET.
                String dnName = getDisplayNameKey();
                String csid = node.selectSingleNode("csid").getText();
                list.add(csid);
                String urlPlusCSID = url + "/" + csid;

                List<Node> nameNodes = node.selectNodes(dnName);
                String nameListValue = null;
                for (Node nameNode : nameNodes) {
                    String name = nameNode.getText();
                    if (nameListValue == null) {
                        nameListValue = name;
                    } else {
                        nameListValue = JSONUtils.appendWithArraySeparator(nameListValue, name);
                    }
                }
                if (nameListValue == null) {
                    throw new JSONException("No displayNames found!");
                } else {
                    String json_name = view_map.get(dnName);
                    setGleanedValue(cache, urlPlusCSID, json_name, nameListValue);
                }

                List<Node> fields = node.selectNodes("*[(name()!='" + dnName + "')]");
                for (Node field : fields) {
                    String json_name = view_map.get(field.getName());
                    if (json_name != null) {
                        String value = field.getText();
                        // XXX hack to cope with multi values      
                        if (value == null || "".equals(value)) {
                            List<Node> inners = field.selectNodes("*");
                            for (Node n : inners) {
                                value += n.getText();
                            }
                        }
                        setGleanedValue(cache, urlPlusCSID, json_name, value);
                    }
                }
                if (allfields == null || allfields.length == 0) {
                    log.warn("Missing fieldsReturned value - may cause fan-out!");
                } else {
                    // Mark all the fields not yet found as gleaned - 
                    for (String s : allfields) {
                        String gleaned = getGleanedValue(cache, urlPlusCSID, s);
                        if (gleaned == null) {
                            setGleanedValue(cache, urlPlusCSID, s, "");
                        }
                    }
                }
            } else if (fieldsReturnedName.equals(node.getName())) {
                String myfields = node.getText();
                allfields = myfields.split("\\|");
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }

        out.put("pagination", pagination);
        out.put("listItems", list.toArray(new String[0]));
        return out;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Connection exception" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("UTF-8 not supported!?" + e.getLocalizedMessage());
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Error parsing JSON" + e.getLocalizedMessage());
    }
}

From source file:org.craftercms.core.util.XmlUtils.java

License:Open Source License

/**
 * Executes the specified XPath query as a multiple node query, returning the text values of the resulting list of
 * nodes./*from  www.  j  a va  2 s. c  o m*/
 */
@SuppressWarnings("unchecked")
public static List<String> selectNodeValues(Node node, String xpathQuery) {
    List<Node> resultNodes = node.selectNodes(xpathQuery);

    return extractNodeValues(resultNodes);
}

From source file:org.craftercms.cstudio.alfresco.dm.service.impl.DmContentTypeServiceImpl.java

License:Open Source License

/**
 * merge the given template child element to the node
 *
 * @param templateElement//from   w  w  w  .  j av  a2s . c  o  m
 * @param targetNode
 */
@SuppressWarnings("unchecked")
protected void mergeChildElement(Element templateElement, Node targetNode) {
    List<Element> elements = templateElement.elements();
    if (elements != null && elements.size() > 0) {
        for (Element element : elements) {
            String path = element.getName();
            List<Node> nodes = targetNode.selectNodes(path);
            if (nodes != null && nodes.size() > 0) {
                for (Node childNode : nodes) {
                    mergeChildElement(element, childNode);
                }
            } else {
                Element copiedElement = element.createCopy();
                Element targetElement = (Element) targetNode;
                targetElement.add(copiedElement);
            }
        }
    }
}

From source file:org.craftercms.cstudio.alfresco.dm.util.impl.DmImportServiceImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public void importFromConfigNode(final String site, String publishChannelGroup, final Node node,
        final String fileRoot, final String targetRoot, final NodeRef targetRef, boolean publish, int chunkSize,
        int delayInterval, int delayLength) {
    if (!inProgress) {
        inProgress = true;//from   ww  w.j  av a 2 s  .  co  m
        if (delayInterval > 0)
            pauseEanbeld = true;
        this.currentDelayInterval = delayInterval * 1000;
        this.currentDelayLength = delayLength * 1000;
        final Set<String> importedPaths = new FastSet<String>();
        final List<String> importedFullPaths = new FastList<String>();
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("[IMPORT] started importing in " + site + ", pause enabled: " + pauseEanbeld
                    + ", delay interval: " + this.currentDelayInterval + ", delay length: "
                    + this.currentDelayLength);
        }
        boolean overWrite = ContentFormatUtils.getBooleanValue(node.valueOf("@over-write"));
        final List<Node> folderNodes = node.selectNodes("folder");
        if (publish) {
            SiteService siteService = getService(SiteService.class);
            PublishingChannelGroupConfigTO configTO = siteService.getPublishingChannelGroupConfigs(site)
                    .get(publishChannelGroup);
            String user = _authenticationService.getCurrentUserName();
            List<PublishingChannel> channels = getChannels(site, configTO);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[IMPORT] publishing user: " + user + ", publishing channel config: "
                        + configTO.getName());
            }
            this.nextStop = System.currentTimeMillis() + this.currentDelayInterval;
            createFolders(site, importedPaths, importedFullPaths, folderNodes, fileRoot, targetRef, targetRoot,
                    "", overWrite, channels, user);
            LOGGER.info("Starting Publish of Imported Files (Total " + importedFullPaths.size()
                    + " On chunkSize of " + chunkSize + " )");
            publish(site, publishChannelGroup, targetRoot, importedFullPaths, chunkSize);
        } else {
            this.nextStop = System.currentTimeMillis() + this.currentDelayInterval;
            createFolders(site, importedPaths, importedFullPaths, folderNodes, fileRoot, targetRef, targetRoot,
                    "", overWrite, null, null);
        }
        inProgress = false;
    } else {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("[IMPORT] an import process is currently running.");
        }
    }
}