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:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    // Log.i(AnkiDroidApp.TAG, "StudyOptionsFragment: onActivityResult");

    if (resultCode == DeckPicker.RESULT_DB_ERROR) {
        closeStudyOptions(DeckPicker.RESULT_DB_ERROR);
    }//from www. jav  a2 s.c o  m

    if (resultCode == AnkiDroidApp.RESULT_TO_HOME) {
        closeStudyOptions();
        return;
    }

    // TODO: proper integration of big widget
    if (resultCode == DeckPicker.RESULT_MEDIA_EJECTED) {
        closeStudyOptions(DeckPicker.RESULT_MEDIA_EJECTED);
    } else {
        if (!AnkiDroidApp.colIsOpen()) {
            reloadCollection();
            mDontSaveOnStop = false;
            return;
        }
        if (requestCode == DECK_OPTIONS) {
            if (mCramInitialConfig != null) {
                mCramInitialConfig = null;
                try {
                    JSONObject deck = AnkiDroidApp.getCol().getDecks().current();
                    if (deck.getInt("dyn") != 0 && deck.has("empty")) {
                        deck.remove("empty");
                    }
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                rebuildCramDeck();
            } else {
                resetAndUpdateValuesFromDeck();
            }
        } else if (requestCode == ADD_NOTE && resultCode != Activity.RESULT_CANCELED) {
            resetAndUpdateValuesFromDeck();
        } else if (requestCode == REQUEST_REVIEW) {
            // Log.i(AnkiDroidApp.TAG, "Result code = " + resultCode);
            // TODO: Return to standard scheduler
            // TODO: handle big widget
            switch (resultCode) {
            default:
                // do not reload counts, if activity is created anew because it has been before destroyed by android
                resetAndUpdateValuesFromDeck();
                break;
            case Reviewer.RESULT_NO_MORE_CARDS:
                prepareCongratsView();
                setFragmentContentView(mCongratsView);
                break;
            }
            mDontSaveOnStop = false;
        } else if (requestCode == BROWSE_CARDS
                && (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED)) {
            mDontSaveOnStop = false;
            resetAndUpdateValuesFromDeck();
        } else if (requestCode == STATISTICS && mCurrentContentView == CONTENT_CONGRATS) {
            resetAndUpdateValuesFromDeck();
            mCurrentContentView = CONTENT_STUDY_OPTIONS;
            setFragmentContentView(mStudyOptionsView);
        }
    }
}

From source file:com.joyfulmongo.db.OpCmdAdd.java

@Override
public void onUpdate(String colname, JSONObject parseObject) {
    JSONArray a = mObj.optJSONArray(AddProps.objects.toString());
    JSONObject each = new JSONObject();
    each.put(CMD_EACH, a);//from w  ww . j a  v  a  2s . com

    JSONObject addToSet = parseObject.optJSONObject(CMD_ADD_TO_SET);
    if (addToSet == null) {
        JSONObject field = new JSONObject();
        field.put(key, each);

        parseObject.remove(key);
        parseObject.put(CMD_ADD_TO_SET, field);
    } else {
        parseObject.remove(key);
        addToSet.put(key, each);
    }
}

From source file:org.loklak.android.client.SearchClient.java

