List of usage examples for org.json JSONObject getLong
public long getLong(String key) throws JSONException
From source file:fr.openbike.android.io.RemoteStationsUpdateHandler.java
/** {@inheritDoc} */ @Override// w w w .j a v a 2s . c o m public Object parse(JSONObject jsonBikes, OpenBikeDBAdapter dbAdapter) throws JSONException, IOException { long version = jsonBikes.getLong(VERSION); String message = jsonBikes.optString(MESSAGE); JSONArray stations = jsonBikes.optJSONArray(STATIONS); if (stations != null) { dbAdapter.cleanAndInsertStations(version, stations); } return "".equals(message) ? null : message; }
From source file:com.asd.littleprincesbeauty.data.Task.java
@Override public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try {/* www .ja v a2 s. c o m*/ // id if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); } // last_modified if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); } // name if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); } // notes if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); } // deleted if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); } // completed if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("fail to get task content from jsonobject"); } } }
From source file:com.asd.littleprincesbeauty.data.Task.java
@Override public int getSyncAction(Cursor c) { try {// w w w . j ava 2 s . c o m JSONObject noteInfo = null; if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); } if (noteInfo == null) { Log.w(TAG, "it seems that note meta has been deleted"); return SYNC_ACTION_UPDATE_REMOTE; } if (!noteInfo.has(NoteColumns.ID)) { Log.w(TAG, "remote note id seems to be deleted"); return SYNC_ACTION_UPDATE_LOCAL; } // validate the note id now if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { Log.w(TAG, "note id doesn't match"); return SYNC_ACTION_UPDATE_LOCAL; } if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { // there is no local update if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // no update both side return SYNC_ACTION_NONE; } else { // apply remote to local return SYNC_ACTION_UPDATE_LOCAL; } } else { // validate gtask id if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { Log.e(TAG, "gtask id doesn't match"); return SYNC_ACTION_ERROR; } if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { // local modification only return SYNC_ACTION_UPDATE_REMOTE; } else { return SYNC_ACTION_UPDATE_CONFLICT; } } } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); } return SYNC_ACTION_ERROR; }
From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java
PointOfInterest fromFeature(JSONObject feature) throws JSONException { String type = feature.getString("type").toString(); PointOfInterest point;//from w ww. j a v a 2s .c o m String name = null; String url = null; Long id = null; if (type.equals("Feature")) { point = fromPoint(feature.getJSONObject("geometry")); if (feature.has("properties")) { JSONObject properties = feature.getJSONObject("properties"); if (properties.has("name")) { name = properties.getString("name"); } if (properties.has("url")) { url = properties.getString("url"); } if (properties.has("id")) { id = properties.getLong("id"); } } } else { throw new IllegalArgumentException(); } return new PoiBuilder(id, point.getLatitude(), point.getLongitude(), this.category).setName(name) .setUrl(url).build(); }
From source file:net.dv8tion.jda.core.handle.GuildBanHandler.java
@Override protected Long handleInternally(JSONObject content) { final long id = content.getLong("guild_id"); if (api.getGuildLock().isLocked(id)) return id; JSONObject userJson = content.getJSONObject("user"); GuildImpl guild = (GuildImpl) api.getGuildMap().get(id); if (guild == null) { api.getEventCache().cache(EventCache.Type.GUILD, id, () -> { handle(responseNumber, allContent); });//from ww w . j av a 2s . c om EventCache.LOG.debug( "Received Guild Member " + (banned ? "Ban" : "Unban") + " event for a Guild not yet cached."); return null; } User user = api.getEntityBuilder().createFakeUser(userJson, false); if (banned) { api.getEventManager().handle(new GuildBanEvent(api, responseNumber, guild, user)); } else { api.getEventManager().handle(new GuildUnbanEvent(api, responseNumber, guild, user)); } return null; }
From source file:com.sonoport.freesound.response.mapping.Mapper.java
/** * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an * instance of <code>JSONObject.NULL</code>. * * @param jsonObject The {@link JSONObject} being processed * @param field The field to retrieve/* ww w. j av a 2 s .c o m*/ * @param fieldType The data type of the field * @return The field value (or null if not found) * * @param <T> The data type to return */ @SuppressWarnings("unchecked") protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field, final Class<T> fieldType) { T fieldValue = null; if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) { try { if (fieldType == String.class) { fieldValue = (T) jsonObject.getString(field); } else if (fieldType == Integer.class) { fieldValue = (T) Integer.valueOf(jsonObject.getInt(field)); } else if (fieldType == Long.class) { fieldValue = (T) Long.valueOf(jsonObject.getLong(field)); } else if (fieldType == Float.class) { fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field))); } else if (fieldType == JSONArray.class) { fieldValue = (T) jsonObject.getJSONArray(field); } else if (fieldType == JSONObject.class) { fieldValue = (T) jsonObject.getJSONObject(field); } else { fieldValue = (T) jsonObject.get(field); } } catch (final JSONException | ClassCastException e) { // TODO Log a warning } } return fieldValue; }
From source file:com.gvccracing.android.tttimer.Tabs.RaceInfoTab.java
public void postData() { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://www.gvccracing.com/?page_id=2525&pass=com.gvccracing.android.tttimer"); try {/*from w ww.j a v a 2 s . c o m*/ // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert the Bytes read to a String. */ String text = new String(baf.toByteArray()); JSONObject mainJson = new JSONObject(text); JSONArray jsonArray = mainJson.getJSONArray("members"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); String firstName = json.getString("fname"); String lastName = json.getString("lname"); String licenseStr = json.getString("license"); Integer license = 0; try { license = Integer.parseInt(licenseStr); } catch (Exception ex) { Log.e(LOG_TAG(), "Unable to parse license string"); } long age = json.getLong("age"); String categoryStr = json.getString("category"); Integer category = 5; try { category = Integer.parseInt(categoryStr); } catch (Exception ex) { Log.e(LOG_TAG(), "Unable to parse category string"); } String phone = json.getString("phone"); long phoneNumber = 0; try { phoneNumber = Long.parseLong(phone.replace("-", "").replace("(", "").replace(")", "") .replace(" ", "").replace(".", "").replace("*", "")); } catch (Exception e) { Log.e(LOG_TAG(), "Unable to parse phone number"); } String gender = json.getString("gender"); String econtact = json.getString("econtact"); String econtactPhone = json.getString("econtact_phone"); long eContactPhoneNumber = 0; try { eContactPhoneNumber = Long.parseLong(econtactPhone.replace("-", "").replace("(", "") .replace(")", "").replace(" ", "").replace(".", "").replace("*", "")); } catch (Exception e) { Log.e(LOG_TAG(), "Unable to parse econtact phone number"); } Long member_id = json.getLong("member_id"); String gvccCategory; switch (category) { case 1: case 2: case 3: gvccCategory = "A"; break; case 4: gvccCategory = "B4"; break; case 5: gvccCategory = "B5"; break; default: gvccCategory = "B5"; break; } Log.w(LOG_TAG(), lastName); Cursor racerInfo = Racer.Instance().Read(getActivity(), new String[] { Racer._ID, Racer.FirstName, Racer.LastName, Racer.USACNumber, Racer.PhoneNumber, Racer.EmergencyContactName, Racer.EmergencyContactPhoneNumber }, Racer.USACNumber + "=?", new String[] { license.toString() }, null); if (racerInfo.getCount() > 0) { racerInfo.moveToFirst(); Long racerID = racerInfo.getLong(racerInfo.getColumnIndex(Racer._ID)); Racer.Instance().Update(getActivity(), racerID, firstName, lastName, license, 0l, phoneNumber, econtact, eContactPhoneNumber, gender); Cursor racerClubInfo = RacerClubInfo.Instance().Read(getActivity(), new String[] { RacerClubInfo._ID, RacerClubInfo.GVCCID, RacerClubInfo.RacerAge, RacerClubInfo.Category }, RacerClubInfo.Racer_ID + "=? AND " + RacerClubInfo.Year + "=? AND " + RacerClubInfo.Upgraded + "=?", new String[] { racerID.toString(), "2013", "0" }, null); if (racerClubInfo.getCount() > 0) { racerClubInfo.moveToFirst(); long racerClubInfoID = racerClubInfo .getLong(racerClubInfo.getColumnIndex(RacerClubInfo._ID)); String rciCategory = racerClubInfo .getString(racerClubInfo.getColumnIndex(RacerClubInfo.Category)); boolean upgraded = gvccCategory != rciCategory; if (upgraded) { RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null, null, null, null, null, null, upgraded); RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } else { RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null, null, null, null, age, member_id, upgraded); } } else { RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } if (racerClubInfo != null) { racerClubInfo.close(); } } else { // TODO: Better birth date Uri resultUri = Racer.Instance().Create(getActivity(), firstName, lastName, license, 0l, phoneNumber, econtact, eContactPhoneNumber, gender); long racerID = Long.parseLong(resultUri.getLastPathSegment()); RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } if (racerInfo != null) { racerInfo.close(); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { Log.e(LOG_TAG(), e.getMessage()); } }
From source file:com.google.testing.testify.risk.frontend.server.task.UploadDataTask.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) { String user = req.getParameter("user"); String jsonString = req.getParameter("json"); try {// w w w .j a v a2s . c o m // TODO(jimr): add impersonation of user in string user. JSONObject json = new JSONObject(jsonString); JSONObject item; if (json.has("bug")) { item = json.getJSONObject("bug"); Bug bug = new Bug(); bug.setParentProjectId(item.getLong("projectId")); bug.setExternalId(item.getLong("bugId")); bug.setTitle(item.getString("title")); bug.setPath(item.getString("path")); bug.setSeverity(item.getLong("severity")); bug.setPriority(item.getLong("priority")); bug.setBugGroups(Sets.newHashSet(StringUtil.csvToList(item.getString("groups")))); bug.setBugUrl(item.getString("url")); bug.setState(item.getString("status")); bug.setStateDate(item.getLong("statusDate")); dataService.addBug(bug); } else if (json.has("test")) { item = json.getJSONObject("test"); TestCase test = new TestCase(); test.setParentProjectId(item.getLong("projectId")); test.setExternalId(item.getLong("testId")); test.setTitle(item.getString("title")); test.setTags(Sets.newHashSet(StringUtil.csvToList(item.getString("tags")))); test.setTestCaseUrl(item.getString("url")); test.setState(item.getString("result")); test.setStateDate(item.getLong("resultDate")); dataService.addTestCase(test); } else if (json.has("checkin")) { item = json.getJSONObject("checkin"); Checkin checkin = new Checkin(); checkin.setParentProjectId(item.getLong("projectId")); checkin.setExternalId(item.getLong("checkinId")); checkin.setSummary(item.getString("summary")); checkin.setDirectoriesTouched(Sets.newHashSet(StringUtil.csvToList(item.getString("directories")))); checkin.setChangeUrl(item.getString("url")); checkin.setState(item.getString("state")); checkin.setStateDate(item.getLong("stateDate")); dataService.addCheckin(checkin); } else { LOG.severe("No applicable data found for json: " + json.toString()); } } catch (JSONException e) { // We don't issue a 500 or similar response code here to prevent retries, which would have // no different a result. LOG.severe("Couldn't parse input JSON: " + jsonString); return; } }
From source file:net.dv8tion.jda.core.handle.GuildEmojisUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("guild_id"); if (api.getGuildLock().isLocked(guildId)) return guildId; GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId); if (guild == null) { api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent)); return null; }/*from w w w. j a v a2 s. c om*/ JSONArray array = content.getJSONArray("emojis"); TLongObjectMap<Emote> emoteMap = guild.getEmoteMap(); List<Emote> oldEmotes = new ArrayList<>(emoteMap.valueCollection()); //snapshot of emote cache List<Emote> newEmotes = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { JSONObject current = array.getJSONObject(i); final long emoteId = current.getLong("id"); EmoteImpl emote = (EmoteImpl) emoteMap.get(emoteId); EmoteImpl oldEmote = null; if (emote == null) { emote = new EmoteImpl(emoteId, guild); newEmotes.add(emote); } else { // emote is in our cache which is why we don't want to remove it in cleanup later oldEmotes.remove(emote); oldEmote = emote.clone(); } emote.setName(current.getString("name")).setManaged(current.getBoolean("managed")); //update roles JSONArray roles = current.getJSONArray("roles"); Set<Role> newRoles = emote.getRoleSet(); Set<Role> oldRoles = new HashSet<>(newRoles); //snapshot of cached roles for (int j = 0; j < roles.length(); j++) { Role role = guild.getRoleById(roles.getString(j)); newRoles.add(role); oldRoles.remove(role); } //cleanup old cached roles that were not found in the JSONArray for (Role r : oldRoles) { // newRoles directly writes to the set contained in the emote newRoles.remove(r); } // finally, update the emote emoteMap.put(emote.getIdLong(), emote); // check for updated fields and fire events handleReplace(oldEmote, emote); } //cleanup old emotes that don't exist anymore for (Emote e : oldEmotes) { emoteMap.remove(e.getIdLong()); api.getEventManager().handle(new EmoteRemovedEvent(api, responseNumber, e)); } for (Emote e : newEmotes) { api.getEventManager().handle(new EmoteAddedEvent(api, responseNumber, e)); } return null; }
From source file:com.nginious.http.application.Http11SerializerTestCase.java
private void testResponse(String body) throws Exception { JSONObject bean = new JSONObject(body); assertTrue(bean.has("testBean1")); bean = bean.getJSONObject("testBean1"); assertEquals(true, bean.getBoolean("first")); assertEquals(1.1d, bean.getDouble("second")); assertEquals(1.2f, (float) bean.getDouble("third")); assertEquals(2, bean.getInt("fourth")); assertEquals(5L, bean.getLong("fifth")); assertEquals((short) 3, (short) bean.getInt("sixth")); assertEquals("Seven", bean.getString("seventh")); assertTrue(bean.has("eight")); assertTrue(bean.has("ninth")); }