Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

In this page you can find the example usage for org.json JSONObject JSONObject.

Prototype

public JSONObject() 

Source Link

Document

Construct an empty JSONObject.

Usage

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private JSONObject getPerm(Storage storage, Record recordForPermResource, String resourceName, String permLevel)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject permitem = new JSONObject();

    if (permLevel.equals("none")) {
        return permitem;
    }/*from w  ww .j a  v a  2s . c om*/

    JSONArray actions = new JSONArray();
    JSONObject permR = permJSON("READ");
    JSONObject permC = permJSON("CREATE");
    JSONObject permU = permJSON("UPDATE");
    JSONObject permD = permJSON("DELETE");
    JSONObject permL = permJSON("SEARCH");

    ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL
    String queryString = "CRUDL";

    if (permLevel.equals(Generic.READ_PERMISSION)) {
        queryString = "RL";
        actions.put(permR);
        actions.put(permL);
    } else if (permLevel.equals(Generic.WRITE_PERMISSION)) {
        queryString = "CRUL";
        actions.put(permC);
        actions.put(permR);
        actions.put(permU);
        actions.put(permL);
    } else if (permLevel.equals(Generic.DELETE_PERMISSION) || permLevel.equals(Generic.LOCK_PERMISSION)) {
        actions.put(permC);
        actions.put(permR);
        actions.put(permU);
        if (recordForPermResource != null && recordForPermResource.hasSoftDeleteMethod()) {
            // Delete is handled in the workflow perms
            queryString = "CRUL";
        } else {
            queryString = "CRUDL";
            actions.put(permD);
        }
        actions.put(permL); // Keep this here to preserve CRUDL order of actions
    } else {
        log.warn("RecordCreateDelete.getPerm passed unknown permLevel: " + permLevel);
    }

    String permbase = spec.getRecordByWebUrl("permission").getID();

    permitem = getPermID(storage, Generic.ResourceNameServices(spec, resourceName), queryString, permbase,
            actions);
    return permitem;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private JSONObject getWorkflowPerm(Storage storage, Record recordForPermResource, String resourceName,
        String permLevel, String workflowTransition)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject permitem = new JSONObject();

    if (permLevel.equals("none")) {
        return permitem;
    }//from   ww  w.j  a  v a  2  s  .c  o m

    JSONArray actions = new JSONArray();
    JSONObject permC = permJSON("CREATE");
    JSONObject permR = permJSON("READ");
    JSONObject permU = permJSON("UPDATE");
    JSONObject permD = permJSON("DELETE");
    JSONObject permL = permJSON("SEARCH");
    actions.put(permR);
    actions.put(permL);

    ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL
    String queryString = "RL";
    String permbase = spec.getRecordByWebUrl("permission").getID();
    boolean hasRights = false;

    if (workflowTransition.equals(DELETE_WORKFLOW_TRANSITION)) {
        // permLevel delete or lock includes this
        hasRights = permLevel.equals(Generic.DELETE_PERMISSION) || permLevel.equals(Generic.LOCK_PERMISSION);
    } else if (workflowTransition.equals(LOCK_WORKFLOW_TRANSITION)) {
        // permLevel lock includes this
        // UI does not yet support admin of the lock perm, so 
        //hasRights = permLevel.equals(Generic.LOCK_PERMISSION);
        // Assumes this is only called for records that actually support locking...
        hasRights = permLevel.equals(Generic.DELETE_PERMISSION) || permLevel.equals(Generic.UPDATE_PERMISSION)
                || permLevel.equals(Generic.LOCK_PERMISSION);
    } else {
        log.warn("RecordCreateUpdate.getWorkflowPerm passed unknown workflowTransition: " + workflowTransition);
    }
    if (hasRights) {
        actions.put(permC);
        actions.put(permU);
        actions.put(permD);
        // They do not really get DELETE rights on a workflow, but that is what the services models by
        // default, so let's stick with that 
        queryString = "CRUDL";
    }
    // Workflow resources all have leading slashes.
    String resource = Generic.ResourceNameServices(spec, resourceName) + WORKFLOW_SUB_RESOURCE
            + workflowTransition;
    if (!resource.startsWith("/"))
        resource = "/" + resource;
    permitem = getPermID(storage, resource, queryString, permbase, actions);
    return permitem;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private JSONObject getPermID(Storage storage, String name, String queryString, String permbase,
        JSONArray actions)/*from  w w  w.j  a  v a 2  s .co m*/
        throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException {

    JSONObject permitem = new JSONObject();
    JSONObject permrestrictions = new JSONObject();
    permrestrictions.put("keywords", name);
    permrestrictions.put("queryTerm", "actGrp");
    permrestrictions.put("queryString", queryString);
    JSONObject data = searcher.getJSON(storage, permrestrictions, "items", permbase);

    String permid = "";
    JSONArray items = data.getJSONArray("items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        String resourcename = item.getString("summary");
        String actionGroup = item.getString("number");
        //need to do a double check as the query is an inexact match
        if (resourcename.equals(name) && actionGroup.equals(queryString)) {
            permid = item.getString("csid");
        }
    }
    if (permid.equals("")) {

        //create the permission
        /**
         * {
        "effect": "PERMIT",
        "resourceName": "testthing2",
                
        "action":[{"name":"CREATE"},{"name":"READ"},{"name":"UPDATE"},{"name":"DELETE"},{"name":"SEARCH"}]
        }
         */

        JSONObject permission_add = new JSONObject();
        permission_add.put("effect", "PERMIT");
        permission_add.put("description", "created because we couldn't find a match");
        permission_add.put("resourceName", name);
        permission_add.put("actionGroup", queryString);
        permission_add.put("action", actions);

        permid = storage.autocreateJSON(spec.getRecordByWebUrl("permission").getID(), permission_add, null);

    }

    if (!permid.equals("")) {
        permitem.put("resourceName", name);
        permitem.put("permissionId", permid);
        permitem.put("actionGroup", queryString);
    }
    return permitem;

}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private void assignPermissions(Storage storage, String path, JSONObject data)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject fields = data.optJSONObject("fields");

    JSONArray permdata = new JSONArray();
    JSONObject permcheck = new JSONObject();
    if (fields.has("permissions")) {
        JSONArray permissions = fields.getJSONArray("permissions");
        for (int i = 0; i < permissions.length(); i++) {
            JSONObject perm = permissions.getJSONObject(i);

            Record recordForPermResource = Generic.RecordNameServices(spec, perm.getString("resourceName"));
            if (recordForPermResource != null) {
                if (recordForPermResource.hasSoftDeleteMethod()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            DELETE_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(//from w  w  w.j a  v a2 s.  c om
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/delete permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
                if (recordForPermResource.supportsLocking()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            LOCK_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/lock permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
            }
            JSONObject permitem = getPerm(storage, recordForPermResource, perm.getString("resourceName"),
                    perm.getString("permission"));
            if (permitem.has("permissionId")) {
                if (permcheck.has(permitem.getString("resourceName"))) {
                    //ignore as we have duplicate name - eek
                    log.warn("RecordCreateUpdate.assignPermissions got duplicate permission for: "
                            + permitem.getString("resourceName"));
                } else {
                    permcheck.put(permitem.getString("resourceName"), permitem);
                    permdata.put(permitem);
                }
            }
        }
    }

    //log.info("permdata"+permdata.toString());
    JSONObject roledata = new JSONObject();
    roledata.put("roleName", fields.getString("roleName"));

    String[] ids = path.split("/");
    roledata.put("roleId", ids[ids.length - 1]);

    JSONObject accountrole = new JSONObject();
    JSONObject arfields = new JSONObject();
    arfields.put("role", roledata);
    arfields.put("permission", permdata);
    accountrole.put("fields", arfields);
    //log.info("WAAA"+arfields.toString());
    if (fields != null)
        path = storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(), arfields, null);
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private void store_set(Storage storage, UIRequest request, String path) throws UIException {
    try {/*from   ww  w .  j ava2  s . c  o  m*/
        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", "ROLE_" + test);
                data.put("fields", fields);
            }
            // If we are updating a role, then we need to clear the userperms cache
            // 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"))) { // If has blobCsid, already has media link so do nothing more
                // No media, so consider the source
                // "sourceUrl" is not a declared field in the app layer config, but the UI passes it in
                // 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
                        String[] parts = uri.split(BLOBS_SERVICE_URL_PATTERN); // Split to get CSID
                        String[] bits = parts[1].split("/"); // Strip off anything trailing the CSID
                        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);
            request.setCacheMaxAgeSeconds(0); // Ensure we do not cache report output.
            //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");
                    }
                }
                path = sendJSON(storage, null, data, restrictions); // REM - We needed a way to send query params, so I'm adding "restrictions" here
                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);
            }

            data = reader.getJSON(storage, path); // We do a GET now to read back what we created.
            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);
    }

}

