Search in sources :

Example 11 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class ConfiguredVocabStorage method updateJSON.

public void updateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, JSONObject jsonObject, JSONObject restrictions, Record thisr, String savePath) throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        String csid = savePath.split("/")[3];
        Map<String, Document> body = new HashMap<String, Document>();
        for (String section : r.getServicesRecordPathKeys()) {
            String path = r.getServicesRecordPath(section);
            String[] record_path = path.split(":", 2);
            String[] tag_path = record_path[1].split(",", 2);
            Document temp = createEntry(section, tag_path[0], tag_path[1], jsonObject, null, null, thisr, false);
            if (temp != null) {
                body.put(record_path[0], temp);
            // log.info(temp.asXML());
            }
        }
        handleHierarchyPayloadSend(thisr, body, jsonObject, csid);
        ReturnedMultipartDocument out = conn.getMultipartXMLDocument(RequestMethod.PUT, savePath, body, creds, cache);
        if (out.isErrorStatus()) {
            if (out.isTransactionFailedStatus()) {
                throw new UnderlyingStorageException(VOCABULARY_UPDATE_FAILED_MESSAGE + ": " + out.TRANSACTION_FAILED_MESSAGE, out.getStatus(), savePath);
            } else {
                throw new UnderlyingStorageException(VOCABULARY_UPDATE_FAILED_MESSAGE, out.getStatus(), savePath);
            }
        }
        // subrecord update
        for (FieldSet fs : thisr.getAllSubRecords("PUT")) {
            Record sr = fs.usesRecordId();
            // get list of existing subrecords
            JSONObject existingcsid = new JSONObject();
            JSONObject updatecsid = new JSONObject();
            JSONArray createcsid = new JSONArray();
            String getPath = savePath + "/" + sr.getServicesURL();
            Integer subcount = 0;
            String firstfile = "";
            while (!getPath.equals("")) {
                JSONObject data = getListView(creds, cache, getPath, sr.getServicesListPath(), "csid", false, sr);
                String[] filepaths = (String[]) data.get("listItems");
                subcount += filepaths.length;
                if (firstfile.equals("") && subcount != 0) {
                    firstfile = filepaths[0];
                }
                for (String uri : filepaths) {
                    String path = uri;
                    if (path != null && path.startsWith("/"))
                        path = path.substring(1);
                    existingcsid.put(path, "original");
                }
                if (data.has("pagination")) {
                    Integer ps = Integer.valueOf(data.getJSONObject("pagination").getString("pageSize"));
                    Integer pn = Integer.valueOf(data.getJSONObject("pagination").getString("pageNum"));
                    Integer ti = Integer.valueOf(data.getJSONObject("pagination").getString("totalItems"));
                    if (ti > (ps * (pn + 1))) {
                        JSONObject pgRestrictions = new JSONObject();
                        pgRestrictions.put("pageSize", Integer.toString(ps));
                        pgRestrictions.put("pageNum", Integer.toString(pn + 1));
                        getPath = getRestrictedPath(getPath, pgRestrictions, sr.getServicesSearchKeyword(), "", false, "");
                    // need more values
                    } else {
                        getPath = "";
                    }
                }
            }
            // how does that compare to what we need
            if (sr.isType("authority")) {
                if (fs instanceof Field) {
                    JSONObject subdata = new JSONObject();
                    // loop thr jsonObject and find the fields I need
                    for (FieldSet subfs : sr.getAllFieldTopLevel("PUT")) {
                        String key = subfs.getID();
                        if (jsonObject.has(key)) {
                            subdata.put(key, jsonObject.get(key));
                        }
                    }
                    if (subcount == 0) {
                        // create
                        createcsid.put(subdata);
                    } else {
                        // update - there should only be one
                        String firstcsid = firstfile;
                        updatecsid.put(firstcsid, subdata);
                        existingcsid.remove(firstcsid);
                    }
                } else if (fs instanceof Group) {
                    // subrecorddata.put(value);
                    if (jsonObject.has(fs.getID())) {
                        Object subdata = jsonObject.get(fs.getID());
                        if (subdata instanceof JSONObject) {
                            if (((JSONObject) subdata).has("_subrecordcsid")) {
                                String thiscsid = ((JSONObject) subdata).getString("_subrecordcsid");
                                // update
                                if (existingcsid.has(thiscsid)) {
                                    updatecsid.put(thiscsid, (JSONObject) subdata);
                                    existingcsid.remove(thiscsid);
                                } else {
                                    // something has gone wrong... best just create it from scratch
                                    createcsid.put(subdata);
                                }
                            } else {
                                // create
                                createcsid.put(subdata);
                            }
                        }
                    }
                } else {
                    // need to find if we have csid's for each one
                    if (jsonObject.has(fs.getID())) {
                        Object subdata = jsonObject.get(fs.getID());
                        if (subdata instanceof JSONArray) {
                            JSONArray subarray = (JSONArray) subdata;
                            for (int i = 0; i < subarray.length(); i++) {
                                JSONObject subrecord = subarray.getJSONObject(i);
                                if (subrecord.has("_subrecordcsid")) {
                                    String thiscsid = subrecord.getString("_subrecordcsid");
                                    // update
                                    if (existingcsid.has(thiscsid)) {
                                        updatecsid.put(thiscsid, (JSONObject) subdata);
                                        existingcsid.remove(thiscsid);
                                    } else {
                                        // something has gone wrong... best just create it from scratch
                                        createcsid.put(subdata);
                                    }
                                } else {
                                    // create
                                    createcsid.put(subdata);
                                }
                            }
                        }
                    }
                }
                String savePathSr = savePath + "/" + sr.getServicesURL() + "/";
                // do delete JSONObject existingcsid = new JSONObject();
                Iterator<String> rit = existingcsid.keys();
                while (rit.hasNext()) {
                    String key = rit.next();
                    deleteJSON(root, creds, cache, key, savePathSr, sr);
                }
                // do update JSONObject updatecsid = new JSONObject();
                Iterator<String> keys = updatecsid.keys();
                while (keys.hasNext()) {
                    String key = keys.next();
                    JSONObject value = updatecsid.getJSONObject(key);
                    String thissave = savePathSr + key;
                    updateJSON(root, creds, cache, value, new JSONObject(), sr, thissave);
                // updateJSON( root, creds, cache, key,  value, sr, savePathSr);
                }
                // do create JSONArray createcsid = new JSONArray();
                for (int i = 0; i < createcsid.length(); i++) {
                    JSONObject value = createcsid.getJSONObject(i);
                    subautocreateJSON(root, creds, cache, sr, value, savePathSr);
                }
            }
        }
    // XXX dont currently update the shortID???
    // cache.setCached(getClass(),new String[]{"shortId",vocab,filePath.split("/")[1]},shortId);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Connection exception " + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Cannot parse surrounding JSON " + e.getLocalizedMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnimplementedException("UnsupportedEncodingException" + e.getLocalizedMessage(), e);
    }
}
Also used : Group(org.collectionspace.chain.csp.schema.Group) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Document(org.dom4j.Document) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) Field(org.collectionspace.chain.csp.schema.Field) FieldSet(org.collectionspace.chain.csp.schema.FieldSet) JSONObject(org.json.JSONObject) Record(org.collectionspace.chain.csp.schema.Record) JSONObject(org.json.JSONObject) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 12 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class AuthorizationStorage method getPaths.

