Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

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

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

From source file:me.mast3rplan.phantombot.cache.FollowersCache.java

public int quickUpdate(String channel) throws Exception {
    JSONObject j = TwitchAPIv3.instance().GetChannelFollows(channel, 100, 0, false);

    if (j.getBoolean("_success")) {
        if (j.getInt("_http") == 200) {
            int i = j.getInt("_total");

            Map<String, JSONObject> newCache = Maps.newHashMap();
            JSONArray followers = j.getJSONArray("follows");

            for (int b = 0; b < followers.length(); b++) {
                JSONObject follower = followers.getJSONObject(b);
                newCache.put(follower.getJSONObject("user").getString("name"), follower);
            }/*www .  jav a2  s  .c  om*/

            for (String key : newCache.keySet()) {
                if (cache == null || !cache.containsKey(key)) {
                    cache.put(key, newCache.get(key));
                    EventBus.instance().post(
                            new TwitchFollowEvent(key, PhantomBot.instance().getChannel("#" + this.channel)));
                }
            }

            this.count = cache.size();

            return i;
        } else {
            throw new Exception("[HTTPErrorException] HTTP " + j.getInt("status") + " " + j.getString("error")
                    + ". req=" + j.getString("_type") + " " + j.getString("_url") + " " + j.getString("_post")
                    + "   " + (j.has("message") && !j.isNull("message") ? "message=" + j.getString("message")
                            : "content=" + j.getString("_content")));
        }
    } else {
        throw new Exception("[" + j.getString("_exception") + "] " + j.getString("_exceptionMessage"));
    }
}

From source file:me.mast3rplan.phantombot.cache.FollowersCache.java

