Example usage for org.json JSONObject put

List of usage examples for org.json JSONObject put

Introduction

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

Prototype

public JSONObject put(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject.

Usage

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  w  ww .  j  a  v  a2  s . c om*/
        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;/* w  w  w . j ava  2 s .c  o m*/
    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 w w .  j a v a  2 s . co m
    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;// w  ww  .ja va2 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 w w w. java  2  s .c  om
        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. j  ava  2s.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);
}

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

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

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

        _params.put("entryId", entryId);

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

    session.invoke(_command);
}

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

public JSONObject updateEntry(long entryId, 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)
        throws Exception {
    JSONObject _command = new JSONObject();

    try {// www .j a v  a2  s.  c om
        JSONObject _params = new JSONObject();

        _params.put("entryId", entryId);
        _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);

        _command.put("/announcementsentry/update-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:net.straylightlabs.archivo.net.MindCommandRecordingFolderItemSearch.java

private static JSONArray buildTemplate() {
    JSONArray templates = new JSONArray();
    JSONObject template;

    // Only get the recording ID
    template = new JSONObject();
    template.put(TYPE, "responseTemplate");
    template.put(FIELD_NAME, Collections.singletonList("childRecordingId"));
    template.put(TYPE_NAME, "recordingFolderItem");
    templates.put(template);/*  w w w  .java 2  s .  c  om*/

    return templates;
}

From source file:com.graphhopper.http.InfoServlet.java

void writeInfos(HttpServletRequest req, HttpServletResponse res) throws Exception {
    BBox bb = hopper.getGraph().getBounds();
    List<Double> list = new ArrayList<Double>(4);
    list.add(bb.minLon);//ww w  .  j  av  a  2s .  co  m
    list.add(bb.minLat);
    list.add(bb.maxLon);
    list.add(bb.maxLat);

    JSONObject json = new JSONObject();
    json.put("bbox", list);

    String[] vehicles = hopper.getGraph().getEncodingManager().toString().split(",");
    json.put("supported_vehicles", vehicles);
    JSONObject features = new JSONObject();
    for (String v : vehicles) {
        JSONObject perVehicleJson = new JSONObject();
        perVehicleJson.put("elevation", hopper.hasElevation());
        features.put(v, perVehicleJson);
    }
    json.put("features", features);

    json.put("version", Constants.VERSION);
    json.put("build_date", Constants.BUILD_DATE);

    StorableProperties props = hopper.getGraph().getProperties();
    json.put("import_date", props.get("osmreader.import.date"));

    if (!Helper.isEmpty(props.get("prepare.date")))
        json.put("prepare_date", props.get("prepare.date"));

    writeJson(req, res, json);
}