Search in sources :

Example 46 with Record

use of org.collectionspace.chain.csp.schema.Record in project application by collectionspace.

the class XmlJsonConversion method addFieldToJson.

private static void addFieldToJson(JSONObject out, Element root, Field field, String operation, JSONObject tempSon, String csid, String ims_url) throws JSONException {
    String use_csid = field.useCsid();
    if (use_csid != null) {
        if (field.useCsidField() != null) {
            csid = tempSon.getString(field.useCsidField());
        }
        out.put(field.getID(), csid_value(csid, field.useCsid(), ims_url));
    } else {
        Element el = root;
        if (field.getUIType().startsWith("groupfield") && field.getUIType().contains("selfrenderer")) {
            String[] parts = field.getUIType().split("/");
            Record subitems = field.getRecord().getSpec().getRecordByServicesUrl(parts[1]);
            for (FieldSet fs : subitems.getAllServiceFieldTopLevel(operation, "common")) {
                addFieldSetToJson(out, el, fs, operation, tempSon, csid, ims_url);
            }
            return;
        }
        el = getFieldNodeEl(root, field);
        if (el == null) {
            return;
        }
        addExtraToJson(out, el, field, tempSon);
        Object val = el.getText();
        if (field.getUIType().startsWith("groupfield")) {
            String[] parts = field.getUIType().split("/");
            Record subitems = field.getRecord().getSpec().getRecordByServicesUrl(parts[1]);
            JSONObject temp = new JSONObject();
            for (FieldSet fs : subitems.getAllServiceFieldTopLevel(operation, "common")) {
                addFieldSetToJson(temp, el, fs, operation, tempSon, csid, ims_url);
            }
            out.put(field.getID(), temp);
        } else if (field.getDataType().equals("boolean")) {
            out.put(field.getID(), (Boolean.parseBoolean((String) val) ? true : false));
        } else {
            out.put(field.getID(), val);
        }
        tempSon = addtemp(tempSon, field.getID(), val);
    }
}
Also used : FieldSet(org.collectionspace.chain.csp.schema.FieldSet) JSONObject(org.json.JSONObject) Element(org.dom4j.Element) Record(org.collectionspace.chain.csp.schema.Record) JSONObject(org.json.JSONObject)

Example 47 with Record

use of org.collectionspace.chain.csp.schema.Record in project application by collectionspace.

the class VocabulariesRead method getRefObjs.

/**
 * Returns all the objects that are linked to a vocabulary item
 * @param storage
 * @param path
 * @return
 * @throws ExistException
 * @throws UnimplementedException
 * @throws UnderlyingStorageException
 * @throws JSONException
 */
@SuppressWarnings("unchecked")
private void getRefObjs(Storage storage, String path, JSONObject out, String itemsKey, boolean addPagination, JSONObject restrictions) throws JSONException {
    JSONArray items = new JSONArray();
    try {
        JSONObject refObjs = storage.retrieveJSON(path + "/refObjs", restrictions);
        if (refObjs != null) {
            if (refObjs.has("items")) {
                JSONArray ritems = refObjs.getJSONArray("items");
                for (int i = 0; i < ritems.length(); i++) {
                    JSONObject in = ritems.getJSONObject(i);
                    // JSONObject in=ritems.getJSONObject(field);
                    String rt = in.getString("sourceFieldType");
                    Record rec = this.spec.getRecordByServicesDocType(rt);
                    // as the key.
                    if (rec == null) {
                        if (in.has("summarylist")) {
                            JSONObject summaryList = in.getJSONObject("summarylist");
                            if (summaryList.has("uri")) {
                                String uri = summaryList.getString("uri");
                                if (Tools.notBlank(uri)) {
                                    String recordtypekey = uri.split("/")[0];
                                    if (Tools.notBlank(recordtypekey)) {
                                        rec = this.spec.getRecordByServicesUrl(recordtypekey);
                                    }
                                }
                            }
                        }
                    }
                    String uiname;
                    if (rec != null) {
                        uiname = rec.getWebURL();
                        if (rec.isType("authority")) {
                            // Need to add namespace for authorities
                            String refName = null;
                            if (in.has("refName")) {
                                refName = in.getString("refName");
                            } else if (in.has("summarylist")) {
                                JSONObject summList = in.getJSONObject("summarylist");
                                if (summList.has("refName")) {
                                    refName = summList.getString("refName");
                                }
                            }
                            if (refName != null) {
                                RefName.AuthorityItem item = RefName.AuthorityItem.parse(refName);
                                in.put("namespace", item.getParentShortIdentifier());
                            }
                        }
                    } else {
                        uiname = rt;
                    }
                    in.put("recordtype", uiname);
                    /*
						JSONObject entry=new JSONObject();
						entry.put("csid",in.getString("csid"));
						entry.put("recordtype",in.getString("sourceFieldType"));
						entry.put("sourceFieldName",field);
						entry.put("number",in.getString("sourceFieldName"));
						*/
                    items.put(in);
                }
            }
            out.put(itemsKey, items);
            if (addPagination && refObjs.has("pagination")) {
                out.put("pagination", refObjs.get("pagination"));
            }
        }
    } catch (JSONException ex) {
        log.debug("JSONException" + ex.getLocalizedMessage());
    // wordlessly eat the errors at the moment as they might be permission errors
    } catch (ExistException e) {
        log.debug("ExistException" + e.getLocalizedMessage());
    // wordlessly eat the errors at the moment as they might be permission errors
    } catch (UnimplementedException e) {
        log.debug("UnimplementedException" + e.getLocalizedMessage());
    // wordlessly eat the errors at the moment as they might be permission errors
    } catch (UnderlyingStorageException e) {
        log.debug("UnderlyingStorageException" + e.getLocalizedMessage());
    // wordlessly eat the errors at the moment as they might be permission errors
    }
}
Also used : JSONObject(org.json.JSONObject) RefName(org.collectionspace.services.common.api.RefName) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) 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)