public static Timeline search(final String protocolhostportstub, final String query, final Timeline.Order order,
        final String source, final int count, final int timezoneOffset, final long timeout) throws IOException {
    Timeline tl = new Timeline(order);
    String urlstring = "";
    try {//from  w w w  . j  ava2 s .c om
        urlstring = protocolhostportstub + "/api/search.json?q="
                + URLEncoder.encode(query.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset
                + "&maximumRecords=" + count + "&source=" + (source == null ? "all" : source)
                + "&minified=true&timeout=" + timeout;
        JSONObject json = JsonIO.loadJson(urlstring);
        if (json == null || json.length() == 0)
            return tl;
        JSONArray statuses = json.getJSONArray("statuses");
        if (statuses != null) {
            for (int i = 0; i < statuses.length(); i++) {
                JSONObject tweet = statuses.getJSONObject(i);
                JSONObject user = tweet.getJSONObject("user");
                if (user == null)
                    continue;
                tweet.remove("user");
                UserEntry u = new UserEntry(user);
                MessageEntry t = new MessageEntry(tweet);
                tl.add(t, u);
            }
        }
        if (json.has("search_metadata")) {
            JSONObject metadata = json.getJSONObject("search_metadata");
            if (metadata.has("hits")) {
                tl.setHits((Integer) metadata.get("hits"));
            }
            if (metadata.has("scraperInfo")) {
                String scraperInfo = (String) metadata.get("scraperInfo");
                tl.setScraperInfo(scraperInfo);
            }
        }
    } catch (Throwable e) {
        Log.e("SeachClient", e.getMessage(), e);
    }
    //System.out.println(parser.text());
    return tl;
}

From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java

/**
 * Given either a {@link JSONArray} or a {@link JSONObject}, a key ending and a prefix to add, 
 * it looks for keys at any object inside the provided JSON ending with the key ending and adds 
 * the given prefix to that ending.//from   w ww.ja  v  a  2  s .  c  o m
 * This method calls itself recursively to traverse inner parts of {@link JSONObject}s.
 * @param jsonRoot The root {@link JSONObject} or {@link JSONArray}. If an object of any other type is provided, 
 *                the method just does nothing.
 * @param oldKeyEnding the ending to look for.
 * @param prefixToAdd the prefix to add to that ending.
 */
private void addPrefixToJSONKeysEndingsRecursive(Object jsonRoot, String oldKeyEnding, String prefixToAdd) {
    if (jsonRoot instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) jsonRoot;
        SortedSet<String> keys = ImmutableSortedSet.<String>naturalOrder().addAll(jsonObject.keySet()).build();
        for (String key : keys) {
            Object value = jsonObject.get(key);
            addPrefixToJSONKeysEndingsRecursive(value, oldKeyEnding, prefixToAdd);
            if (key.endsWith(oldKeyEnding)) {
                String newKey = key.replaceAll(Pattern.quote(oldKeyEnding) + "$", prefixToAdd + oldKeyEnding);
                jsonObject.remove(key);
                jsonObject.put(newKey, value);
            }
        }
    } else if (jsonRoot instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) jsonRoot;
        for (int i = 0; i < jsonArray.length(); i++) {
            Object value = jsonArray.get(i);
            addPrefixToJSONKeysEndingsRecursive(value, oldKeyEnding, prefixToAdd);
        }
    } else {
        return;
    }
}

From source file:ai.susi.mind.SusiSkill.java

/**
 * Create a skill by parsing of the skill description
 * @param json the skill description//from www  .  j a va2  s .co  m
 * @throws PatternSyntaxException
 */
private SusiSkill(JSONObject json) throws PatternSyntaxException {

    // extract the phrases and the phrases subscore
    if (!json.has("phrases"))
        throw new PatternSyntaxException("phrases missing", "", 0);
    JSONArray p = (JSONArray) json.remove("phrases");
    this.phrases = new ArrayList<>(p.length());
    p.forEach(q -> this.phrases.add(new SusiPhrase((JSONObject) q)));

    // extract the actions and the action subscore
    if (!json.has("actions"))
        throw new PatternSyntaxException("actions missing", "", 0);
    p = (JSONArray) json.remove("actions");
    this.actions = new ArrayList<>(p.length());
    p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q)));

    // extract the inferences and the process subscore; there may be no inference at all
    if (json.has("process")) {
        p = (JSONArray) json.remove("process");
        this.inferences = new ArrayList<>(p.length());
        p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q)));
    } else {
        this.inferences = new ArrayList<>(0);
    }

    // extract (or compute) the keys; there may be none key given, then they will be computed
    this.keys = new HashSet<>();
    JSONArray k;
    if (json.has("keys")) {
        k = json.getJSONArray("keys");
        if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0))
            k = computeKeysFromPhrases(this.phrases);
    } else {
        k = computeKeysFromPhrases(this.phrases);
    }

    k.forEach(o -> this.keys.add((String) o));

    this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE;
    this.score = null; // calculate this later if required

    // extract the comment
    this.comment = json.has("comment") ? json.getString("comment") : "";

    // calculate the id
    String ids0 = this.actions.toString();
    String ids1 = this.phrases.toString();
    this.id = ids0.hashCode() + ids1.hashCode();
}