private void updateCache(int newCount) throws Exception {
    Map<String, JSONObject> newCache = Maps.newHashMap();

    final List<JSONObject> responses = Lists.newArrayList();
    List<Thread> threads = Lists.newArrayList();

    hasFail = false;/*  ww w  .  ja  v  a 2 s  .co m*/

    Calendar c = Calendar.getInstance();

    c.add(Calendar.HOUR, 1);

    nextFull = c.getTime();

    for (int i = 0; i < Math.ceil(newCount / 100.0); i++) {
        final int offset = i * 100;
        Thread thread = new Thread() {
            @Override
            public void run() {
                JSONObject j = TwitchAPIv3.instance().GetChannelFollows(channel, 100, offset, true);

                if (j.getBoolean("_success")) {
                    if (j.getInt("_http") == 200) {
                        responses.add(j);

                    } else {
                        try {
                            throw new Exception("[HTTPErrorException] HTTP " + j.getInt("status") + " "
                                    + j.getString("error") + ". req=" + j.getString("_type") + " "
                                    + j.getString("_url") + " " + j.getString("_post") + "   "
                                    + (j.has("message") && !j.isNull("message")
                                            ? "message=" + j.getString("message")
                                            : "content=" + j.getString("_content")));
                        } catch (Exception e) {
                            com.gmt2001.Console.out
                                    .println("FollowersCache.updateCache>>Failed to update followers: "
                                            + e.getMessage());
                            com.gmt2001.Console.err.logStackTrace(e);
                        }
                    }
                } else {
                    try {
                        throw new Exception(
                                "[" + j.getString("_exception") + "] " + j.getString("_exceptionMessage"));
                    } catch (Exception e) {
                        if ((e.getMessage().startsWith("[SocketTimeoutException]")
                                || e.getMessage().startsWith("[IOException]")) && !hasFail) {
                            hasFail = true;

                            Calendar c = Calendar.getInstance();

                            if (lastFail.after(new Date())) {
                                numfail++;
                            } else {
                                numfail = 1;
                            }

                            c.add(Calendar.MINUTE, 1);

                            lastFail = c.getTime();

                            if (numfail >= 5) {
                                timeoutExpire = c.getTime();
                            }
                        }

                        com.gmt2001.Console.out.println(
                                "FollowersCache.updateCache>>Failed to update followers: " + e.getMessage());
                        com.gmt2001.Console.err.logStackTrace(e);
                    }
                }
            }
        };
        threads.add(thread);
        thread.start();
    }

    for (Thread thread : threads) {
        thread.join();
    }

    for (JSONObject response : responses) {
        JSONArray followers = response.getJSONArray("follows");

        if (followers.length() == 0) {
            break;
        }

        for (int j = 0; j < followers.length(); j++) {
            JSONObject follower = followers.getJSONObject(j);
            newCache.put(follower.getJSONObject("user").getString("name"), follower);
        }
    }

    List<String> followers = Lists.newArrayList();
    List<String> unfollowers = Lists.newArrayList();

    for (String key : newCache.keySet()) {
        if (cache == null || !cache.containsKey(key)) {
            followers.add(key);
        }
    }

    if (cache != null) {
        for (String key : cache.keySet()) {
            if (!newCache.containsKey(key)) {
                unfollowers.add(key);
            }
        }
    }

    this.cache = newCache;
    this.count = newCache.size();

    for (String follower : followers) {
        EventBus.instance()
                .post(new TwitchFollowEvent(follower, PhantomBot.instance().getChannel("#" + this.channel)));
    }

    for (String follower : unfollowers) {
        EventBus.instance()
                .post(new TwitchUnfollowEvent(follower, PhantomBot.instance().getChannel("#" + this.channel)));
    }

    if (firstUpdate) {
        firstUpdate = false;
        EventBus.instance()
                .post(new TwitchFollowsInitializedEvent(PhantomBot.instance().getChannel("#" + this.channel)));
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.DownloaderFE.java

private List<DownloadItem> retrieveList() throws Exception {
    List<DownloadItem> diList = new ArrayList<DownloadItem>();
    String url = "";
    if (action.equals(INTENT_ACTION_SEARCH_TAG)) {
        url = FE_API_TAG + URLEncoder.encode(searchCriterion, "UTF-8");
    } else if (action.equals(INTENT_ACTION_SEARCH_USER)) {
        url = FE_API_USER + URLEncoder.encode(searchCriterion, "UTF-8");
    } else {//from   w ww .  j av  a 2 s .c o m
        throw new IOException("Incorrect criterion used for this call");
    }
    Log.i(TAG, "Url: " + url);

    String jsonString = downloaderUtils.downloadJSONString(url);
    Log.v(TAG, "JSON String: " + jsonString);
    JSONObject jsonObject = new JSONObject(jsonString);
    String status = jsonObject.getString("response_type");
    if (!status.equals("ok")) {
        throw new IOException("Status is not OK. Status: " + status);
    }
    JSONArray jsonArray = jsonObject.getJSONObject("results").getJSONArray("sets");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonItem = jsonArray.getJSONObject(i);
        int cardId;
        if (jsonItem.has("original_card_set_id") && !jsonItem.isNull("original_card_set_id")) {
            cardId = jsonItem.getInt("original_card_set_id");
        } else {
            cardId = jsonItem.getInt("card_set_id");
        }

        String address = FE_API_CARDSET + cardId;

        DownloadItem di = new DownloadItem(DownloadItem.ItemType.Database, jsonItem.getString("title"),
                jsonItem.getString("description"), address);
        diList.add(di);
    }
    return diList;
}

From source file:com.ryansmertz.sunshine.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//from   w ww.  j  a  va 2  s .  c o m
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting,
                System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert

        Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder);

        cVVector = new Vector<ContentValues>(cur.getCount());
        if (cur.moveToFirst()) {
            do {
                ContentValues cv = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(cur, cv);
                cVVector.add(cv);
            } while (cur.moveToNext());
        }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        return resultStrs;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

From source file:com.ichi2.libanki.test.ModelsTestCase.java

@MediumTest
public void test_modelCopy() throws JSONException {
    Collection deck = Shared.getEmptyDeck(getInstrumentation().getContext());
    JSONObject m = deck.getModels().current();
    JSONObject m2 = deck.getModels().copy(m);
    assertEquals(m2.getString("name"), "Basic copy");
    MoreAsserts.assertNotEqual(m2.getInt("id"), m.getInt("id"));
    assertEquals(m2.getJSONArray("flds").length(), 2);
    assertEquals(m.getJSONArray("flds").length(), 2);
    assertEquals(m2.getJSONArray("flds").length(), m.getJSONArray("flds").length());
    assertEquals(m.getJSONArray("tmpls").length(), 1);
    assertEquals(m2.getJSONArray("tmpls").length(), 1);
    assertEquals(deck.getModels().scmhash(m), deck.getModels().scmhash(m2));
}