/**
 * Returns a list of csid's from a certain type of record
 */
@Override
@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);
    }
}
Also used : Node(org.dom4j.Node) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) Document(org.dom4j.Document) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 13 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class AuthorizationStorage method simpleRetrieveJSONFullPath.

public JSONObject simpleRetrieveJSONFullPath(CSPRequestCredentials creds, CSPRequestCache cache, String filePath, Record thisr) throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        JSONObject out = new JSONObject();
        if (thisr.isMultipart()) {
            ReturnedMultipartDocument doc = conn.getMultipartXMLDocument(RequestMethod.GET, filePath, null, creds, cache);
            if ((doc.getStatus() < 200 || doc.getStatus() >= 300))
                throw new UnderlyingStorageException("Does not exist ", doc.getStatus(), filePath);
            for (String section : thisr.getServicesRecordPathKeys()) {
                String path = thisr.getServicesRecordPath(section);
                String[] parts = path.split(":", 2);
                convertToJson(out, doc.getDocument(parts[0]), thisr, "GET", section, "", "");
            }
        } else {
            ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET, filePath, null, creds, cache);
            if ((doc.getStatus() < 200 || doc.getStatus() >= 300)) {
                if (doc.getStatus() == 401) {
                    throw new UnauthorizedException("Username and/or password are invalid.", doc.getStatus(), filePath);
                } else if (doc.getStatus() == 409) {
                    throw new ConflictException("Conflict with request. The user's tenant may be disabled. Contact your CollectionSpace administrator.", doc.getStatus(), filePath);
                } else {
                    String status = Integer.toString(doc.getStatus());
                    throw new UnderlyingStorageException("Does not exist ", doc.getStatus(), filePath);
                }
            }
            convertToJson(out, doc.getDocument(), thisr, "GET", "common", "");
        }
        return out;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e);
    }
}
Also used : ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) JSONObject(org.json.JSONObject) ConflictException(org.collectionspace.csp.api.persistence.ConflictException) UnauthorizedException(org.collectionspace.csp.api.persistence.UnauthorizedException) JSONException(org.json.JSONException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 14 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class AuthorizationStorage method getPathsJSON.

/**
 * Gets a list of csids of a certain type of record together with the pagination info
 * permissions might need to break the mold tho.
 */
@Override
@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") || r.getID().equals("batch")) {
            String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), "", false, "");
            JSONObject data = getListView(creds, cache, path, 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();
        String listItemPath = r.getServicesListPath();
        String[] listItemPathElements = listItemPath.split("/");
        if (listItemPathElements.length != 2) {
            throw new RuntimeException("Illegal list item path " + listItemPath);
        }
        String listNodeName = listItemPathElements[0];
        String listItemNodeName = listItemPathElements[1];
        String listNodeChildrenSelector = "/" + listNodeName + "/*";
        List<Node> nodes = list.selectNodes(listNodeChildrenSelector);
        for (Node node : nodes) {
            if (listItemNodeName.equals(node.getName())) {
                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);
    }
}
Also used : Node(org.dom4j.Node) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) Document(org.dom4j.Document) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) JSONObject(org.json.JSONObject) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 15 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class AuthorizationStorage method deleteJSON.

