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:ai.susi.mind.SusiAction.java

/**
 * An action is backed with a JSON data structure. That can be retrieved here.
 * @return the json structure of the action
 *//* w w  w .  java2 s .  c  om*/
public JSONObject toJSONClone() {
    JSONObject j = new JSONObject(true);
    this.json.keySet().forEach(key -> j.put(key, this.json.get(key))); // make a clone
    if (j.has("expression")) {
        j.remove("phrases");
        j.remove("select");
    }
    return j;
}

From source file:com.ichi2.anki2.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 w  w  w.  j  av a  2  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:org.loklak.harvester.TwitterAPI.java

public static JSONObject user2json(User user) throws IOException {
    String jsonstring = TwitterObjectFactory.getRawJSON(user);
    JSONObject json = new JSONObject(jsonstring);
    json.put("retrieval_date", AbstractObjectEntry.utcFormatter.print(System.currentTimeMillis()));
    Object status = json.remove("status"); // we don't need to store the latest status update in the user dump
    // TODO: store the latest status in our message database
    return json;//from  w w w  . j  a va 2s .  com
}

From source file:org.loklak.harvester.TwitterAPI.java

public static JSONObject getNetwork(String screen_name, int maxFollowers, int maxFollowing)
        throws IOException, TwitterException {
    JSONObject map = new JSONObject(true);
    // we clone the maps because we modify it
    map.putAll(getNetworkerNames(screen_name, maxFollowers, Networker.FOLLOWERS));
    map.putAll(getNetworkerNames(screen_name, maxFollowing, Networker.FOLLOWING));
    map.remove("screen_name");

    //int with_before = 0, with_after = 0;

    for (String setname : new String[] { "followers", "unfollowers", "following", "unfollowing" }) {
        JSONArray users = new JSONArray();
        JSONObject names = map.has(setname + "_names") ? (JSONObject) map.remove(setname + "_names") : null;
        if (names != null) {
            for (String sn : names.keySet()) {
                JsonFactory user = DAO.user_dump.get("screen_name", sn);
                if (user != null) {
                    JSONObject usermap = user.getJSON();
                    //if (usermap.get("location") != null && ((String) usermap.get("location")).length() > 0) with_before++;
                    enrichLocation(usermap);
                    correctLocation(usermap);
                    //if (usermap.get("location") != null && ((String) usermap.get("location")).length() > 0) with_after++;
                    users.put(usermap);//  w  ww  .ja va 2s  .  c  om
                }
            }
        }
        //if (users.size() > 0) DAO.log("enrichLocation result: set = " + setname + ", users = " + users.size() + ", with location before = " + with_before + ", with location after = " + with_after + ", success = " + (100 * (with_after - with_before) / users.size()) + "%");
        map.put(setname + "_count", users.length());
        map.put(setname, users);
    }

    return map;
}

From source file:org.collectionspace.chain.storage.TestServiceThroughWebapp.java

@Test
public void testTermsUsed() throws Exception {
    JSONObject data = new JSONObject(
            "{'csid':'','fields':{'personTermGroup':[{'termDisplayName':'David Bowie'}]}}");
    UTF8SafeHttpTester out = tester.jettyDoUTF8(jetty, "POST", "/tenant/core/vocabularies/person",
            data.toString());/*  w w w.j av a  2 s  .com*/
    if (out.getStatus() != 201) {
        System.err.println("out.getStatus() != 201");
    }
    assertEquals(201, out.getStatus());
    JSONObject jo = new JSONObject(out.getContent());
    String p_csid = jo.getString("csid");
    out = tester.jettyDoUTF8(jetty, "GET", "/tenant/core/vocabularies/person/" + p_csid, data.toString());
    String p_refid = new JSONObject(out.getContent()).getJSONObject("fields").getString("refid");
    data = new JSONObject(tester.getResourceString("int4.json"));
    data.remove("valuer");
    data.put("valuer", p_refid);
    out = tester.jettyDoUTF8(jetty, "POST", "/tenant/core/intake/", tester.makeSimpleRequest(data.toString()));
    log.info(out.getContent());
    assertEquals(201, out.getStatus());
    jo = new JSONObject(out.getContent());
    //log.info(jo.toString());
    JSONArray terms_used = jo.getJSONArray("termsUsed");
    assertEquals(1, terms_used.length());
    JSONObject term_used = terms_used.getJSONObject(0);
    //assertEquals("valuer",term_used.getString("sourceFieldName"));
    assertEquals("person", term_used.getString("recordtype"));
    assertEquals("David Bowie", term_used.getString("number"));
}