From source file:edu.stanford.junction.provider.irc.Junction.java

protected void handleScriptRequest(String from, JSONObject req) {
    if (mActivityScript == null)
        return;/*from w  w w .  ja va  2s. c  om*/
    try {
        JSONObject response = new JSONObject();
        response.put("scriptResponse", true);
        response.put("requestId", req.optString("requestId"));
        response.put("script", mActivityScript.getJSON());
        sendMessageToActor(from, response);
    } catch (JSONException e) {
        e.printStackTrace(System.err);
    }
}

From source file:edu.stanford.junction.provider.irc.Junction.java

@Override
public ActivityScript getActivityScript() {
    scriptQ.clear();/*w ww  .j  a v  a  2 s.  c  om*/
    JSONObject req = new JSONObject();
    String requestId = UUID.randomUUID().toString();
    try {
        req.put("scriptRequest", "true");
        req.put("requestId", requestId);
        sendMessageToSession(req);
    } catch (JSONException e) {
        e.printStackTrace(System.err);
        return null;
    }
    try {
        int maxTries = 5;
        long maxWaitPerTry = 2000L;
        for (int i = 0; i < maxTries; i++) {
            JSONObject response = scriptQ.poll(maxWaitPerTry, TimeUnit.MILLISECONDS);
            if (response == null) {
                return null;
            } else if (response.optString("requestId").equals(requestId)) {
                JSONObject script = response.optJSONObject("script");
                return new ActivityScript(script);
            }
        }
    } catch (InterruptedException e) {
        return null;
    }
    return null;
}

