Search in sources :

Example 66 with UnderlyingStorageException

use of org.collectionspace.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.

the class RecordCreateUpdate method store_set.

private void store_set(Storage storage, UIRequest request, String path) throws UIException {
    try {
        JSONObject restrictions = new JSONObject();
        JSONObject data = request.getJSONBody();
        if (this.base.equals("role")) {
            JSONObject fields = data.optJSONObject("fields");
            if ((fields.optString("roleName") == null || fields.optString("roleName").equals("")) && fields.optString("displayName") != null) {
                String test = fields.optString("displayName");
                test = test.toUpperCase();
                test.replaceAll("\\W", "_");
                fields.put("roleName", "xROLE_" + test);
                data.put("fields", fields);
            }
            // Note that creating a role does not impact things until we assign it
            if (!create) {
                ResponseCache.clearCache(ResponseCache.USER_PERMS_CACHE);
            }
        }
        if (this.record.getID().equals("media")) {
            JSONObject fields = data.optJSONObject("fields");
            // Handle linked media references
            if (!fields.has("blobCsid") || StringUtils.isEmpty(fields.getString("blobCsid"))) {
                // Can consider mapping srcUri to this if want to clean that up
                if (fields.has("sourceUrl")) {
                    // We have a source - see where it is from
                    String uri = fields.getString("sourceUrl");
                    if (uri.contains(BLOBS_SERVICE_URL_PATTERN)) {
                        // This is an uploaded blob, so just pull the csid and set into blobCsid
                        // Split to get CSID
                        String[] parts = uri.split(BLOBS_SERVICE_URL_PATTERN);
                        // Strip off anything trailing the CSID
                        String[] bits = parts[1].split("/");
                        fields.put("blobCsid", bits[0]);
                    } else {
                        // This must be an external Url source
                        // External Source is handled as params to the CREATE/UPDATE of the media record
                        restrictions.put(Record.BLOB_SOURCE_URL, uri);
                        // Tell the Services to delete the original after creating derivatives
                        restrictions.put(Record.BLOB_PURGE_ORIGINAL, Boolean.toString(true));
                    }
                    fields.remove("sourceUrl");
                    data.put("fields", fields);
                }
            }
        }
        if (this.record.getID().equals("output")) {
            // 
            // Invoke a report
            // 
            ReportUtils.invokeReport(this, storage, request, path);
        } else if (this.record.getID().equals("batchoutput")) {
            // do a read instead of a create as reports are special and evil
            JSONObject fields = data.optJSONObject("fields");
            JSONObject payload = new JSONObject();
            payload.put("mode", "single");
            if (fields.has("mode")) {
                payload.put("mode", fields.getString("mode"));
            }
            if (fields.has("docType")) {
                String type = spec.getRecordByWebUrl(fields.getString("docType")).getServicesTenantSg();
                payload.put("docType", type);
            }
            if (fields.has("singleCSID")) {
                payload.put("singleCSID", fields.getString("singleCSID"));
            } else if (fields.has("groupCSID")) {
                payload.put("singleCSID", fields.getString("csid"));
            }
            JSONObject out = storage.retrieveJSON(base + "/" + path, payload);
            byte[] data_array = (byte[]) out.get("getByteBody");
            String contentDisp = out.has("contentdisposition") ? out.getString("contentdisposition") : null;
            request.sendUnknown(data_array, out.getString("contenttype"), contentDisp);
            // Ensure we do not cache report output.
            request.setCacheMaxAgeSeconds(0);
            // request.sendJSONResponse(out);
            request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE);
        } else {
            // 
            // <Please document this clause.>
            // 
            FieldSet displayNameFS = this.record.getDisplayNameField();
            String displayNameFieldName = (displayNameFS != null) ? displayNameFS.getID() : null;
            boolean remapDisplayName = false;
            String remapDisplayNameValue = null;
            boolean quickie = false;
            if (create) {
                quickie = (data.has("_view") && data.getString("_view").equals("autocomplete"));
                remapDisplayName = quickie && !"displayName".equals(displayNameFieldName);
                // Check to see if displayName field needs remapping from UI
                if (remapDisplayName) {
                    // Need to map the field for displayName, and put it into a proper structure
                    JSONObject fields = data.getJSONObject("fields");
                    remapDisplayNameValue = fields.getString("displayName");
                    if (remapDisplayNameValue != null) {
                        // This needs generalizing, in case the remapped name is nested
                        /*
							 * From vocab handling where we know where the termDisplayName is
							FieldSet parentTermGroup = (FieldSet)displayNameFS.getParent();
							JSONArray parentTermInfoArray = new JSONArray();
							JSONObject termInfo = new JSONObject();
							termInfo.put(displayNameFieldName, remapDisplayNameValue);
							parentTermInfoArray.put(termInfo);
							*/
                        fields.put(displayNameFieldName, remapDisplayNameValue);
                        fields.remove("displayName");
                    }
                }
                // REM - We needed a way to send query params, so I'm adding "restrictions" here
                path = sendJSON(storage, null, data, restrictions);
                data.put("csid", path);
                data.getJSONObject("fields").put("csid", path);
            // Is this needed???
            /*
					String refName = data.getJSONObject("fields").getString("refName");
					data.put("urn", refName);
					data.getJSONObject("fields").put("urn", refName);
					// This seems wrong - especially when we create from existing.
					if(remapDisplayName){
						JSONObject newdata = new JSONObject();
						newdata.put("urn", refName);
						newdata.put("displayName",quickieDisplayName);
						data = newdata;
					}
					 */
            } else {
                path = sendJSON(storage, path, data, restrictions);
            }
            if (path == null) {
                throw new UIException("Insufficient data for create (no fields?)");
            }
            if (this.base.equals("role")) {
                assignPermissions(storage, path, data);
            }
            if (this.base.equals("termlist")) {
                assignTerms(storage, path, data);
            }
            // We do a GET now to read back what we created.
            data = reader.getJSON(storage, path);
            if (quickie) {
                JSONObject newdata = new JSONObject();
                JSONObject fields = data.getJSONObject("fields");
                String displayName = fields.getString(remapDisplayName ? displayNameFieldName : "displayName");
                newdata.put("displayName", remapDisplayNameValue);
                String refName = fields.getString("refName");
                newdata.put("urn", refName);
                data = newdata;
            }
            request.sendJSONResponse(data);
            request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE);
            if (create)
                request.setSecondaryRedirectPath(new String[] { url_base, path });
        }
    } catch (JSONException x) {
        throw new UIException("Failed to parse JSON: " + x, x);
    } catch (ExistException x) {
        UIException uiexception = new UIException(x.getMessage(), 0, "", x);
        request.sendJSONResponse(uiexception.getJSON());
    } catch (UnimplementedException x) {
        throw new UIException("Unimplemented exception: " + x, x);
    } catch (UnderlyingStorageException x) {
        UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x);
        request.setStatus(x.getStatus());
        request.setFailure(true, uiexception);
        request.sendJSONResponse(uiexception.getJSON());
    } catch (Exception x) {
        throw new UIException(x);
    }
}
Also used : FieldSet(org.collectionspace.chain.csp.schema.FieldSet) JSONObject(org.json.JSONObject) UIException(org.collectionspace.csp.api.ui.UIException) JSONException(org.json.JSONException) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException) JSONException(org.json.JSONException) UIException(org.collectionspace.csp.api.ui.UIException) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ConfigException(org.collectionspace.chain.csp.config.ConfigException)