From source file:org.loklak.api.learning.ConsoleLearning.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization user,
        final JSONObjectWithDefault permissions) throws APIException {
    JSONObject json = new JSONObject(true).put("accepted", true);

    // unauthenticated users are rejected
    if (user.getIdentity().isAnonymous()) {
        json.put("accepted", false);
        json.put("reject-reason", "you must be logged in");
        return json;
    }//from   w w  w  .  j  a  v a2s.  c om
    String client = user.getIdentity().getClient();

    // to categorize the rule, we use project names and tags. Both can be omitted, in that case the project
    // is named "default" and the tag list is empty. Both methods can later be used to retrieve subsets of the
    // rule set
    String project = post.get("project", "default");
    String[] tagsl = post.get("tags", "").split(",");
    JSONArray tags = new JSONArray();
    for (String t : tagsl)
        tags.put(t);
    json.put("project", project);
    json.put("tags", tags);

    // parameters
    String action = post.get("action", "");
    if (action.length() == 0) {
        json.put("accepted", false);
        json.put("reject-reason",
                "you must submit a parameter 'action' containing either the word 'list', 'test', 'learn' or 'delete'");
        return json;
    }
    json.put("action", action);

    if (action.equals("list")) {
        Set<String> projectnames = DAO.susi.getRulesetNames(client);
        JSONObject projects = new JSONObject(true);
        for (String p : projectnames) {
            try {
                JsonTray t = DAO.susi.getRuleset(client, p);
                projects.put(p, t.toJSON().getJSONObject("console"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        json.put("projects", projects);
    } else {
        String name = post.get("name", "");
        if (name.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "you must submit a parameter 'name' containing the rule name");
            return json;
        }
        json.put("name", name);

        if (action.equals("delete")) {
            try {
                JsonTray tray = DAO.susi.getRuleset(client, project);
                if (!tray.has("console"))
                    tray.put("console", new JSONObject(), true);
                JSONObject console = tray.getJSONObject("console");
                console.remove(name);
                tray.commit();
            } catch (IOException e) {
                e.printStackTrace();
                json.put("accepted", false);
                json.put("reject-reason", "deletion the console rule causes an error: " + e.getMessage());
            }
            return json;
        }

        String serviceURL = post.get("url", ""); // i.e. url=http://api.loklak.org/api/console.json?q=SELECT%20*%20FROM%20wikigeodata%20WHERE%20place='$query$';
        if (serviceURL.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "url parameter required");
            return json;
        }
        if (!serviceURL.contains("$query$")) {
            json.put("accepted", false);
            json.put("reject-reason", "the url must contain a string $query$");
            return json;
        }

        String test = post.get("test", "");
        if (test.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "a testquery parameter is required");
            return json;
        }

        // now test the api call
        byte[] serviceResponse = null;
        try {
            serviceResponse = ConsoleService.loadData(serviceURL, test);
        } catch (Exception e) {
            json.put("accepted", false);
            json.put("reject-reason", "the console test load resulted in an error: " + e.getMessage());
            return json;
        }

        // try to find the correct jsonPath automatically
        JSONArray path_computed = new JSONArray();
        Object serviceObject = null;
        try {
            serviceObject = new JSONObject(new JSONTokener(new ByteArrayInputStream(serviceResponse)));
        } catch (JSONException e) {
        }
        if (serviceObject != null && ((JSONObject) serviceObject).length() > 0) {
            for (String s : ((JSONObject) serviceObject).keySet()) {
                if (((JSONObject) serviceObject).get(s) instanceof JSONArray)
                    path_computed.put("$." + s);
            }
        } else {
            try {
                serviceObject = new JSONArray(new JSONTokener(new ByteArrayInputStream(serviceResponse)));
            } catch (JSONException e) {
            }
            if (serviceObject != null && ((JSONArray) serviceObject).length() > 0) {
                path_computed.put("$");
            }
        }

        String path = post.get("path", "");
        if (path.length() == 0) {
            if (path_computed.length() == 1) {
                path = path_computed.getString(0);
            } else {
                json.put("accepted", false);
                json.put("reject-reason",
                        "a data parameter containing the jsonpath to the data object is required. "
                                + (path_computed.length() < 1 ? ""
                                        : "Suggested paths: " + path_computed.toString(0)));
                return json;
            }
        }

        JSONArray data = ConsoleService
                .parseJSONPath(new JSONTokener(new ByteArrayInputStream(serviceResponse)), path);
        if (data == null || data.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "the jsonPath from data object did not recognize an array object");
            return json;
        }

        // find out the attributes in the data object
        Set<String> a = new LinkedHashSet<>();
        for (int i = 0; i < data.length(); i++)
            a.addAll(data.getJSONObject(i).keySet());
        for (int i = 0; i < data.length(); i++) {
            Set<String> doa = data.getJSONObject(i).keySet();
            Iterator<String> j = a.iterator();
            while (j.hasNext())
                if (!doa.contains(j.next()))
                    j.remove();
        }
        JSONArray attributes = new JSONArray();
        for (String s : a)
            attributes.put(s);
        json.put("path_computed", path_computed);

        // construct a new rule
        JSONObject consolerule = new JSONObject(true);
        consolerule.put("example", "http://127.0.0.1:4000/susi/console.json?q=%22SELECT%20*%20FROM%20" + name
                + "%20WHERE%20query=%27" + test + "%27;%22");
        consolerule.put("url", serviceURL);
        consolerule.put("test", test);
        consolerule.put("parser", "json");
        consolerule.put("path", path);
        consolerule.put("attributes", attributes);
        //consolerule.put("author", user.getIdentity().getName());
        //consolerule.put("license", "provided by " + user.getIdentity().getName() + ", licensed as public domain");
        json.put("console", new JSONObject().put(name, consolerule));

        // testing was successful, now decide which action to take: report or store
        if (action.equals("test")) {
            json.put("data", data);
            return json;
        }

        if (action.equals("learn")) {
            try {
                JsonTray tray = DAO.susi.getRuleset(client, project);
                if (!tray.has("console"))
                    tray.put("console", new JSONObject(), true);
                JSONObject console = tray.getJSONObject("console");
                console.put(name, consolerule);
                tray.commit();
            } catch (IOException e) {
                e.printStackTrace();
                json.put("accepted", false);
                json.put("reject-reason", "storing the console rule causes an error: " + e.getMessage());
            }
            return json;
        }
    }

    // fail case
    json.put("accepted", false);
    json.put("reject-reason", "no valid action given");
    return json;
}

