List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:uk.co.petertribble.jproc.parse.JSONParser.java
private static JProcStatus getStatus(JSONObject jo) { JProcStatus jps = new JProcStatus(); try {/*from ww w .j a va2 s. co m*/ jps.insert(jo.getInt("lwpid"), jo.getLong("utime"), jo.getLong("nutime"), jo.getLong("stime"), jo.getLong("nstime"), jo.getLong("cutime"), jo.getLong("ncutime"), jo.getLong("cstime"), jo.getLong("ncstime")); } catch (JSONException jse) { return null; } return jps; }
From source file:uk.co.petertribble.jproc.parse.JSONParser.java
private static JProcUsage getUsage(JSONObject jo) { JProcUsage jpu = new JProcUsage(); try {/*from w w w. j ava 2 s . c o m*/ jpu.insert(jo.getInt("lwpid"), jo.getInt("count"), jo.getLong("rtime"), jo.getLong("nrtime"), jo.getLong("utime"), jo.getLong("nutime"), jo.getLong("stime"), jo.getLong("nstime"), jo.getLong("minf"), jo.getLong("majf"), jo.getLong("nswap"), jo.getLong("inblk"), jo.getLong("oublk"), jo.getLong("msnd"), jo.getLong("mrcv"), jo.getLong("sigs"), jo.getLong("vctx"), jo.getLong("ictx"), jo.getLong("sysc"), jo.getLong("ioch")); } catch (JSONException jse) { return null; } return jpu; }
From source file:uk.co.petertribble.jproc.parse.JSONParser.java
private static JProcInfo getInfo(JSONObject jo) { JProcInfo jpi = new JProcInfo(); try {/* w w w.java2s. co m*/ jpi.insert(jo.getInt("pid"), jo.getInt("ppid"), jo.getInt("uid"), jo.getInt("euid"), jo.getInt("gid"), jo.getInt("egid"), jo.getInt("nlwp"), jo.getLong("size"), jo.getLong("rssize"), jo.getLong("stime"), jo.getLong("etime"), jo.getLong("ntime"), jo.getLong("ectime"), jo.getLong("nctime"), jo.getInt("taskid"), jo.getInt("projid"), jo.getInt("zoneid"), jo.getInt("contract"), jo.getString("fname")); } catch (JSONException jse) { return null; } return jpi; }
From source file:uk.co.petertribble.jproc.parse.JSONParser.java
private static JProcLwpStatus getLwpStatus(JSONObject jo) { JProcLwpStatus jpls = new JProcLwpStatus(); try {/*from w w w . ja va 2s. c om*/ jpls.insert(jo.getInt("pid"), jo.getInt("lwpid"), jo.getLong("utime"), jo.getLong("nutime"), jo.getLong("stime"), jo.getLong("nstime")); } catch (JSONException jse) { return null; } return jpls; }
From source file:uk.co.petertribble.jproc.parse.JSONParser.java
private static JProcLwpInfo getLwpInfo(JSONObject jo) { JProcLwpInfo jpli = new JProcLwpInfo(); try {/* ww w . ja v a 2s . c om*/ jpli.insert(jo.getInt("pid"), jo.getInt("lwpid"), jo.getLong("stime"), jo.getLong("etime"), jo.getLong("ntime")); } catch (JSONException jse) { return null; } return jpli; }
From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java
private ArrayList<Torrent> parseJsonRetrieveTorrents(JSONObject response) throws JSONException { // Parse response ArrayList<Torrent> torrents = new ArrayList<Torrent>(); JSONArray rarray = response.getJSONArray("torrents"); for (int i = 0; i < rarray.length(); i++) { JSONObject tor = rarray.getJSONObject(i); // Add the parsed torrent to the list float have = (float) (tor.getLong(RPC_DOWNLOADSIZE1) + tor.getLong(RPC_DOWNLOADSIZE2)); long total = tor.getLong(RPC_TOTALSIZE); // Error is a number, see https://trac.transmissionbt.com/browser/trunk/libtransmission/transmission.h#L1747 // We only consider it a real error if it is local (blocking), which is error code 3 boolean hasError = tor.getInt(RPC_ERROR) == 3; String errorString = tor.getString(RPC_ERRORSTRING).trim(); String commentString = tor.getString(RPC_COMMENT).trim(); if (!commentString.equals("")) { errorString = errorString.equals("") ? commentString : errorString + "\n" + commentString; }/*from w ww . j a va 2 s. com*/ String locationDir = tor.getString(RPC_DOWNLOADDIR); if (!locationDir.endsWith(settings.getOS().getPathSeperator())) { locationDir += settings.getOS().getPathSeperator(); } // @formatter:off torrents.add(new Torrent(tor.getInt(RPC_ID), null, tor.getString(RPC_NAME), hasError ? TorrentStatus.Error : getStatus(tor.getInt(RPC_STATUS)), locationDir, tor.getInt(RPC_RATEDOWNLOAD), tor.getInt(RPC_RATEUPLOAD), tor.getInt(RPC_PEERSSENDING), tor.getInt(RPC_PEERSCONNECTED), tor.getInt(RPC_PEERSGETTING), tor.getInt(RPC_PEERSCONNECTED), tor.getInt(RPC_ETA), tor.getLong(RPC_DOWNLOADSIZE1) + tor.getLong(RPC_DOWNLOADSIZE2), tor.getLong(RPC_UPLOADEDEVER), tor.getLong(RPC_TOTALSIZE), //(float) tor.getDouble(RPC_PERCENTDONE), (total == 0 ? 0 : have / (float) total), (total == 0 ? 0 : (have + (float) tor.getLong(RPC_AVAILABLE)) / (float) total), // No label/category/group support in the RPC API for now null, new Date(tor.getLong(RPC_DATEADDED) * 1000L), new Date(tor.getLong(RPC_DATEDONE) * 1000L), errorString, settings.getType())); // @formatter:on } // Return the list return torrents; }
From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java
private ArrayList<TorrentFile> parseJsonFileList(JSONObject response, Torrent torrent) throws JSONException { // Parse response ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>(); JSONArray rarray = response.getJSONArray("torrents"); if (rarray.length() > 0) { JSONArray files = rarray.getJSONObject(0).getJSONArray("files"); JSONArray fileStats = rarray.getJSONObject(0).getJSONArray("fileStats"); for (int i = 0; i < files.length(); i++) { JSONObject file = files.getJSONObject(i); JSONObject stat = fileStats.getJSONObject(i); // @formatter:off torrentfiles.add(new TorrentFile(String.valueOf(i), file.getString(RPC_FILE_NAME), file.getString(RPC_FILE_NAME), torrent.getLocationDir() + file.getString(RPC_FILE_NAME), file.getLong(RPC_FILE_LENGTH), file.getLong(RPC_FILE_COMPLETED), convertTransmissionPriority(stat.getBoolean(RPC_FILESTAT_WANTED), stat.getInt(RPC_FILESTAT_PRIORITY)))); // @formatter:on }//from ww w . j av a 2 s. c o m } // Return the list return torrentfiles; }
From source file:com.mio.jrdv.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.//w w w . j ava 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); } //////////////////////////////////////////////////////////////////////////////////////////// ////// //////////////////////////////////////////////////////////////////////////////////////////// //////NO SE USA SE PASA AL FORECAST ADAPTER // The lines in getWeatherDataFromJson where we requery the database after the insert. //vamoa acambiarlo por el nuevo FroreCastAdapter!!: //////////////////////////////////////////////////////////////////////////////////////////// // // 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 // //esto no hace nada !!lo que hace es que inserte 0!!!! si no lo hacemos por medio un 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; int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:com.nextgis.forestinspector.activity.MainActivity.java
protected boolean getInspectorDetail(Connection connection, long resourceId, String login) { String sURL = NGWUtil.getFeaturesUrl(connection.getURL(), resourceId, "login=" + login); try {//from ww w . jav a2s . c o m HttpGet get = new HttpGet(sURL); get.setHeader("Cookie", connection.getCookie()); get.setHeader("Accept", "*/*"); HttpResponse response = connection.getHttpClient().execute(get); HttpEntity entity = response.getEntity(); JSONArray features = new JSONArray(EntityUtils.toString(entity)); if (features.length() == 0) return false; JSONObject jsonDetail = features.getJSONObject(0); int id = jsonDetail.getInt(NGWUtil.NGWKEY_ID); GeoGeometry geom = GeoGeometryFactory.fromWKT(jsonDetail.getString(NGWUtil.NGWKEY_GEOM)); GeoEnvelope env = geom.getEnvelope(); JSONObject fields = jsonDetail.getJSONObject(NGWUtil.NGWKEY_FIELDS); String sUserName = fields.getString(Constants.KEY_INSPECTOR_USER); String sUserDescription = fields.getString(Constants.KEY_INSPECTOR_USER_DESC); // if no exception store data in config final SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit(); edit.putInt(SettingsConstants.KEY_PREF_USERID, id); edit.putString(SettingsConstants.KEY_PREF_USER, sUserName); edit.putString(SettingsConstants.KEY_PREF_USERDESC, sUserDescription); edit.putFloat(SettingsConstants.KEY_PREF_USERMINX, (float) env.getMinX()); edit.putFloat(SettingsConstants.KEY_PREF_USERMINY, (float) env.getMinY()); edit.putFloat(SettingsConstants.KEY_PREF_USERMAXX, (float) env.getMaxX()); edit.putFloat(SettingsConstants.KEY_PREF_USERMAXY, (float) env.getMaxY()); return edit.commit(); } catch (IOException | JSONException e) { e.printStackTrace(); return false; } }
From source file:net.dv8tion.jda.core.handle.ReadyHandler.java
public void guildLoadComplete(JSONObject content) { api.getClient().setChunkingAndSyncing(false); EntityBuilder builder = api.getEntityBuilder(); JSONArray privateChannels = content.getJSONArray("private_channels"); if (api.getAccountType() == AccountType.CLIENT) { JSONArray relationships = content.getJSONArray("relationships"); JSONArray presences = content.getJSONArray("presences"); JSONObject notes = content.getJSONObject("notes"); JSONArray readstates = content.has("read_state") ? content.getJSONArray("read_state") : null; JSONArray guildSettings = content.has("user_guild_settings") ? content.getJSONArray("user_guild_settings") : null;/*from w w w .j a va 2s . co m*/ for (int i = 0; i < relationships.length(); i++) { JSONObject relationship = relationships.getJSONObject(i); Relationship r = builder.createRelationship(relationship); if (r == null) JDAImpl.LOG.fatal("Provided relationship in READY with an unknown type! JSON: " + relationship.toString()); } for (int i = 0; i < presences.length(); i++) { JSONObject presence = presences.getJSONObject(i); String userId = presence.getJSONObject("user").getString("id"); FriendImpl friend = (FriendImpl) api.asClient().getFriendById(userId); if (friend == null) WebSocketClient.LOG.warn( "Received a presence in the Presences array in READY that did not correspond to a cached Friend! JSON: " + presence); else builder.createPresence(friend, presence); } } for (int i = 0; i < privateChannels.length(); i++) { JSONObject chan = privateChannels.getJSONObject(i); ChannelType type = ChannelType.fromId(chan.getInt("type")); switch (type) { case PRIVATE: builder.createPrivateChannel(chan); break; case GROUP: builder.createGroup(chan); break; default: WebSocketClient.LOG.warn( "Received a Channel in the priv_channels array in READY of an unknown type! JSON: " + type); } } api.getClient().ready(); }