Example 48 with Record

use of org.collectionspace.chain.csp.schema.Record in project application by collectionspace.

the class UserStorage method deleteJSON.

@Override
public void deleteJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath) throws ExistException, UnimplementedException, UnderlyingStorageException {
    String[] parts = filePath.split("/");
    if (parts.length > 2) {
        for (FieldSet allfs : r.getAllSubRecords("DELETE")) {
            Record allr = allfs.usesRecordId();
            if (allr.getID().equals(parts[2])) {
                filePath = parts[0] + "/" + allr.getServicesURL() + "/" + parts[2];
            }
        }
    }
    // String serviceurl = r.getServicesURL() + "/";
    deleteJSON(root, creds, cache, filePath, r);
}
Also used : FieldSet(org.collectionspace.chain.csp.schema.FieldSet) Record(org.collectionspace.chain.csp.schema.Record)

Example 49 with Record

use of org.collectionspace.chain.csp.schema.Record in project application by collectionspace.

the class ConfiguredVocabStorage method autocreateJSON.

@Override
public String autocreateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, JSONObject jsonObject, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        Map<String, Document> body = new HashMap<String, Document>();
        String vocab = null;
        String pathurl = "/" + r.getServicesURL() + "/";
        if (filePath.equals("")) {
            for (String section : r.getServicesInstancesPaths()) {
                String path = r.getServicesInstancesPath(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, vocab, null, r, true);
                if (temp != null) {
                    body.put(record_path[0], temp);
                // log.info(temp.asXML());
                }
            }
        } else {
            vocab = RefName.shortIdToPath(filePath);
            pathurl = "/" + r.getServicesURL() + "/" + vocab + ITEMS_SUFFIX;
            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, vocab, null, r, false);
                if (temp != null) {
                    body.put(record_path[0], temp);
                // log.info(temp.asXML());
                }
            }
        }
        handleHierarchyPayloadSend(r, body, jsonObject, null);
        ReturnedURL out = conn.getMultipartURL(RequestMethod.POST, pathurl, body, creds, cache);
        if (out.getStatus() > 299)
            throw new UnderlyingStorageException("Could not create vocabulary", out.getStatus(), pathurl);
        String csid = out.getURLTail();
        // create related sub records?
        for (FieldSet fs : r.getAllSubRecords("POST")) {
            Record sr = fs.usesRecordId();
            // sr.getID()
            if (sr.isType("authority")) {
                String savePath = out.getURL() + "/" + sr.getServicesURL();
                if (fs instanceof Field) {
                    // get the fields form inline XXX untested - might not work...
                    JSONObject subdata = new JSONObject();
                    // loop thr jsonObject and find the fields I need
                    for (FieldSet subfs : sr.getAllFieldTopLevel("POST")) {
                        String key = subfs.getID();
                        if (jsonObject.has(key)) {
                            subdata.put(key, jsonObject.get(key));
                        }
                    }
                    subautocreateJSON(root, creds, cache, sr, subdata, savePath);
                } else if (fs instanceof Group) {
                    // JSONObject
                    if (jsonObject.has(fs.getID())) {
                        Object subdata = jsonObject.get(fs.getID());
                        if (subdata instanceof JSONObject) {
                            JSONObject subrecord = (JSONObject) subdata;
                            subautocreateJSON(root, creds, cache, sr, subrecord, savePath);
                        } else {
                            log.warn("autocreateJSON: Contact subrecord is malformed (not a JSONObject)!");
                            if (log.isDebugEnabled()) {
                                log.debug("autocreateJSON: Contact subrecord: " + subdata.toString());
                            }
                        }
                    }
                } else {
                    // JSONArray
                    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);
                                subautocreateJSON(root, creds, cache, sr, subrecord, savePath);
                            }
                        }
                    }
                }
            }
        }
        return csid;
    } 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);
    }
}
Also used : ReturnedURL(org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL) Group(org.collectionspace.chain.csp.schema.Group) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) 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) 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) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 50 with Record