From source file:com.pool.rest.CarPoolRestService.java

@GET
@Path("/getUserDetails/{userid}")
@Produces({ MediaType.APPLICATION_JSON })
public Response getUserDetails(@PathParam("userid") String userid) {
    _validateSession();/*from   ww w. j av  a 2  s.c o m*/
    CarPoolService service = new CarPoolService();
    File profileImgFile = null;

    final User usr = service.fetchUserDetails(Long.valueOf(userid));

    usr.setCarpools(null);
    usr.setPasswd(null);
    usr.setVehicles(null);

    String path = request.getSession().getServletContext().getRealPath("/images/");

    if (usr.getProfileImagePath() != null) {
        profileImgFile = new File(path + usr.getProfileImagePath());
    }

    JSONObject jsonObj = new JSONObject(usr);

    try {
        if (profileImgFile != null && profileImgFile.exists()) {
            jsonObj.put("profileImagePath", usr.getProfileImagePath());
        } else {
            jsonObj.remove("profileImagePath");
        }
    } catch (JSONException e) {
    }

    return Response.status(Response.Status.OK).entity(jsonObj.toString()).build();
}

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

public static void adjustConstraints(JSONObject constraints) {
    constraints.remove(S_KEY);
}

From source file:com.hichinaschool.flashcards.libanki.Storage.java

