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:reseau.jeu.serveur.Protocole.java

public static String construireMsgChangerEquipe(int etat) {
    JSONObject msg = new JSONObject();

    try {/* w  ww.ja va  2  s. c  om*/
        msg.put("TYPE", JOUEUR_CHANGER_EQUIPE);
        msg.put("STATUS", etat);
    } catch (JSONException jsone) {
        jsone.printStackTrace();
    }

    return msg.toString();
}

From source file:reseau.jeu.serveur.Protocole.java

public static String construireMsgCreatureArrivee(Creature creature) {
    JSONObject msg = new JSONObject();

    try {/*from  w w w  .  j  a v  a  2s. co m*/
        msg.put("TYPE", CREATURE_ARRIVEE);
        msg.put("ID_CREATURE", creature.getId());
    } catch (JSONException jsone) {
        jsone.printStackTrace();
    }

    return msg.toString();
}

From source file:reseau.jeu.serveur.Protocole.java

public static String construireMsgMessage(int idAuteur, String contenu) {
    JSONObject msg = new JSONObject();

    try {//from   w ww .j  a  va  2s. c  o  m
        // Construction de la structure JSON
        msg.put("TYPE", JOUEUR_MESSAGE);
        msg.put("ID_JOUEUR", idAuteur);
        msg.put("MESSAGE", contenu);
    } catch (JSONException jsone) {
        jsone.printStackTrace();
    }

    return msg.toString();
}

From source file:reseau.jeu.serveur.Protocole.java

public static String construireMsgJoueurDeconnecte(int idJoueur) {
    JSONObject msg = new JSONObject();

    try {//w w  w. j a  v a2 s .  c  o  m
        // Construction de la structure JSON
        msg.put("TYPE", JOUEUR_DECONNEXION);
        msg.put("ID_JOUEUR", idJoueur);
    } catch (JSONException jsone) {
        jsone.printStackTrace();
    }

    return msg.toString();
}

From source file:reseau.jeu.serveur.Protocole.java

public static String construireMsgEquipeAPerdue(int id) {
    JSONObject msg = new JSONObject();

    try {/*from   w w  w  .  j a  va 2 s  .  c  om*/
        // Construction de la structure JSON
        msg.put("TYPE", EQUIPE_A_PERDUE);
        msg.put("ID_EQUIPE", id);
    } catch (JSONException jsone) {
        jsone.printStackTrace();
    }

    return msg.toString();
}

From source file:io.appium.uiautomator2.handler.GetDeviceSize.java

@Override
public AppiumResponse safeHandle(IHttpRequest request) {
    Logger.info("Get window size of the device");
    // only makes sense on a device
    final JSONObject res = new JSONObject();
    try {//from  ww  w  .  j a  va2s.c om
        res.put("height", getUiDevice().getDisplayHeight());
        res.put("width", getUiDevice().getDisplayWidth());
    } catch (JSONException e) {
        Logger.error("Exception while reading JSON: ", e);
        return new AppiumResponse(getSessionId(request), WDStatus.JSON_DECODER_ERROR, e);
    }
    return new AppiumResponse(getSessionId(request), WDStatus.SUCCESS, res);
}

From source file:org.ohmage.reminders.types.location.LocTrigService.java

private void uploadLatestLocation() {

    final String KEY_LOC_LAT = "latitude";
    final String KEY_LOC_LONG = "longitude";
    final String KEY_LOC_ACC = "accuracy";
    final String KEY_LOC_PROVIDER = "provider";
    final String KEY_LOC_TIME = "time";
    final String TIME_STAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";

    //Check if any location update has been received
    if (mLastKnownLocTime == 0 || mLastKnownLoc == null) {
        return;/*from w  w  w  .j  av  a2 s .c  om*/
    }

    //If 'upload always' is not enabled, check for the
    //compile time constants and upload only if it is
    //allowed
    if (!mLocTraceUploadAlways) {

        //Check if the user has moved at least the distance specified
        if (mLastKnownLoc.distanceTo(mLastLocTrace) < LocTrigConfig.LOC_TRACE_MIN_DISTANCE_FOR_UPLOAD) {

            //Before discarding the trace, check the time stamp
            //of the last upload. If it has been longer than the
            //specified time, upload.
            if (mLastKnownLoc.getTime()
                    - mLastLocTrace.getTime() < LocTrigConfig.LOC_TRACE_MAX_GAP_BETWEEN_UPLOADS) {

                Log.v(TAG, "LocTrigService: Skipping the location" + " trace upload");
                return;
            }
        }
    }

    //TODO move loc to JSON conversion to a common place
    //The trigger details upload also has the same logic
    JSONObject jLoc = new JSONObject();

    try {
        jLoc.put(KEY_LOC_LAT, mLastKnownLoc.getLatitude());
        jLoc.put(KEY_LOC_LONG, mLastKnownLoc.getLongitude());
        jLoc.put(KEY_LOC_ACC, mLastKnownLoc.getAccuracy());
        jLoc.put(KEY_LOC_PROVIDER, mLastKnownLoc.getProvider());

        SimpleDateFormat dateFormat = new SimpleDateFormat(TIME_STAMP_FORMAT);
        jLoc.put(KEY_LOC_TIME, dateFormat.format(new Date(mLastKnownLoc.getTime())));
    } catch (JSONException e) {

        Log.e(TAG, "LocTrigService: Error while converting " + " location to JSON for tracing", e);
        return;
    }

    String msg = "Location trace: " + jLoc.toString();
    //Upload the trace using LogProbe
    Log.v(TAG, "LocTrigService: Upload location trace: " + msg);

    //Save this location locally
    mLastLocTrace.set(mLastKnownLoc);
}