From source file:de.dmxcontrol.executor.EntityExecutorPage.java

public static EntityExecutorPage Receive(JSONObject o) {
    EntityExecutorPage entity = null;/*from  w  w w . j  a v  a  2 s .co  m*/
    try {
        if (o.getString("Type").equals(NetworkID)) {
            entity = new EntityExecutorPage(o.getInt("Number"), o.getString("Name"));
            entity.guid = o.getString("GUID");

            ArrayList<String> executors = new ArrayList<String>();

            for (int i = 0; i < o.getJSONArray("Executors").length(); i++) {
                executors.add(o.getJSONArray("Executors").getString(i));
            }

            entity.setExecutorGUIDs(executors);
        }
    } catch (Exception e) {
        Log.e("UDP Listener: ", e.getMessage());
        DMXControlApplication.SaveLog();
    }
    o = null;
    if (o == null) {
        ;
    }
    return entity;
}

From source file:info.zamojski.soft.towercollector.parsers.update.UpdateFeedParser.java

private int getVersionCode(JSONObject object) throws JSONException {
    return object.getInt(VERSION_CODE);
}

From source file:ac.robinson.ticqr.TicQRActivity.java

@Override
protected void onPageIdFound(String id) {
    // Toast.makeText(TicQRActivity.this, "Page ID found", Toast.LENGTH_SHORT).show();

    RequestParams params = new RequestParams("lookup", id);
    new AsyncHttpClient().get(SERVER_URL, params, new JsonHttpResponseHandler() {
        private void handleFailure(int reason) {
            // TODO: there are concurrency issues here with hiding the progress bar and showing the rescan button
            // TODO: (e.g., this task and photo taking complete in different orders)
            findViewById(R.id.parse_progress).setVisibility(View.GONE);
            getSupportActionBar().setTitle(R.string.title_activity_image_only);
            supportInvalidateOptionsMenu();
            Toast.makeText(TicQRActivity.this, getString(reason), Toast.LENGTH_SHORT).show();
        }/* w  w w .  j  av  a 2  s. c o  m*/

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
                if ("ok".equals(response.getString("status"))) {
                    mDestinationEmail = response.isNull("destination") ? null
                            : response.getString("destination");

                    JSONArray boxes = response.getJSONArray("tickBoxes");
                    if (boxes != null && !boxes.isNull(0)) {
                        for (int i = 0; i < boxes.length(); i++) {
                            JSONObject jsonBox = boxes.getJSONObject(i);

                            TickBoxHolder box = new TickBoxHolder(
                                    new PointF(jsonBox.getInt("x"), jsonBox.getInt("y")),
                                    jsonBox.getString("description"), jsonBox.getInt("quantity"));

                            box.ticked = true; // first we assume all boxes are ticked
                            box.foundOnImage = false; // (but not yet found on the image)
                            mServerTickBoxes.add(box);
                        }
                    }

                    mBoxesLoaded = true;
                    if (mImageParsed) {
                        verifyBoxes();
                    }
                } else {
                    handleFailure(R.string.hint_json_error);
                }
            } catch (JSONException e) {
                handleFailure(R.string.hint_json_error);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            handleFailure(R.string.hint_connection_error);
        }
    });
}

From source file:edu.pdx.its.portal.routelandia.entities.Station.java

public Station(JSONObject json) throws JSONException {
    this.stationid = json.getInt("stationid");
    this.highwayid = json.getInt("highwayid");

    if (!json.isNull("geojson_raw")) {
        JSONObject geojsonRaw = json.getJSONObject("geojson_raw");

        //Create json array from coordinates
        JSONArray coordinates = (JSONArray) geojsonRaw.get("coordinates");

        //for each json array coordinates, create latlng and
        //add it to the list latlng of its station
        for (int j = 0; j < coordinates.length(); j++) {
            double latitude = Double.parseDouble(((JSONArray) coordinates.get(j)).get(1).toString());
            double longtitude = Double.parseDouble(((JSONArray) coordinates.get(j)).get(0).toString());
            this.addLatLng(new LatLng(latitude, longtitude));
        }//from   w  w  w.j  a  v a2 s .c o  m
    }
}