private static void _upgrade(Collection col, int ver) {
    try {//from  ww  w .ja va  2  s  .  co  m
        if (ver < 3) {
            // new deck properties
            for (JSONObject d : col.getDecks().all()) {
                d.put("dyn", 0);
                d.put("collapsed", false);
                col.getDecks().save(d);
            }
        }
        if (ver < 4) {
            col.modSchema();
            ArrayList<JSONObject> clozes = new ArrayList<JSONObject>();
            for (JSONObject m : col.getModels().all()) {
                if (!m.getJSONArray("tmpls").getJSONObject(0).getString("qfmt").contains("{{cloze:")) {
                    m.put("type", Sched.MODEL_STD);
                } else {
                    clozes.add(m);
                }
            }
            for (JSONObject m : clozes) {
                _upgradeClozeModel(col, m);
            }
            col.getDb().execute("UPDATE col SET ver = 4");
        }
        if (ver < 5) {
            col.getDb().execute("UPDATE cards SET odue = 0 WHERE queue = 2");
            col.getDb().execute("UPDATE col SET ver = 5");
        }
        if (ver < 6) {
            col.modSchema();
            for (JSONObject m : col.getModels().all()) {
                m.put("css", new JSONObject(Models.defaultModel).getString("css"));
                JSONArray ar = m.getJSONArray("tmpls");
                for (int i = 0; i < ar.length(); i++) {
                    JSONObject t = ar.getJSONObject(i);
                    if (!t.has("css")) {
                        continue;
                    }
                    m.put("css", m.getString("css") + "\n"
                            + t.getString("css").replace(".card ", ".card" + t.getInt("ord") + 1));
                    t.remove("css");
                }
                col.getModels().save(m);
            }
            col.getDb().execute("UPDATE col SET ver = 6");
        }
        if (ver < 7) {
            col.modSchema();
            col.getDb().execute("UPDATE cards SET odue = 0 WHERE (type = 1 OR queue = 2) AND NOT odid");
            col.getDb().execute("UPDATE col SET ver = 7");
        }
        if (ver < 8) {
            col.modSchema();
            col.getDb().execute("UPDATE cards SET due = due / 1000 WHERE due > 4294967296");
            col.getDb().execute("UPDATE col SET ver = 8");
        }
        if (ver < 9) {
            col.getDb().execute("UPDATE col SET ver = 9");
        }
        if (ver < 10) {
            col.getDb().execute("UPDATE cards SET left = left + left * 1000 WHERE queue = 1");
            col.getDb().execute("UPDATE col SET ver = 10");
        }
        if (ver < 11) {
            col.modSchema();
            for (JSONObject d : col.getDecks().all()) {
                if (d.getInt("dyn") != 0) {
                    int order = d.getInt("order");
                    // failed order was removed
                    if (order >= 5) {
                        order -= 1;
                    }
                    JSONArray ja = new JSONArray(
                            Arrays.asList(new Object[] { d.getString("search"), d.getInt("limit"), order }));
                    d.put("terms", new JSONArray());
                    d.getJSONArray("terms").put(0, ja);
                    d.remove("search");
                    d.remove("limit");
                    d.remove("order");
                    d.put("resched", true);
                    d.put("return", true);
                } else {
                    if (!d.has("extendNew")) {
                        d.put("extendNew", 10);
                        d.put("extendRev", 50);
                    }
                }
                col.getDecks().save(d);
            }
            for (JSONObject c : col.getDecks().allConf()) {
                JSONObject r = c.getJSONObject("rev");
                r.put("ivlFct", r.optDouble("ivlFct", 1));
                if (r.has("ivlfct")) {
                    r.remove("ivlfct");
                }
                r.put("maxIvl", 36500);
                col.getDecks().save(c);
            }
            for (JSONObject m : col.getModels().all()) {
                JSONArray tmpls = m.getJSONArray("tmpls");
                for (int ti = 0; ti < tmpls.length(); ++ti) {
                    JSONObject t = tmpls.getJSONObject(ti);
                    t.put("bqfmt", "");
                    t.put("bafmt", "");
                }
                col.getModels().save(m);
            }
            col.getDb().execute("update col set ver = 11");
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.grobox.blitzmail.MailStorage.java

static public void deleteMail(Context context, String id) {
    SharedPreferences sharedPref = context.getSharedPreferences("BlitzMail", Context.MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = sharedPref.edit();

    JSONObject mails = getMails(context);

    mails.remove(id);

    String mails_str = null;//  ww w .  j  ava 2 s  .  c o  m
    try {
        mails_str = mails.toString(4);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    Log.d("MailStorage", "Removing mail with id " + id);

    prefEditor.putString("mails", mails_str);
    prefEditor.commit();
}