Example usage for org.dom4j Node getName

List of usage examples for org.dom4j Node getName

Introduction

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

Prototype

String getName();

Source Link

Document

getName returns the name of this node.

Usage

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

License:Open Source License

public String getPath(Node n) {

    List<String> path_nodes = new ArrayList<String>();
    while (n != null && !n.getName().equals("PARAMETERS")) {
        path_nodes.add(n.valueOf("@name"));
        n = n.getParent();/* ww w.java2s  .c o  m*/
    }

    Collections.reverse(path_nodes);

    String ret = "";
    int N = path_nodes.size();
    for (int i = 0; i < N; i++) {
        if (i == N - 1) {
            ret += path_nodes.get(i);
        } else {
            ret += path_nodes.get(i) + ".";
        }
    }
    return ret;
}

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

License:Educational Community License

/**
 * Returns a list of csid's from a certain type of record
 *///from w w  w. j a va  2 s.c  o  m
@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, "res", "", false, "");

        ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
        if (all.getStatus() != 200) {
            throw new ConnectionException("Bad request in Authorization Storage: status not 200",
                    all.getStatus(), path);
        }
        list = all.getDocument();
        List<Node> objects = list.selectNodes(r.getServicesListPath());

        for (Node object : objects) {
            String csid = object.valueOf("@csid");
            out.add(csid);
            setGleanedValue(cache, r.getServicesURL() + "/" + csid, view_map.get(object.getName()),
                    object.getText());
        }

        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" + e.getLocalizedMessage(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e);
    }
}

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

License:Educational Community License

/**
 * Gets a list of csids of a certain type of record together with the pagination info
 * permissions might need to break the mold tho.
 *//*from   w  w  w  .  j av  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();

        // PLS: why on earth would reports be routed through AuthStorage?!?!
        if (r.getID().equals("reports")) {

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

            String node = "/" + r.getServicesListPath().split("/")[0] + "/*";
            JSONObject data = getListView(creds, cache, path, node, "/" + r.getServicesListPath(), "csid",
                    false, r);

            return data;
        }

        Document list = null;
        String prefix = null;
        Boolean queryadded = false;
        JSONObject pagination = new JSONObject();
        List<String> listitems = new ArrayList<String>();
        String serviceurl = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(),
                "", false, "");

        ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, serviceurl, null, creds, cache);
        if (all.getStatus() != 200) {
            throw new ConnectionException("Bad request in Authorization Storage getPathsJSON: status not 200",
                    all.getStatus(), serviceurl);
        }
        list = all.getDocument();

        List<Node> nodes = list.selectNodes("/" + r.getServicesListPath().split("/")[0] + "/*");
        for (Node node : nodes) {
            if (node.matches("/" + r.getServicesListPath())) {
                String csid = node.valueOf("@csid");
                listitems.add(csid);
                String fullPath = r.getServicesURL() + "/" + csid;
                if (view_map.get(node.getName()) != null) {
                    setGleanedValue(cache, fullPath, view_map.get(node.getName()), node.getText());
                }
                // Now glean the values we need from the child nodes
                List<Node> fields = node.selectNodes("*");
                for (Node field : fields) {
                    // Is this a field we want?
                    String json_name = view_map.get(field.getName());
                    if (json_name != null) {
                        String value = field.getText();
                        setGleanedValue(cache, r.getServicesURL() + "/" + csid, json_name, value);
                    }
                }
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }

        out.put("pagination", pagination);
        out.put("listItems", listitems.toArray(new String[0]));
        return out;
    } 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" + e.getLocalizedMessage(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e);
    }
}

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

License:Educational Community License

/**
 * get data needed for terms Used block of a record
 * @param creds//w  ww . ja  v a2  s  . c o  m
 * @param cache
 * @param path
 * @return
 * @throws ExistException
 * @throws UnimplementedException
 * @throws UnderlyingStorageException
 * @throws JSONException
 * @throws UnsupportedEncodingException 
 */
