Example usage for org.dom4j Node selectSingleNode

List of usage examples for org.dom4j Node selectSingleNode

Introduction

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

Prototype

Node selectSingleNode(String xpathExpression);

Source Link

Document

selectSingleNode evaluates an XPath expression and returns the result as a single Node instance.

Usage

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

License:Educational Community License

@SuppressWarnings("unchecked")
public JSONObject getPathsJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    JSONObject out = new JSONObject();
    Boolean isHierarchical = false;
    if (isPathType(rootPath, new String[] { "main" }, 0)) {
        extractPaths(rootPath, new String[] { "main" }, 0);
    } else if (isPathType(rootPath, new String[] { "hierarchical" }, 0)) {
        extractPaths(rootPath, new String[] { "hierarchical" }, 0);
        isHierarchical = true;/*from  w  ww  .j a  v  a  2s .  c o  m*/
    }

    try {
        JSONObject moredata = new JSONObject();
        List<String> list = new ArrayList<String>();
        ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, "/relations?" + searchPath(restrictions),
                null, creds, cache);
        Document doc = data.getDocument();
        if (doc == null)
            throw new UnderlyingStorageException("Could not retrieve relation, missing relations_common");
        JSONObject pagination = new JSONObject();
        String xmlroot = "relations-common-list";
        List<Node> nodes = doc.getDocument().selectNodes("/" + xmlroot + "/*");
        for (Node node : nodes) {
            if (node.matches("/" + xmlroot + "/relation-list-item")) {
                //if(post_filter(creds,cache,restrictions,node))
                list.add(node.selectSingleNode("csid").getText());
                if (isHierarchical) {
                    JSONObject hdata = new JSONObject();
                    Node subjectNode = node.selectSingleNode("subject");
                    Node objectNode = node.selectSingleNode("object");
                    hdata.put("subjecturi", subjectNode.selectSingleNode("uri").getText());
                    hdata.put("objecturi", objectNode.selectSingleNode("uri").getText());
                    hdata.put("subjectcsid", subjectNode.selectSingleNode("csid").getText());
                    hdata.put("objectcsid", objectNode.selectSingleNode("csid").getText());

                    findNameUnderNode(hdata, "subjectname", "subjectrefname", subjectNode);
                    findNameUnderNode(hdata, "objectname", "objectrefname", objectNode);

                    hdata.put("type", node.selectSingleNode("predicate").getText());
                    hdata.put("csid", node.selectSingleNode("csid").getText());
                    moredata.put(node.selectSingleNode("csid").getText(), hdata);
                }
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }

        out.put("pagination", pagination);
        out.put("listItems", list.toArray(new String[0]));
        out.put("moredata", moredata);
        return out;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage(),
                e.getStatus(), e.getUrl());
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Could not retrieve relation", e);
    }
}

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

License:Educational Community License

private void findNameUnderNode(JSONObject out, String nameKey, String refNameKey, Node itemNode)
        throws JSONException {
    // Look for something to put into the subjectname. Start with refName,
    // then name, then number
    Node itemRefName = itemNode.selectSingleNode("refName");
    String nameValue = null;//w  w w . j ava2 s.  co  m
    if (itemRefName != null) {
        String refNameValue = itemRefName.getText();
        out.put(refNameKey, refNameValue);
        RefName.AuthorityItem item = RefName.AuthorityItem.parse(refNameValue);
        if (item != null) {
            nameValue = item.displayName;
        } else {
            RefName.Authority authority = RefName.Authority.parse(refNameValue);
            if (authority != null) {
                nameValue = authority.displayName;
            }
        }
    }
    // If no displayName from refName, then try name element
    if (nameValue == null) {
        Node itemNameNode = itemNode.selectSingleNode("name");
        if (itemNameNode != null) {
            nameValue = itemNameNode.getText();
        }
    }
    // Still nothing? try number element
    if (nameValue == null) {
        Node itemNumberNode = itemNode.selectSingleNode("number");
        if (itemNumberNode != null) {
            nameValue = itemNumberNode.getText();
        }
    }
    if (nameValue == null) {
        nameValue = "MISSING DATA";
    }
    out.put(nameKey, nameValue);
}

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