Example 67 with UnderlyingStorageException

use of org.collectionspace.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.

the class RecordRead method store_get.

private void store_get(Storage storage, UIRequest request, String path) throws Exception {
    // Get the data
    try {
        if (record.isType("blob")) {
            JSONObject outputJSON = getJSON(storage, path);
            String content = outputJSON.getString("contenttype");
            String contentDisp = outputJSON.has("contentdisposition") ? outputJSON.getString("contentdisposition") : null;
            byte[] bob = (byte[]) outputJSON.get("getByteBody");
            String getByteBody = bob.toString();
            request.sendUnknown(getByteBody, content, contentDisp);
        } else if (record.getID().equals("output")) {
            // 
            // Invoke a report
            // 
            ReportUtils.invokeReport(this, storage, request, path);
        } else if (record.getID().equals("batchoutput")) {
            String[] bits = path.split("/");
            JSONObject payload = new JSONObject();
            if (bits.length > 1 && !bits[1].equals("output")) {
                payload.put("mode", "single");
                String type = spec.getRecordByWebUrl(bits[1]).getServicesTenantDoctype(false);
                payload.put("docType", type);
                payload.put("singleCSID", bits[2]);
                path = bits[0];
            }
            JSONObject out = storage.retrieveJSON(base + "/" + path, payload);
            request.sendJSONResponse(out);
        } else {
            JSONObject outputJSON = getJSON(storage, path);
            outputJSON.put("csid", path);
            // Write the requested JSON out
            request.sendJSONResponse(outputJSON);
        }
    } catch (JSONException e1) {
        throw new UIException("Cannot add csid", e1);
    } catch (ExistException e) {
        throw new UIException("Cannot add csid", e);
    } catch (UnimplementedException e) {
        throw new UIException("Cannot add csid", e);
    } catch (UnderlyingStorageException e) {
        throw new UIException("Cannot add csid", e);
    }
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) UIException(org.collectionspace.csp.api.ui.UIException) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException)