public JSONObject refViewRetrieveJSON(ContextualisedStorage storage, CSPRequestCredentials creds,
        CSPRequestCache cache, String path, JSONObject restrictions) throws ExistException,
        UnimplementedException, UnderlyingStorageException, JSONException, UnsupportedEncodingException {
    try {
        JSONObject out = new JSONObject();
        JSONObject pagination = new JSONObject();
        JSONObject listitems = new JSONObject();
        //not all the records need a reference, look in cspace-config.xml for which that don't
        if (r.hasTermsUsed()) {
            path = getRestrictedPath(path, restrictions, "kw", "", false, "");
            if (r.hasSoftDeleteMethod()) {//XXX completely not the right thinsg to do but a good enough hack
                path = softpath(path);
            }
            if (r.hasHierarchyUsed("screen")) {
                path = hierarchicalpath(path);
            }
            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",
                        all.getStatus(), path);
            Document list = all.getDocument();

            //assumes consistency in service layer payloads - possible could configure this rather than hard code?
            List<Node> nodes = list.selectNodes("authority-ref-list/*");
            for (Node node : nodes) {
                if (node.getName().equals("authority-ref-item")) {
                    if (!(node instanceof Element))
                        continue;
                    if (((Element) node).hasContent()) {

                        String key = ((Element) node).selectSingleNode("sourceField").getText();
                        String refname = ((Element) node).selectSingleNode("refName").getText();
                        String itemDisplayName = ((Element) node).selectSingleNode("itemDisplayName").getText();
                        String uri = "";
                        if (null != ((Element) node).selectSingleNode("uri")) { //seems to be missing sometimes
                            uri = ((Element) node).selectSingleNode("uri").getText();
                        }

                        String fieldName = key;
                        if (key.split(":").length > 1) {
                            fieldName = key.split(":")[1];
                        }

                        Field fieldinstance = null;
                        if (r.getFieldFullList(fieldName) instanceof Repeat) {
                            Repeat rp = (Repeat) r.getFieldFullList(fieldName);
                            for (FieldSet a : rp.getChildren("GET")) {
                                if (a instanceof Field && a.hasAutocompleteInstance()) {
                                    fieldinstance = (Field) a;
                                }
                            }
                        } else {
                            fieldinstance = (Field) r.getFieldFullList(fieldName);
                        }

                        if (fieldinstance != null) {

                            JSONObject data = new JSONObject();
                            data.put("sourceField", key);
                            data.put("itemDisplayName", itemDisplayName);
                            data.put("refname", refname);
                            data.put("uri", uri);
                            //JSONObject data=miniForURI(storage,creds,cache,refname,null,restrictions);
                            /*
                            if(!data.has("refid")){//incase of permissions errors try our best
                               data.put("refid",refname);
                               if(data.has("displayName")){
                                  String itemDisplayName=((Element)node).selectSingleNode("itemDisplayName").getText();
                                  String temp = data.getString("displayName");
                                  data.remove("displayName");
                                  data.put(temp, itemDisplayName);
                               }
                            }
                            */
                            data.put("sourceFieldselector", fieldinstance.getSelector());
                            data.put("sourceFieldName", fieldName);
                            data.put("sourceFieldType", r.getID());
                            if (listitems.has(key)) {
                                JSONArray temp = listitems.getJSONArray(key).put(data);
                                listitems.put(key, temp);
                            } else {
                                JSONArray temp = new JSONArray();
                                temp.put(data);
                                listitems.put(key, temp);
                            }
                        }
                    }

                } else {
                    pagination.put(node.getName(), node.getText());
                }
            }
        }
        out.put("pagination", pagination);
        out.put("listItems", listitems);
        return out;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Connection problem" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    }
}

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 w w  .  j  a  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  w  ww  .j a v  a 2 s. 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
 * //ww  w  .j  a va  2s  .  co 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.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;/* ww w .  j a  v  a  2  s .  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.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 {// www. j  a  va 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.ja va2  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());
    }
}