License:Educational Community License

@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    extractPaths(rootPath, new String[] { "main" }, 0);
    try {//from ww w .  j av  a 2  s. c o  m
        List<String> out = new ArrayList<String>();
        ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, "/relations/" + searchPath(restrictions),
                null, creds, cache);
        Document doc = data.getDocument();
        if (doc == null)
            throw new UnderlyingStorageException("Could not retrieve relation, missing relations_common");
        List<Node> objects = doc.getDocument().selectNodes("relations-common-list/relation-list-item");
        for (Node object : objects) {
            if (post_filter(creds, cache, restrictions, object))
                out.add(object.selectSingleNode("csid").getText());
        }
        return out.toArray(new String[0]);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage(),
                e.getStatus(), e.getUrl(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage());
    }
}

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 {// w  ww.  j  av  a  2  s .co 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 ww .j a v a2 s. c o m*/
@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.collectionspace.chain.csp.persistence.services.vocab.VocabInstanceCache.java

License:Educational Community License

@SuppressWarnings("unchecked")
private void buildVocabularies(CSPRequestCredentials creds, CSPRequestCache cache)
        throws ConnectionException, UnderlyingStorageException {
    ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, "/" + r.getServicesURL() + "/", null, creds,
            cache);//from ww w .  ja  va 2 s  .  com
    Document doc = data.getDocument();
    if (doc == null)
        throw new UnderlyingStorageException("Could not retrieve vocabularies");
    String[] path_parts = r.getServicesInstancesPath().split(":", 2);
    String[] tag_parts = path_parts[1].split(",", 2);
    List<Node> objects = doc.getDocument().selectNodes(tag_parts[1]);
    for (Node object : objects) {
        String name = "MISSING";
        if (null != object.selectSingleNode("displayName")) {
            name = object.selectSingleNode("displayName").getText();
        }
        if (null == object.selectSingleNode("shortIdentifier")) {
            continue;
        }
        String base = object.selectSingleNode("shortIdentifier").getText();
        if (base == null)
            continue;
        if (!vocabs.containsKey(base)) {
            vocabs.put(base, name);
        }
        csids.put(base, object.selectSingleNode("csid").getText());
    }
}

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

License:Open Source License

/**
 * Executes the specified XPath query as a single node query, returning the text value of the resulting single node.
 */// ww w  .ja  v a  2 s . com
public static String selectSingleNodeValue(Node node, String xpathQuery) {
    Node resultNode = node.selectSingleNode(xpathQuery);
    if (resultNode != null) {
        return resultNode.getText();
    } else {
        return null;
    }
}

From source file:org.craftercms.cstudio.alfresco.dm.script.DmImportScript.java

License:Open Source License

/**
 * import site contents/*from w ww  . java 2  s. c  o  m*/
 * 
 * @param configLocation
 */