Example 68 with UnderlyingStorageException

use of org.collectionspace.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.

the class RecordRelated method store_get.

private void store_get(Storage storage, UIRequest ui, String path) throws UIException {
    try {
        JSONObject restriction = new JSONObject();
        restriction.put("src", base + "/" + path);
        String key = "items";
        Set<String> args = ui.getAllRequestArgument();
        for (String restrict : args) {
            if (ui.getRequestArgument(restrict) != null) {
                String value = ui.getRequestArgument(restrict);
                // }
                if (restrict.equals(WebMethod.PAGE_SIZE_PARAM) || restrict.equals(WebMethod.PAGE_NUM_PARAM) || restrict.equals("keywords")) {
                    restriction.put(restrict, value);
                } else if (restrict.equals(WebMethod.SEARCH_QUERY_PARAM)) {
                // ignore - someone was doing something odd
                } else {
                    // XXX I would so prefer not to restrict and just pass
                    // stuff up but I know it will cause issues later
                    restriction.put("queryTerm", restrict);
                    restriction.put("queryString", value);
                }
            }
        }
        // Get the data
        JSONObject outputJSON = new JSONObject();
        JSONObject recordtypes = getRelations(storage, restriction, new JSONObject(), new JSONArray());
        outputJSON.put("relations", recordtypes);
        try {
            outputJSON.put("csid", path);
        } catch (JSONException e1) {
            throw new UIException("Cannot add csid", e1);
        }
        // Write the requested JSON out
        ui.sendJSONResponse(outputJSON);
    } catch (JSONException e) {
        throw new UIException("JSONException during store_get", e);
    } catch (ExistException e) {
        throw new UIException("ExistException during store_get", e);
    } catch (UnimplementedException e) {
        throw new UIException("UnimplementedException during store_get", e);
    } catch (UnderlyingStorageException x) {
        UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x);
        ui.sendJSONResponse(uiexception.getJSON());
    }
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) UIException(org.collectionspace.csp.api.ui.UIException) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException)

Example 69 with UnderlyingStorageException

use of org.collectionspace.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.

the class RecordSearchList method search_or_list.

/**
 * This function is the general function that calls the correct funtions to
 * get all the data that the UI requested and get it in the correct format
 * for the UI.
 *
 * @param {Storage} storage The type of storage requested (e.g.
 * RecordStorage, AuthorizationStorage,...)
 * @param {UIRequest} ui The request from the ui to which we send a
 * response.
 * @param {String} param If a querystring has been added to the
 * URL(e.g.'?query='), it will be in this param
 * @param {String} pageSize The amount of results per page requested.
 * @param {String} pageNum The amount of pages requested.
 * @throws UIException
 */
private void search_or_list(Storage storage, UIRequest ui, String path) throws UIException {
    try {
        JSONObject restrictedkey = GenericSearch.setRestricted(ui, null, null, null, (mode == MODE_SEARCH), this.r);
        JSONObject restriction = restrictedkey.getJSONObject("restriction");
        String key = restrictedkey.getString("key");
        JSONObject results = getResults(ui, storage, restriction, key, path);
        // cache for record traverser
        if (results.has("pagination") && results.getJSONObject("pagination").has("separatelists")) {
            GenericSearch.createTraverser(ui, this.r.getID(), "", results, restriction, key, 1);
        }
        ui.sendJSONResponse(results);
    } catch (JSONException e) {
        throw new UIException("JSONException during search_or_list", e);
    } catch (ExistException e) {
        throw new UIException("ExistException during search_or_list", e);
    } catch (UnimplementedException e) {
        throw new UIException("UnimplementedException during search_or_list", e);
    } catch (UnderlyingStorageException x) {
        UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x);
        ui.sendJSONResponse(uiexception.getJSON());
    }
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) UIException(org.collectionspace.csp.api.ui.UIException) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException)

Example 70 with UnderlyingStorageException

use of org.collectionspace.csp.api.persistence.UnderlyingStorageException in project application by collectionspace.

the class RecordSearchList method generateMiniRecord.

/**
 * Retrieve the mini summary information e.g. summary and number and append
 * the csid and recordType to it
 *
 * @param {Storage} storage Type of storage (e.g. AuthorizationStorage,
 * RecordStorage,...)
 * @param {String} type The type of record requested (e.g. permission)
 * @param {String} csid The csid of the record
 * @return {JSONObject} The JSON string containing the mini record
 * @throws ExistException
 * @throws UnimplementedException
 * @throws UnderlyingStorageException
 * @throws JSONException
 */