From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java

private void handleIncomingMessage(final IncomingMessage incoming) {
    final SignedObj contents = incoming.contents();
    final long hash = contents.getHash();
    if (contents.getSender() == null) {
        Log.e(TAG, "Null sender for " + contents.getType() + ", " + contents.getJson());
        return;//from w w  w.  j  a  v a  2 s.c  o m
    }
    final String personId = contents.getSender().getId();
    // final String personId = incoming.from();

    /**
     * TODO: This needs to be updated with the POSI standards to accept a
     * SignedObj.
     */

    if (DBG)
        Log.i(TAG, "Localized contents: " + contents);
    try {
        JSONObject in_obj = contents.getJson();
        String feedName = contents.getFeedName();
        String type = contents.getType();
        Uri feedPreUri = Feed.uriForName(feedName);
        if (mMessageDropHandler.preFiltersObj(mContext, feedPreUri)) {
            return;
        }

        if (mHelper.queryAlreadyReceived(hash)) {
            if (DBG)
                Log.i(TAG, "Message already received: " + hash);
            return;
        }

        Maybe<Contact> contact = mHelper.contactForPersonId(personId);
        final DbEntryHandler objHandler = DbObjects.getObjHandler(in_obj);
        byte[] extracted_data = null;
        if (objHandler instanceof UnprocessedMessageHandler) {
            Pair<JSONObject, byte[]> r = ((UnprocessedMessageHandler) objHandler).handleUnprocessed(mContext,
                    in_obj);
            if (r != null) {
                in_obj = r.first;
                extracted_data = r.second;
            }
        }
        final JSONObject obj = in_obj;
        final byte[] raw = extracted_data;

        /**
         *  TODO STFAN BJDODSON KANAKB
         *
         *  See FriendAcceptObj.handleUnprocessed as template, code is something like:
         *
         *  if (!mPublicKeyDirectory.verify(in_obj.getString("email"), in_obj.getPublicKey())) {
         *    Log.w("Spammer trying to claim public key for email address");
         *    return;
         *  }
         *  if (inAddressBook(email)) {
         *     // auto-accept and notify of new friend
         *  } else {
         *     // notification to accept friend
         *  }
         */

        if (!contact.isKnown()) {
            Log.i(TAG, "Message from unknown contact. " + contents);
            return;
        }

        /**
         * Run handlers over all received objects:
         */

        long objId;
        final Contact realContact = contact.get();
        long contactId = realContact.id;
        if (DBG)
            Log.d(TAG, "Msg from " + contactId + " ( " + realContact.name + ")");
        // Insert into the database. (TODO: Handler, both android.os and
        // musubi.core)

        if (!objHandler.handleObjFromNetwork(mContext, realContact, obj)) {
            return;
        }

        Integer intKey = null;
        if (obj.has(DbObjects.JSON_INT_KEY)) {
            intKey = obj.getInt(DbObjects.JSON_INT_KEY);
            obj.remove(DbObjects.JSON_INT_KEY);
        }
        objId = mHelper.addObjectByJson(contact.otherwise(Contact.NA()).id, obj, hash, raw, intKey);
        Uri feedUri;
        if (feedName.equals("friend")) {
            feedUri = Feed.uriForName("friend/" + contactId);
        } else {
            feedUri = Feed.uriForName(feedName);
        }
        mContext.getContentResolver().notifyChange(feedUri, null);
        if (feedName.equals("direct") || feedName.equals("friend")) {
            long time = obj.optLong(DbObject.TIMESTAMP);
            Helpers.updateLastPresence(mContext, realContact, time);
            objHandler.handleDirectMessage(mContext, realContact, obj);
        }

        /**
         * Run handlers over all received objects:
         */

        // TODO: framework code.
        DbObj signedObj = App.instance().getMusubi().objForId(objId);
        getFromNetworkHandlers().handleObj(mContext, DbObjects.forType(type), signedObj);
        objHandler.afterDbInsertion(mContext, signedObj);
    } catch (Exception e) {
        Log.e(TAG, "Error handling incoming message.", e);
    }
}