From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java

private void onPrepareDialog(int id, StyledDialog styledDialog) {
    Resources res = getResources();
    switch (id) {
    case DIALOG_CUSTOM_STUDY_DETAILS:
        styledDialog.setTitle(res.getStringArray(R.array.custom_study_options_labels)[mCustomDialogChoice]);
        switch (mCustomDialogChoice + 1) {
        case CUSTOM_STUDY_NEW:
            if (AnkiDroidApp.colIsOpen()) {
                Collection col = AnkiDroidApp.getCol();
                mCustomStudyTextView1.setText(res.getString(R.string.custom_study_new_total_new,
                        col.getSched().totalNewForCurrentDeck()));
            }/*from  ww w . j  a va 2 s  . c om*/
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_new_extend));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendNew", 10)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendNew", n)
                                            .commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendNew", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(n, 0);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(),
                                            getResources().getString(R.string.custom_study_invalid_number),
                                            false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_REV:
            if (AnkiDroidApp.colIsOpen()) {
                Collection col = AnkiDroidApp.getCol();
                mCustomStudyTextView1.setText(res.getString(R.string.custom_study_rev_total_rev,
                        col.getSched().totalRevForCurrentDeck()));
            }
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_rev_extend));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendRev", 10)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendRev", n)
                                            .commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendRev", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(0, n);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(),
                                            getResources().getString(R.string.custom_study_invalid_number),
                                            false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_FORGOT:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_forgotten));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("forgottenDays", 2)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            JSONArray ar = new JSONArray();
                            try {
                                int forgottenDays = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                ar.put(0, 1);
                                createFilteredDeck(ar,
                                        new Object[] { String.format(Locale.US, "rated:%d:1", forgottenDays),
                                                9999, Sched.DYN_RANDOM },
                                        false);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_AHEAD:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_ahead));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("aheadDays", 1)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int days = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(), new Object[] {
                                        String.format(Locale.US, "prop:due<=%d", days), 9999, Sched.DYN_DUE },
                                        true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_RANDOM:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_random));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("randomCards", 100)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int randomCards = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(),
                                        new Object[] { "", randomCards, Sched.DYN_RANDOM }, true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_PREVIEW:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_preview));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("previewDays", 1)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String previewDays = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(),
                                    new Object[] { "is:new added:" + previewDays, 9999, Sched.DYN_OLDEST },
                                    false);
                        }
                    });
            break;

        case CUSTOM_STUDY_TAGS:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_tags));
            mCustomStudyEditText
                    .setText(AnkiDroidApp.getSharedPrefs(getActivity()).getString("customTags", ""));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String tags = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(),
                                    new Object[] { "(is:new or is:due) " + tags, 9999, Sched.DYN_RANDOM },
                                    true);
                        }
                    });
            break;
        }
    }
}

From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java

