Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:at.alladin.rmbt.db.TestStat.java

/**
 * checks for submitted extended test stats 
 * @param entity/*w w w  . j  a  va2  s.c o m*/
 * @param testUid
 * @return
 */
public static TestStat checkForSubmittedTestStats(final JSONObject entity, final long testUid) {
    final JSONObject testStatObject = entity.optJSONObject("extended_test_stat");
    if (testStatObject != null) {
        final JSONObject cpuUsage = testStatObject.optJSONObject("cpu_usage");
        final JSONObject memUsage = testStatObject.optJSONObject("mem_usage");

        if (cpuUsage != null || memUsage != null) {
            final TestStat ts = new TestStat();

            ts.setTestUid(testUid);
            ts.setCpuUsage(cpuUsage);
            ts.setMemUsage(memUsage);

            return ts;
        }
    }

    return null;
}

From source file:com.gotraveling.insthub.BeeFramework.model.BaseModel.java

public void callback(String url, JSONObject jo, AjaxStatus status) {
    if (null == jo) {
        ToastView toast = new ToastView(mContext, "");
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();//from ww  w .  j  ava 2  s  . c  o m
        return;
    }
    try {
        STATUS responseStatus = new STATUS();
        responseStatus.fromJson(jo.optJSONObject("status"));
        if (responseStatus.succeed != ErrorCodeConst.ResponseSucceed) {
            if (responseStatus.error_code == ErrorCodeConst.InvalidSession) {
                ToastView toast = new ToastView(mContext, mContext.getString(R.string.session_expires_tips));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                E0_ProfileFragment.isRefresh = true;
                Intent intent = new Intent(mContext, A0_SigninActivity.class);
                mContext.startActivity(intent);

                shared = mContext.getSharedPreferences("userInfo", 0);
                editor = shared.edit();

                editor.putString("uid", "");
                editor.putString("sid", "");
                editor.commit();
                SESSION.getInstance().uid = shared.getString("uid", "");
                SESSION.getInstance().sid = shared.getString("sid", "");

            }

        }

        Resources resource = mContext.getResources();
        String way = resource.getString(R.string.delivery);
        String col = resource.getString(R.string.collected);
        String und = resource.getString(R.string.understock);
        String been = resource.getString(R.string.been_used);
        String sub = resource.getString(R.string.submit_the_parameter_error);
        String fai = resource.getString(R.string.failed);
        String pur = resource.getString(R.string.error_10008);
        String noi = resource.getString(R.string.no_shipping_information);
        String error = resource.getString(R.string.username_or_password_error);
        if (responseStatus.error_code == ErrorCodeConst.SelectedDeliverMethod) {
            ToastView toast = new ToastView(mContext, way);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }

        if (responseStatus.error_code == ErrorCodeConst.AlreadyCollected) {
            //Toast.makeText(mContext, "??", Toast.LENGTH_SHORT).show();
            ToastView toast = new ToastView(mContext, col);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }

        if (responseStatus.error_code == ErrorCodeConst.InventoryShortage) {
            ToastView toast = new ToastView(mContext, und);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }

        if (responseStatus.error_code == ErrorCodeConst.UserOrEmailExist) {
            ToastView toast = new ToastView(mContext, been);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }

        if (responseStatus.error_code == ErrorCodeConst.InvalidParameter) {
            ToastView toast = new ToastView(mContext, sub);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }

        if (responseStatus.error_code == ErrorCodeConst.ProcessFailed) {
            ToastView toast = new ToastView(mContext, fai);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }

        if (responseStatus.error_code == ErrorCodeConst.BuyFailed) {
            ToastView toast = new ToastView(mContext, pur);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }

        if (responseStatus.error_code == ErrorCodeConst.NoShippingInformation) {
            ToastView toast = new ToastView(mContext, noi);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
        if (responseStatus.error_code == ErrorCodeConst.InvalidUsernameOrPassword) {
            ToastView toast = new ToastView(mContext, error);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
        if (responseStatus.error_code == ErrorCodeConst.UserOrEmailExist) {
            ToastView toast = new ToastView(mContext, resource.getString(R.string.been_used));
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    } catch (JSONException e) {

    }

}

From source file:pubsub.io.processing.Pubsub.java

/**
 * React to messages.../*from w  w  w  .j  a v a 2 s .c  o m*/
 */
@Override
public void onMessage(JSONObject msg) {
    if (DEBUG)
        System.out.println(DEBUGTAG + msg.toString());

    int callback_id = 0;

    callback_id = msg.getInt("id");

    if (msg.optJSONObject("doc") != null) {
        JSONObject doc = msg.getJSONObject("doc");

        // Get the callback method
        Method eventMethod = callbacks.get(callback_id);
        if (eventMethod != null) {
            try {
                // Invoke only if the method existed
                eventMethod.invoke(myParent, doc);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    } else if (msg.optJSONArray("doc") != null) {
        JSONArray doc = msg.getJSONArray("doc");

        // Get the callback method
        Method eventMethod = callbacks.get(callback_id);
        if (eventMethod != null) {
            try {
                // Invoke only if the method existed
                eventMethod.invoke(myParent, doc);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    } else {
        // Neither...
    }
}

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

public String sendJSON(Storage storage, String path, JSONObject data, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException {
    final String WORKFLOW_TRANSITION = "workflowTransition";
    final String WORKFLOW_TRANSITION_LOCK = "lock";

    JSONObject fields = data.optJSONObject("fields");
    JSONArray relations = data.optJSONArray("relations");
    if (path != null) {
        // Update
        if (fields != null)
            storage.updateJSON(base + "/" + path, fields, restrictions);
    } else {/*ww  w . j a v  a2 s .  c om*/
        // Create
        if (fields != null)
            path = storage.autocreateJSON(base, fields, restrictions);
    }
    if (relations != null)
        setRelations(storage, path, relations);
    if (record.supportsLocking() && data.has(WORKFLOW_TRANSITION)
            && WORKFLOW_TRANSITION_LOCK.equalsIgnoreCase(data.getString(WORKFLOW_TRANSITION))) {
        // If any problem, will throw exception.
        storage.transitionWorkflowJSON(base + "/" + path, WORKFLOW_TRANSITION_LOCK);
    }
    return path;
}

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

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

    if (fields.has("terms")) {
        Record vr = this.spec.getRecord("vocab");
        Record thisr = spec.getRecord("vocab");
        String sid = fields.getString("shortIdentifier");
        String name = fields.getString("displayName");
        insId = "vocab-" + sid;
        if (create) {
            Map<String, String> options = new HashMap<String, String>();
            options.put("id", insId);
            options.put("title", name);
            options.put("web-url", sid);
            options.put("title-ref", sid);

            Instance ins = new Instance(thisr, options);
            vr.addInstance(ins);/*from  w  w  w  .  j av  a  2  s  .c  om*/
        }
        ctl.get(storage, sid, vr, 0);
    }

}

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(//  w w w .  j  a va  2 s  . com
                                    "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 {/* w w w  . j  a  v a  2  s . co 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

@Override
public ActivityScript getActivityScript() {
    scriptQ.clear();//from  ww  w . j a  v  a  2 s . com
    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  w w  w . j  a v  a 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.norman0406.slimgress.API.Interface.RequestResult.java

public static void handleRequest(JSONObject json, RequestResult result) {
    if (result == null)
        throw new RuntimeException("invalid result object");

    try {//from w  w w .j ava  2  s  .  co  m
        // handle exception string if available
        String excString = json.optString("exception");
        if (excString.length() > 0)
            result.handleException(excString);

        // handle error code if available
        String error = json.optString("error");
        if (error.length() > 0)
            result.handleError(error);
        else if (json.has("error"))
            Log.w("RequestResult", "request contains an unknown error type");

        // handle game basket if available
        JSONObject gameBasket = json.optJSONObject("gameBasket");
        if (gameBasket != null)
            result.handleGameBasket(new GameBasket(gameBasket));

        // handle result if available
        JSONObject resultObj = json.optJSONObject("result");
        JSONArray resultArr = json.optJSONArray("result");
        String resultStr = json.optString("result");
        if (resultObj != null)
            result.handleResult(resultObj);
        else if (resultArr != null)
            result.handleResult(resultArr);
        else if (resultStr != null)
            result.handleResult(resultStr);
        else if (json.has("result"))
            Log.w("RequestResult", "request contains an unknown result type");

        result.finished();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}