use of org.collectionspace.chain.csp.schema.Record in project application by collectionspace.

the class WebLoginStatus method getPermissions.

private JSONObject getPermissions(Storage storage) throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException {
    final String WORKFLOW_DELETE_RESOURCE_TAIL = WORKFLOW_SUB_RESOURCE + "delete";
    final String WORKFLOW_LOCK_RESOURCE_TAIL = WORKFLOW_SUB_RESOURCE + "lock";
    JSONObject data = new JSONObject();
    JSONObject perms = new JSONObject();
    // spec.getRecordByWebUrl("userperm").getID();
    String permbase = "accountperms";
    String base = spec.getRecordByWebUrl("userperm").getID();
    JSONObject activePermissions = storage.retrieveJSON(base + "/0/", new JSONObject());
    // UI doesn't know what it wants to do about pagination etc
    if (activePermissions.has("account")) {
        JSONObject account = activePermissions.getJSONObject("account");
        String csid = account.getString("accountId");
        String userId = account.getString("userId");
        String tenantId = account.getString("tenantId");
        String screenName = userId;
        if (account.has("screenName")) {
            screenName = account.getString("screenName");
        }
        data.put("csid", csid);
        data.put("screenName", screenName);
        data.put("userId", userId);
        data.put("tenant", tenantId);
    }
    if (activePermissions.has("permission")) {
        JSONArray active = activePermissions.getJSONArray("permission");
        for (int j = 0; j < active.length(); j++) {
            JSONObject perm = active.getJSONObject(j);
            if (perm.has("resourceName") && perm.has("actionGroup")) {
                JSONArray newPermissionsList = null;
                String resourceName = perm.getString("resourceName");
                String resourceNameUI = null;
                // Check and filter the workflow resources
                if (resourceName.endsWith(WORKFLOW_DELETE_RESOURCE_TAIL)) {
                    // Only consider if we can write the workflow transition
                    if (Generic.PermissionIncludesWritable(perm.getString("actionGroup"))) {
                        if (resourceName.startsWith("/")) {
                            resourceName = resourceName.substring(1);
                        }
                        // Get the base resource that the workflow is related to
                        String baseResource = resourceName.substring(0, resourceName.length() - WORKFLOW_DELETE_RESOURCE_TAIL.length());
                        resourceNameUI = Generic.ResourceNameUI(spec, baseResource);
                        // Workflow delete means we have CRUDL permissions
                        if (!perms.has(resourceNameUI)) {
                            newPermissionsList = Generic.PermissionLevelArray("CRUDL");
                        } else {
                            JSONArray prevPermsList = (JSONArray) perms.get(resourceNameUI);
                            newPermissionsList = Generic.PermissionLevelArrayEnsure(prevPermsList, Generic.DELETE_PERMISSION);
                        }
                    }
                } else if (resourceName.endsWith(WORKFLOW_LOCK_RESOURCE_TAIL)) {
                    // TODO Should ignore this if record not configred to support locking.
                    if (Generic.PermissionIncludesWritable(perm.getString("actionGroup"))) {
                        if (resourceName.startsWith("/")) {
                            resourceName = resourceName.substring(1);
                        }
                        // Get the base resource that the workflow is related to
                        String baseResource = resourceName.substring(0, resourceName.length() - WORKFLOW_LOCK_RESOURCE_TAIL.length());
                        resourceNameUI = Generic.ResourceNameUI(spec, baseResource);
                        // Workflow lock means we have CRUDL permissions too
                        if (!perms.has(resourceNameUI)) {
                            newPermissionsList = Generic.PermissionLevelArray("CRUDLK");
                        } else {
                            JSONArray prevPermsList = (JSONArray) perms.get(resourceNameUI);
                            newPermissionsList = Generic.PermissionLevelArrayEnsure(prevPermsList, Generic.LOCK_PERMISSION);
                        }
                    }
                } else if (resourceName.endsWith(WORKFLOW_SIMPLE_SUB_RESOURCE)) {
                    log.info("WebLoginStatus.getPerms: Ignoring resource for simple workflow subresource");
                } else if (resourceName.contains(WORKFLOW_SUB_RESOURCE)) {
                    log.debug("WebLoginStatus.getPerms: Ignoring resource for unrecognized workflow transition: " + resourceName);
                } else {
                    // TODO - If the associated record is configured with soft-Delete, should we
                    // filter 'D' from the actionGroup here?
                    resourceNameUI = Generic.ResourceNameUI(spec, resourceName);
                    // Converts the "actionGroup" from the Services into a list of permission verbs
                    newPermissionsList = Generic.PermissionLevelArray(perm.getString("actionGroup"));
                    if (perms.has(resourceNameUI) == true) {
                        // Merge the existing permissions list with another.
                        JSONArray prevPermsList = (JSONArray) perms.get(resourceNameUI);
                        newPermissionsList = Generic.PermissionLevelArrayEnsure(prevPermsList, newPermissionsList);
                    }
                }
                if (newPermissionsList != null) {
                    perms.put(resourceNameUI, newPermissionsList);
                }
            }
        }
        // to match that of the parent authority.
        for (Record r : spec.getAllRecords()) {
            if (r.isType("authority")) {
                for (Instance ins : r.getAllInstances()) {
                    JSONArray permsdata = new JSONArray();
                    if (r.getWebURL().equals("vocab")) {
                        if (perms.has("vocabularyitems")) {
                            permsdata = perms.getJSONArray("vocabularyitems");
                        }
                    } else {
                        if (perms.has(r.getWebURL())) {
                            permsdata = perms.getJSONArray(r.getWebURL());
                        }
                    }
                    perms.put(ins.getID(), permsdata);
                }
            }
        }
    } else {
        // no permissions = no roles for this tenant
        return new JSONObject();
    }
    for (Record r : spec.getAllRecords()) {
        if (!perms.has(r.getWebURL())) {
            perms.put(r.getWebURL(), new JSONArray());
        }
    }
    // make termlist permissions match vocabularyItems permissions
    // perms.put("termlist", perms.get("vocab"));
    data.put("permissions", perms);
    return data;
}
Also used : JSONObject(org.json.JSONObject) Instance(org.collectionspace.chain.csp.schema.Instance) JSONArray(org.json.JSONArray) Record(org.collectionspace.chain.csp.schema.Record)

Aggregations

Record (org.collectionspace.chain.csp.schema.Record)59 JSONObject (org.json.JSONObject)33 FieldSet (org.collectionspace.chain.csp.schema.FieldSet)23 JSONArray (org.json.JSONArray)19 UnderlyingStorageException (org.collectionspace.csp.api.persistence.UnderlyingStorageException)14 JSONException (org.json.JSONException)14 Field (org.collectionspace.chain.csp.schema.Field)12 Group (org.collectionspace.chain.csp.schema.Group)12 Instance (org.collectionspace.chain.csp.schema.Instance)11 UnimplementedException (org.collectionspace.csp.api.persistence.UnimplementedException)11 ReturnedDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument)10 ReturnedMultipartDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument)10 Document (org.dom4j.Document)10 HashMap (java.util.HashMap)9 ConnectionException (org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)9 ExistException (org.collectionspace.csp.api.persistence.ExistException)9 Element (org.dom4j.Element)9 UIException (org.collectionspace.csp.api.ui.UIException)8 IOException (java.io.IOException)7 Repeat (org.collectionspace.chain.csp.schema.Repeat)7