/**
 * Remove an object in the Service Layer.
 */
@Override
public void deleteJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath) throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        int status = 0;
        if (r.hasDeleteMethod()) {
            // get all data to post back
            // hopefully the filepath we have is the filepath to get the data from
            Document doc = null;
            try {
                doc = simpleRetrieveXML(creds, cache, filePath + "/");
                String nodepath = "/" + r.getServicesListPath() + "/*";
                List<Node> nodes = doc.selectNodes(nodepath);
                if (nodes.size() > 0) {
                    status = 201;
                    status = conn.getNone(RequestMethod.DELETE, filePath, null, creds, cache);
                // post it back to delete it
                /*
						log.info("TRYING TO DELETE ACCOUNTROLE");
						log.info(doc.asXML());
						log.info(filePath+"?_method=delete");
						ReturnedURL url = null;
						url = conn.getURL(RequestMethod.POST, filePath+"?_method=delete", doc, creds, cache);
						status = url.getStatus();
						//status=conn.getNone(RequestMethod.POST,r.getServicesURL()+"/"+filePath+"?_method=delete",doc,creds,cache);
						 	
	*/
                } else {
                    // if we didn't need to delete it because there was nothing there then everything was good
                    status = 201;
                }
            } catch (ExistException ex) {
                // ignore as nothign to delete if nothing exists
                status = 201;
            }
        } else {
            status = conn.getNone(RequestMethod.DELETE, r.getServicesURL() + "/" + filePath, null, creds, cache);
        }
        if (// XXX CSPACE-73, should be 404
        status > 299 || status < 200)
            throw new UnderlyingStorageException("Service layer exception status=" + status, status, r.getServicesURL() + "/" + filePath);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Service layer exception", e);
    }
}
Also used : Node(org.dom4j.Node) Document(org.dom4j.Document) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Aggregations

ConnectionException (org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)39 UnderlyingStorageException (org.collectionspace.csp.api.persistence.UnderlyingStorageException)37 JSONException (org.json.JSONException)28 ReturnedDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument)26 Document (org.dom4j.Document)24 JSONObject (org.json.JSONObject)23 ReturnedMultipartDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument)21 UnsupportedEncodingException (java.io.UnsupportedEncodingException)14 ArrayList (java.util.ArrayList)11 Node (org.dom4j.Node)11 FieldSet (org.collectionspace.chain.csp.schema.FieldSet)10 HashMap (java.util.HashMap)8 Field (org.collectionspace.chain.csp.schema.Field)8 Record (org.collectionspace.chain.csp.schema.Record)8 ExistException (org.collectionspace.csp.api.persistence.ExistException)8 UnimplementedException (org.collectionspace.csp.api.persistence.UnimplementedException)8 JSONArray (org.json.JSONArray)8 ReturnedURL (org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL)6 Group (org.collectionspace.chain.csp.schema.Group)6 IOException (java.io.IOException)3