Example usage for org.dom4j Node getText

List of usage examples for org.dom4j Node getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text of this node.

Usage

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
 *//*  ww  w.  j  a v a2 s.  c  om*/
@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 ww  . j a v a  2  s.  co 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 . j a  v a2s. c  om
 * @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 ww  w . ja  va2  s  .co  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 w  w.  ja v  a2 s . c  om
 * 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.GenericStorage.java

License:Educational Community License

public void handleHierarchyPayloadRetrieve(Record r, ReturnedMultipartDocument doc, JSONObject out,
        String thiscsid) throws JSONException {
    if (r.hasHierarchyUsed("screen")) {
        //lets do relationship stuff...
        Document list = doc.getDocument("relations-common-list");
        if (list == null)
            return;
        List<Node> nodes = list.selectNodes("/relations-common-list/*");

        for (Node node : nodes) {
            if (node.matches("/relations-common-list/relation-list-item")) {
                //String test = node.asXML();
                String relationshipType = node.selectSingleNode("relationshipType").getText();
                // Be forgiving while waiting for services to complete code.
                Node relationshipMetaTypeNode = node.selectSingleNode("relationshipMetaType");
                String relationshipMetaType = (relationshipMetaTypeNode != null)
                        ? relationshipMetaTypeNode.getText()
                        : "";
                //String subjCSID = node.selectSingleNode("subjectCsid").getText();
                //String objCSID = node.selectSingleNode("objectCsid").getText();
                String subjURI = "";
                String subjCSID = "";
                String subjDocType = "";
                if (node.selectSingleNode("subject/uri") != null) {
                    subjCSID = node.selectSingleNode("subject/csid").getText();
                    subjDocType = node.selectSingleNode("subject/documentType").getText();
                    subjURI = node.selectSingleNode("subject/refName").getText();
                }// w  w w. ja  v a 2 s.co m
                String objRefName = "";
                String objDocType = "";
                String objCSID = "";
                if (node.selectSingleNode("object/uri") != null) {
                    objCSID = node.selectSingleNode("object/csid").getText();
                    objDocType = node.selectSingleNode("object/documentType").getText();
                    objRefName = node.selectSingleNode("object/refName").getText();
                }

                String relateduri = objRefName;
                String relatedcsid = objCSID;
                String relatedser = objDocType;

                if (r.getSpec().hasRelationshipByPredicate(relationshipType)) {
                    Relationship rel = r.getSpec().getRelationshipByPredicate(relationshipType);
                    Relationship newrel = rel;
                    //is this subject or object
                    if (thiscsid.equals(objCSID)) {
                        //should we invert
                        if (r.getSpec().hasRelationshipInverse(rel.getID())) {
                            newrel = r.getSpec().getInverseRelationship(rel.getID());
                            relateduri = subjURI;
                            relatedcsid = subjCSID;
                            relatedser = subjDocType;
                        }
                    }

                    String metaTypeField = newrel.getMetaTypeField();

                    if (newrel.getObject().equals("n")) { //array
                        JSONObject subdata = new JSONObject();
                        subdata.put(newrel.getChildName(), relateduri);
                        if (!StringUtils.isEmpty(metaTypeField)) {
                            subdata.put(metaTypeField, relationshipMetaType);
                        }
                        if (out.has(newrel.getID())) {
                            out.getJSONArray(newrel.getID()).put(subdata);
                        } else {
                            JSONArray relList = new JSONArray();
                            relList.put(subdata);
                            out.put(newrel.getID(), relList);
                        }
                    } else {//string
                        out.put(newrel.getID(), relateduri);
                        if (!StringUtils.isEmpty(metaTypeField)) {
                            out.put(metaTypeField, relationshipMetaType);
                        }
                        if (newrel.showSiblings()) {
                            out.put(newrel.getSiblingChild(), relatedser + "/" + relatedcsid);
                            //out.put(newrel.getSiblingChild(), relateduri);
                        }
                    }
                }
            }
        }
    }
}

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