private void createFilteredDeck(JSONArray delays, Object[] terms, Boolean resched) {
    JSONObject dyn;
    if (AnkiDroidApp.colIsOpen()) {
        Collection col = AnkiDroidApp.getCol();
        try {/*from  ww w.  ja va  2  s .  c om*/
            String deckName = col.getDecks().current().getString("name");
            String customStudyDeck = getResources().getString(R.string.custom_study_deck_name);
            JSONObject cur = col.getDecks().byName(customStudyDeck);
            if (cur != null) {
                if (cur.getInt("dyn") != 1) {
                    StyledDialog.Builder builder = new StyledDialog.Builder(getActivity());
                    builder.setMessage(R.string.custom_study_deck_exists);
                    builder.setNegativeButton(getResources().getString(R.string.cancel), new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //
                        }
                    });
                    builder.create().show();
                    return;
                } else {
                    // safe to empty
                    col.getSched().emptyDyn(cur.getLong("id"));
                    // reuse; don't delete as it may have children
                    dyn = cur;
                    col.getDecks().select(cur.getLong("id"));
                }
            } else {
                long did = col.getDecks().newDyn(customStudyDeck);
                dyn = col.getDecks().get(did);
            }
            // and then set various options
            dyn.put("delays", delays);
            JSONArray ar = dyn.getJSONArray("terms");
            ar.getJSONArray(0).put(0,
                    new StringBuilder("deck:\"").append(deckName).append("\" ").append(terms[0]).toString());
            ar.getJSONArray(0).put(1, terms[1]);
            ar.getJSONArray(0).put(2, terms[2]);
            dyn.put("resched", resched);

            if (mFragmented) {
                Bundle config = new Bundle();
                config.putString("searchSuffix", "'deck:" + dyn.getString("name") + "'");
                initAllContentViews(getLayoutInflater(config));
                finishCongrats();
            } else {
                // Load a new fragment with the filtered deck view. The config passed is null, so it uses the
                // current deck. The deck we just created is internally set as the current deck.
                ((StudyOptionsActivity) getActivity()).loadContent(false, null);
            }

            // Initial rebuild
            mProgressDialog = StyledProgressDialog.show(getActivity(), "",
                    getResources().getString(R.string.rebuild_custom_study_deck), true);
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REBUILD_CRAM, mRebuildCustomStudyListener,
                    new DeckTask.TaskData(AnkiDroidApp.getCol(), AnkiDroidApp.getCol().getDecks().selected(),
                            mFragmented));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.loklak.api.iot.EarthquakeServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    String eqBaseUrl = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/";

    // Earthquakes happening per hour.
    String SIGNIFICANT_HOUR = "summary/significant_hour.geojson";
    String MAGNITUDE_4_5_HOUR = "summary/4.5_hour.geojson";
    String MAGNITUDE_2_5_HOUR = "summary/2.5_hour.geojson";
    String MAGNITUDE_1_0_HOUR = "summary/1.0_hour.geojson";
    String ALL_HOUR = "summary/all_hour.geojson";

    // Earthquakes happening per day.
    String SIGNIFICANT_DAY = "summary/significant_day.geojson";
    String MAGNITUDE_4_5_DAY = "summary/4.5_day.geojson";
    String MAGNITUDE_2_5_DAY = "summary/2.5_day.geojson";
    String MAGNITUDE_1_0_DAY = "summary/1.0_day.geojson";
    String ALL_DAY = "summary/all_day.geojson";

    // Earthquakes in the last 7 days.
    String SIGNIFICANT_WEEK = "summary/significant_week.geojson";
    String MAGNITUDE_4_5_WEEK = "summary/4.5_week.geojson";
    String MAGNITUDE_2_5_WEEK = "summary/2.5_week.geojson";
    String MAGNITUDE_1_0_WEEK = "summary/1.0_week.geojson";
    String ALL_WEEK = "summary/all_week.geojson";

    // Earthquakes in the last 30 days.
    String SIGNIFICANT_MONTH = "summary/significant_month.geojson";
    String MAGNITUDE_4_5_MONTH = "summary/4.5_month.geojson";
    String MAGNITUDE_2_5_MONTH = "summary/2.5_month.geojson";
    String MAGNITUDE_1_0_MONTH = "summary/1.0_month.geojson";
    String ALL_MONTH = "summary/all_month.geojson";

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;/*from  w ww  . java 2  s .c o m*/
    }

    String duration = post.get("duration", "");
    String magnitude = post.get("magnitude", "");

    String earthquakeQueryURL = "";

    if ("hour".equals(duration)) {
        if ("4.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_4_5_HOUR;
        } else if ("2.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_2_5_HOUR;
        } else if ("1.0".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_HOUR;
        } else if ("significant".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_HOUR;
        } else {
            earthquakeQueryURL = eqBaseUrl + ALL_HOUR;
        }
    } else if ("day".equals(duration)) {
        if ("4.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_4_5_DAY;
        } else if ("2.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_2_5_DAY;
        } else if ("1.0".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_DAY;
        } else if ("significant".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_DAY;
        } else {
            earthquakeQueryURL = eqBaseUrl + ALL_DAY;
        }
    } else if ("week".equals(duration)) {
        if ("4.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_4_5_WEEK;
        } else if ("2.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_2_5_WEEK;
        } else if ("1.0".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_WEEK;
        } else if ("significant".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_WEEK;
        } else {
            earthquakeQueryURL = eqBaseUrl + ALL_WEEK;
        }
    } else if ("month".equals(duration)) {
        if ("4.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_4_5_MONTH;
        } else if ("2.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_2_5_MONTH;
        } else if ("1.0".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_MONTH;
        } else if ("significant".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_MONTH;
        } else {
            earthquakeQueryURL = eqBaseUrl + ALL_MONTH;
        }
    } else {
        earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_HOUR;
    }
    // earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_MONTH;

    JSONObject json = readJsonFromUrl(earthquakeQueryURL);
    json.put("query", earthquakeQueryURL);

    PrintWriter sos = response.getWriter();
    sos.print(json.toString(2));
    sos.println();
}