Example usage for org.json JSONObject remove

List of usage examples for org.json JSONObject remove

Introduction

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

Prototype

public Object remove(String key) 

Source Link

Document

Remove a name and its value, if present.

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 {//w  ww . j  av  a  2s.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:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

public void sendChangesToCozy() {
    List<LoyaltyCard> unSyncedLoyaltyCards = LoyaltyCard.getAllUnsynced();
    int i = 0;/*from  ww w  .  ja  va2s  .c  om*/
    for (LoyaltyCard loyaltyCard : unSyncedLoyaltyCards) {
        URL urlO = null;
        try {
            JSONObject jsonObject = loyaltyCard.toJsonObject();
            mBuilder.setProgress(unSyncedLoyaltyCards.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new LoyaltyCardSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                loyaltyCard.setRemoteId(result);
                loyaltyCard.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VideoObj.java

@Override
public Pair<JSONObject, byte[]> splitRaw(JSONObject json) {
    byte[] raw = Base64.decode(json.optString(DATA));
    json.remove(DATA);
    return new Pair<JSONObject, byte[]>(json, raw);
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VideoObj.java

public Pair<JSONObject, byte[]> handleUnprocessed(Context context, JSONObject msg) {
    byte[] bytes = Base64.decode(msg.optString(DATA));
    msg.remove(DATA);
    return new Pair<JSONObject, byte[]>(msg, bytes);
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VideoObj.java

@Override
public Pair<JSONObject, byte[]> handleOutgoing(JSONObject json) {
    byte[] bytes = Base64.decode(json.optString(DATA));
    json.remove(DATA);
    return new Pair<JSONObject, byte[]>(json, bytes);
}

From source file:org.b3log.solo.processor.util.Filler.java

/**
 * Fills post comments recently.//ww w.java  2s. c o  m
 *
 * @param dataModel data model
 * @param preference the specified preference
 * @throws ServiceException service exception
 */
public void fillRecentComments(final Map<String, Object> dataModel, final JSONObject preference)
        throws ServiceException {
    Stopwatchs.start("Fill Recent Comments");
    try {
        LOGGER.finer("Filling recent comments....");
        final int recentCommentDisplayCnt = preference.getInt(Preference.RECENT_COMMENT_DISPLAY_CNT);

        final List<JSONObject> recentComments = commentRepository.getRecentComments(recentCommentDisplayCnt);

        for (final JSONObject comment : recentComments) {
            final String content = comment.getString(Comment.COMMENT_CONTENT)
                    .replaceAll(SoloServletListener.ENTER_ESC, "&nbsp;");
            comment.put(Comment.COMMENT_CONTENT, content);
            comment.put(Comment.COMMENT_NAME,
                    StringEscapeUtils.escapeHtml(comment.getString(Comment.COMMENT_NAME)));
            comment.put(Comment.COMMENT_URL,
                    StringEscapeUtils.escapeHtml(comment.getString(Comment.COMMENT_URL)));

            comment.remove(Comment.COMMENT_EMAIL); // Erases email for security reason
        }

        dataModel.put(Common.RECENT_COMMENTS, recentComments);

    } catch (final JSONException e) {
        LOGGER.log(Level.SEVERE, "Fills recent comments failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, "Fills recent comments failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}

From source file:org.b3log.solo.processor.util.Filler.java

/**
 * Fills header.ftl./*from   w  w w  .  ja v a2 s.c  o m*/
 *
 * @param request the specified HTTP servlet request
 * @param dataModel data model
 * @param preference the specified preference
 * @throws ServiceException service exception
 */
public void fillBlogHeader(final HttpServletRequest request, final Map<String, Object> dataModel,
        final JSONObject preference) throws ServiceException {
    Stopwatchs.start("Fill Header");
    try {
        LOGGER.fine("Filling header....");
        dataModel.put(Preference.ARTICLE_LIST_DISPLAY_COUNT,
                preference.getInt(Preference.ARTICLE_LIST_DISPLAY_COUNT));
        dataModel.put(Preference.ARTICLE_LIST_PAGINATION_WINDOW_SIZE,
                preference.getInt(Preference.ARTICLE_LIST_PAGINATION_WINDOW_SIZE));
        dataModel.put(Preference.LOCALE_STRING, preference.getString(Preference.LOCALE_STRING));
        dataModel.put(Preference.BLOG_TITLE, preference.getString(Preference.BLOG_TITLE));
        dataModel.put(Preference.BLOG_SUBTITLE, preference.getString(Preference.BLOG_SUBTITLE));
        dataModel.put(Preference.HTML_HEAD, preference.getString(Preference.HTML_HEAD));
        dataModel.put(Preference.META_KEYWORDS, preference.getString(Preference.META_KEYWORDS));
        dataModel.put(Preference.META_DESCRIPTION, preference.getString(Preference.META_DESCRIPTION));
        dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));

        final String noticeBoard = preference.getString(Preference.NOTICE_BOARD);
        dataModel.put(Preference.NOTICE_BOARD, noticeBoard);

        final Query query = new Query().setPageCount(1);
        final JSONObject result = userRepository.get(query);
        final JSONArray users = result.getJSONArray(Keys.RESULTS);
        final List<JSONObject> userList = CollectionUtils.jsonArrayToList(users);
        dataModel.put(User.USERS, userList);
        for (final JSONObject user : userList) {
            user.remove(User.USER_EMAIL);
        }

        final String skinDirName = (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME);
        dataModel.put(Skin.SKIN_DIR_NAME, skinDirName);

        Keys.fillServer(dataModel);
        Keys.fillRuntime(dataModel);
        fillMinified(dataModel);
        fillPageNavigations(dataModel);
        fillStatistic(dataModel);
    } catch (final JSONException e) {
        LOGGER.log(Level.SEVERE, "Fills blog header failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, "Fills blog header failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}

From source file:org.privatenotes.Note.java

public JSONObject toJsonWithoutContent() throws JSONException {
    JSONObject json = toJson();
    json.remove("note-content");
    return json;//from   w  ww .  ja va  2 s  . com
}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

public void sendChangesToCozy() {
    List<Expense> unSyncedExpenses = Expense.getAllUnsynced();
    int i = 0;//  ww w .  j a v a  2s .  c  o  m
    for (Expense expense : unSyncedExpenses) {
        URL urlO = null;
        try {
            JSONObject jsonObject = expense.toJsonObject();
            mBuilder.setProgress(unSyncedExpenses.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new ExpenseSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_expense_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                expense.setRemoteId(result);
                expense.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:org.loklak.server.Accounting.java

/**
 * cleanup deletes all old entries and frees up the memory.
 * some outside process muss call this frequently
 * @return self/*from  w ww.java 2 s .c o m*/
 */
public Accounting cleanup() {
    if (!this.has("requests"))
        return this;
    JSONObject requests = this.getJSONObject("requests");
    for (String path : requests.keySet()) {
        JSONObject events = requests.getJSONObject(path);
        // shrink that map and delete everything which is older than now minus one hour
        long pivotTime = System.currentTimeMillis() - ONE_HOUR_MILLIS;
        while (events.length() > 0 && Long.parseLong(events.keys().next()) < pivotTime)
            events.remove(events.keys().next());
        if (events.length() == 0)
            requests.remove(path);
    }
    return this;
}