private JSONObject generateMiniRecord(Storage storage, String type, String csid) throws JSONException {
    String postfix = "list";
    if (this.mode == MODE_SEARCH) {
        postfix = "search";
    }
    JSONObject restrictions = new JSONObject();
    JSONObject out = new JSONObject();
    try {
        if (csid == null || csid.equals("")) {
            return out;
        }
        out = storage.retrieveJSON(type + "/" + csid + "/view/" + postfix, restrictions);
        out.put("csid", csid);
        String recordtype = null;
        if (!r.isType("searchall")) {
            recordtype = type_to_url.get(type);
        } else {
            JSONObject summarylist = out.getJSONObject("summarylist");
            String uri = summarylist.getString("uri");
            if (uri != null && uri.startsWith("/")) {
                uri = uri.substring(1);
            }
            String[] parts = uri.split("/");
            String recordurl = parts[0];
            Record itemr = r.getSpec().getRecordByServicesUrl(recordurl);
            if (itemr == null) {
                String docType = summarylist.getString("docType");
                itemr = r.getSpec().getRecordByServicesDocType(docType);
            }
            if (itemr == null) {
                recordtype = UNKNOWN_RECORD_TYPE;
                log.warn("Could not get record type for record with services URI " + uri);
            } else {
                recordtype = type_to_url.get(itemr.getID());
                String refName = null;
                if (summarylist.has("refName")) {
                    refName = summarylist.getString("refName");
                }
                // For an authority item (i.e. an item in a vocabulary),
                // include the name of its parent vocabulary in a
                // "namespace" value within the mini summary.
                RefName.AuthorityItem item = null;
                if (refName != null) {
                    item = RefName.AuthorityItem.parse(refName);
                }
                // authority item refName, then include the "namespace" value.
                if (item != null) {
                    String namespace = item.getParentShortIdentifier();
                    if (namespace != null) {
                        out.put("namespace", namespace);
                    } else {
                        log.warn("Could not get vocabulary namespace for record with services URI " + uri);
                    }
                }
            }
        }
        out.put("recordtype", recordtype);
        // CSPACE-2894
        if (this.r.getID().equals("permission")) {
            String summary = out.getString("summary");
            String name = Generic.ResourceNameUI(this.r.getSpec(), summary);
            if (name.contains(WORKFLOW_SUB_RESOURCE)) {
                return null;
            }
            out.put("summary", name);
            out.put("display", Generic.getPermissionView(this.r.getSpec(), summary));
        }
    } catch (ExistException e) {
        out.put("csid", csid);
        out.put("isError", true);
        JSONObject msg = new JSONObject();
        msg.put("severity", "error");
        msg.put("message", "Exist Exception:" + e.getMessage());
        JSONArray msgs = new JSONArray();
        msgs.put(msg);
        out.put("messages", msgs);
    } catch (UnimplementedException e) {
        out.put("csid", csid);
        out.put("isError", true);
        JSONObject msg = new JSONObject();
        msg.put("severity", "error");
        msg.put("message", "Exist Exception:" + e.getMessage());
        JSONArray msgs = new JSONArray();
        msgs.put(msg);
        out.put("messages", msgs);
    } catch (UnderlyingStorageException e) {
        out.put("csid", csid);
        out.put("isError", true);
        JSONObject msg = new JSONObject();
        msg.put("severity", "error");
        msg.put("message", "Exist Exception:" + e.getMessage());
        JSONArray msgs = new JSONArray();
        msgs.put(msg);
        out.put("messages", msgs);
    }
    return out;
}
Also used : JSONObject(org.json.JSONObject) RefName(org.collectionspace.services.common.api.RefName) JSONArray(org.json.JSONArray) Record(org.collectionspace.chain.csp.schema.Record) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException)

Aggregations

UnderlyingStorageException (org.collectionspace.csp.api.persistence.UnderlyingStorageException)108 JSONObject (org.json.JSONObject)75 JSONException (org.json.JSONException)73 ExistException (org.collectionspace.csp.api.persistence.ExistException)57 UnimplementedException (org.collectionspace.csp.api.persistence.UnimplementedException)55 UIException (org.collectionspace.csp.api.ui.UIException)40 ConnectionException (org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)39 JSONArray (org.json.JSONArray)34 ReturnedDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument)30 Document (org.dom4j.Document)29 ReturnedMultipartDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument)23 FieldSet (org.collectionspace.chain.csp.schema.FieldSet)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)16 Field (org.collectionspace.chain.csp.schema.Field)14 Record (org.collectionspace.chain.csp.schema.Record)14 ArrayList (java.util.ArrayList)11 HashMap (java.util.HashMap)11 Node (org.dom4j.Node)10 ReturnedURL (org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL)9 IOException (java.io.IOException)7