@SuppressWarnings("unchecked")
public void importSite(String configLocation) {
    Document document = loadConfiguration(configLocation);
    if (document != null) {
        Element root = document.getRootElement();
        List<Node> siteNodes = root.selectNodes("site");
        if (siteNodes != null) {
            for (Node siteNode : siteNodes) {
                String name = siteNode.valueOf("name");
                String buildDataLocation = siteNode.valueOf("build-data-location");
                String publishingChannelGroup = siteNode.valueOf("publish-channel-group");
                String publish = siteNode.valueOf("publish");
                String publishSize = siteNode.valueOf("publish-chunk-size");
                int chunkSize = (!StringUtils.isEmpty(publishSize) && StringUtils.isNumeric(publishSize))
                        ? Integer.valueOf(publishSize)
                        : -1;
                Node foldersNode = siteNode.selectSingleNode("folders");
                String targetRoot = this.getServicesConfig().getRepositoryRootPath(name);
                NodeRef targetRef = this.findContent(targetRoot);
                String sourceLocation = buildDataLocation + "/" + name;
                String delayIntervalStr = siteNode.valueOf("delay-interval");
                int delayInterval = (!StringUtils.isEmpty(delayIntervalStr)
                        && StringUtils.isNumeric(delayIntervalStr)) ? Integer.valueOf(delayIntervalStr) : -1;
                String delayLengthStr = siteNode.valueOf("delay-length");
                int delayLength = (!StringUtils.isEmpty(delayLengthStr)
                        && StringUtils.isNumeric(delayLengthStr)) ? Integer.valueOf(delayLengthStr) : -1;

                // trigger an action
                Map<String, Serializable> args = new FastMap<String, Serializable>();
                args.put(DmImportActionExecutor.PARAM_SITE, name);
                args.put(DmImportActionExecutor.PARAM_SOURCE_LOCATION, sourceLocation);
                args.put(DmImportActionExecutor.PARAM_TARGET_LOCATION, targetRoot);
                args.put(DmImportActionExecutor.PARAM_PUBLISH, publish);
                args.put(DmImportActionExecutor.PARAM_CHUNK_SIZE, chunkSize);
                args.put(DmImportActionExecutor.PARAM_DELAY_INTERVAL, delayInterval);
                args.put(DmImportActionExecutor.PARAM_DELAY_LENGTH, delayLength);
                args.put(DmImportActionExecutor.PARAM_PUBLISH_CHANNEL_GROUP, publishingChannelGroup);
                args.put(DmImportActionExecutor.PARAM_CONFIG_NODE, (Serializable) foldersNode);
                Action action = _actionService.createAction(DmImportActionExecutor.NAME, args);
                _actionService.executeAction(action, targetRef, false, true);
            }
        }
    }
}

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

License:Open Source License

/**
 * load delete dependencies mapping/*  w w w  .j av a 2 s. c  o  m*/
 * 
 * @param contentTypeConfig
 * @param nodes
 */
protected void loadDeleteDependencies(ContentTypeConfigTO contentTypeConfig, List<Node> nodes) {
    List<DeleteDependencyConfigTO> deleteConfigs = new FastList<DeleteDependencyConfigTO>();
    if (nodes != null) {
        for (Node node : nodes) {
            Node patternNode = node.selectSingleNode("pattern");
            Node removeFolderNode = node.selectSingleNode("remove-empty-folder");
            if (patternNode != null) {
                String pattern = patternNode.getText();
                String removeEmptyFolder = removeFolderNode.getText();
                boolean isRemoveEmptyFolder = false;
                if (removeEmptyFolder != null) {
                    isRemoveEmptyFolder = Boolean.valueOf(removeEmptyFolder);
                }
                if (StringUtils.isNotEmpty(pattern)) {
                    DeleteDependencyConfigTO deleteConfigTO = new DeleteDependencyConfigTO(pattern,
                            isRemoveEmptyFolder);
                    deleteConfigs.add(deleteConfigTO);
                }
            }
        }
        contentTypeConfig.setDeleteDependencies(deleteConfigs);
    }
}

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

License:Open Source License

/**
 * //w w w  .j  a  v a 2s .  c o m
 * @param config
 * @param copyDependencyNodes
 * @return
 */
protected void loadCopyDependencyPatterns(ContentTypeConfigTO config, List<Node> copyDependencyNodes) {
    List<CopyDependencyConfigTO> copyConfig = new FastList<CopyDependencyConfigTO>();
    if (copyDependencyNodes != null) {
        for (Node copyDependency : copyDependencyNodes) {
            Node patternNode = copyDependency.selectSingleNode("pattern");
            Node targetNode = copyDependency.selectSingleNode("target");
            if (patternNode != null && targetNode != null) {
                String pattern = patternNode.getText();
                String target = targetNode.getText();
                if (StringUtils.isNotEmpty(pattern) && StringUtils.isNotEmpty(target)) {
                    CopyDependencyConfigTO copyDependencyConfigTO = new CopyDependencyConfigTO(pattern, target);
                    copyConfig.add(copyDependencyConfigTO);
                }
            }
        }
    }
    config.setCopyDepedencyPattern(copyConfig);

}