From source file:cn.code.notes.gtask.remote.GTaskManager.java

private void addLocalNode(Node node) throws NetworkFailureException {
    if (mCancelled) {
        return;//from   w ww  .  j a v  a 2  s.com
    }

    SqlNote sqlNote;
    if (node instanceof TaskList) {
        if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
            sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
        } else if (node.getName()
                .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
            sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
        } else {
            sqlNote = new SqlNote(mContext);
            sqlNote.setContent(node.getLocalJSONFromContent());
            sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
        }
    } else {
        sqlNote = new SqlNote(mContext);
        JSONObject js = node.getLocalJSONFromContent();
        try {
            if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
                JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
                if (note.has(NoteColumns.ID)) {
                    long id = note.getLong(NoteColumns.ID);
                    if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
                        // the id is not available, have to create a new one
                        note.remove(NoteColumns.ID);
                    }
                }
            }

            if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
                JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    if (data.has(DataColumns.ID)) {
                        long dataId = data.getLong(DataColumns.ID);
                        if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
                            // the data id is not available, have to create
                            // a new one
                            data.remove(DataColumns.ID);
                        }
                    }
                }

            }
        } catch (JSONException e) {
            Log.w(TAG, e.toString());
            e.printStackTrace();
        }
        sqlNote.setContent(js);

        Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
        if (parentId == null) {
            Log.e(TAG, "cannot find task's parent id locally");
            throw new ActionFailureException("cannot add local node");
        }
        sqlNote.setParentId(parentId.longValue());
    }

    // create the local node
    sqlNote.setGtaskId(node.getGid());
    sqlNote.commit(false);

    // update gid-nid mapping
    mGidToNid.put(node.getGid(), sqlNote.getId());
    mNidToGid.put(sqlNote.getId(), node.getGid());

    // update meta
    updateRemoteMeta(node.getGid(), sqlNote);
}

From source file:com.xebia.incubator.xebium.RemoteWebDriverBuilder.java

public RemoteWebDriverBuilder(String json) {
    JSONObject jsonObject;
    try {//from  www  .  ja v a 2s .c o  m
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        throw new RuntimeException("Unable to interpret browser information", e);
    }

    try {
        remote = jsonObject.getString(REMOTE);
        jsonObject.remove(REMOTE);
        capabilities = jsonObjectToMap(jsonObject);
    } catch (JSONException e) {
        throw new RuntimeException("Unable to fetch required fields from json string", e);
    }
}

From source file:org.jboss.aerogear.cordova.push.PushPlugin.java

private JSONObject parseConfig(JSONArray data) throws JSONException {
    JSONObject pushConfig = data.getJSONObject(0);
    if (!pushConfig.isNull("android")) {
        final JSONObject android = pushConfig.getJSONObject("android");
        for (Iterator iterator = android.keys(); iterator.hasNext();) {
            String key = (String) iterator.next();
            pushConfig.put(key, android.get(key));
        }/*from w  w w.ja  va  2s  . c om*/

        pushConfig.remove("android");
    }
    return pushConfig;
}

From source file:org.chromium.ChromeI18n.java

private JSONObject toLowerCaseMessage(JSONObject contents) throws JSONException {
    List<String> messages = toStringList(contents.names());
    for (String message : messages) {
        JSONObject value = contents.getJSONObject(message);
        contents.remove(message);
        contents.put(message.toLowerCase(), value);
    }/*from w ww . ja v  a 2 s  . c  o  m*/
    return contents;
}