From source file:edu.stanford.junction.provider.irc.Junction.java

@Override
public void doSendMessageToRole(String role, JSONObject message) {
    JSONObject jx;/*from  www  .  ja va  2  s .  c  o  m*/
    if (message.has(NS_JX)) {
        jx = message.optJSONObject(NS_JX);
    } else {
        jx = new JSONObject();
        try {
            message.put(NS_JX, jx);
        } catch (JSONException j) {
        }
    }
    try {
        jx.put("targetRole", role);
    } catch (Exception e) {
    }

    String msg = message.toString();
    sendMsgTo(msg, "#" + mSession + "," + mNickname);
}

From source file:com.liferay.mobile.android.v7.announcementsentry.AnnouncementsEntryService.java

public JSONObject addEntry(long plid, long classNameId, long classPK, String title, String content, String url,
        String type, int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour,
        int displayDateMinute, boolean displayImmediately, int expirationDateMonth, int expirationDateDay,
        int expirationDateYear, int expirationDateHour, int expirationDateMinute, int priority, boolean alert)
        throws Exception {
    JSONObject _command = new JSONObject();

    try {/*from   ww  w. j  av a 2  s. com*/
        JSONObject _params = new JSONObject();

        _params.put("plid", plid);
        _params.put("classNameId", classNameId);
        _params.put("classPK", classPK);
        _params.put("title", checkNull(title));
        _params.put("content", checkNull(content));
        _params.put("url", checkNull(url));
        _params.put("type", checkNull(type));
        _params.put("displayDateMonth", displayDateMonth);
        _params.put("displayDateDay", displayDateDay);
        _params.put("displayDateYear", displayDateYear);
        _params.put("displayDateHour", displayDateHour);
        _params.put("displayDateMinute", displayDateMinute);
        _params.put("displayImmediately", displayImmediately);
        _params.put("expirationDateMonth", expirationDateMonth);
        _params.put("expirationDateDay", expirationDateDay);
        _params.put("expirationDateYear", expirationDateYear);
        _params.put("expirationDateHour", expirationDateHour);
        _params.put("expirationDateMinute", expirationDateMinute);
        _params.put("priority", priority);
        _params.put("alert", alert);

        _command.put("/announcementsentry/add-entry", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.liferay.mobile.android.v7.announcementsentry.AnnouncementsEntryService.java

public JSONObject getEntry(long entryId) throws Exception {
    JSONObject _command = new JSONObject();

    try {//from w  w w  .ja v  a2 s  .  c  o m
        JSONObject _params = new JSONObject();

        _params.put("entryId", entryId);

        _command.put("/announcementsentry/get-entry", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}