List of usage examples for org.json JSONObject getLong
public long getLong(String key) throws JSONException
From source file:com.nextgis.firereporter.GetFiresService.java
protected void FillData(int nType, String sJSON) { GetDataStoped();//w w w .ja v a2 s . com try { JSONObject jsonMainObject = new JSONObject(sJSON); if (jsonMainObject.getBoolean("error")) { String sMsg = jsonMainObject.getString("msg"); SendError(sMsg); return; } if (jsonMainObject.has("rows") && !jsonMainObject.isNull("rows")) { JSONArray jsonArray = jsonMainObject.getJSONArray("rows"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); //Log.i(ParseJSON.class.getName(), jsonObject.getString("text")); long nId = jsonObject.getLong("fid"); long nKey = 10000000000L * nType + nId; //as we have values from separte tables we can get same key - to prevent this add big value multiplied on source type if (mmoFires.containsKey(nKey)) continue; int nIconId = 0; if (nType == 1) {//user nIconId = R.drawable.ic_eye; } else if (nType == 2) {//nasa nIconId = R.drawable.ic_nasa; } String sDate = jsonObject.getString("date"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date dtFire = dateFormat.parse(sDate); double dfLat = jsonObject.getDouble("lat"); double dfLon = jsonObject.getDouble("lon"); double dfDist = jsonObject.getDouble("dist"); FireItem item = new FireItem(this, nType, nId, dtFire, dfLon, dfLat, dfDist, nIconId); mmoFires.put(nKey, item); SendItem(item); String sMsg = String.format("%s/%.1f %s/%s", item.GetShortCoordinates(), dfDist / 1000, getString(R.string.km), item.GetDateAsString()); onNotify(nType, sMsg); } } } catch (Exception e) { SendError(e.getLocalizedMessage());// e.printStackTrace(); } }
From source file:com.github.e2point718.har2jmx.HAR.java
public static HAR build(String source) { HAR h = new HAR(); JSONObject har = new JSONObject(source); JSONObject log = har.getJSONObject("log"); JSONArray jPages = getOptionalArray(log, "pages"); Map<String, Page> pages = new HashMap<>(); if (jPages != null) { h.pages = new Page[jPages.length()]; for (int i = 0; i < jPages.length(); i++) { JSONObject jPage = jPages.getJSONObject(i); Page page = new Page(); h.pages[i] = page;/*w w w . ja va2s . c o m*/ page.id = jPage.getString("id"); page.title = jPage.getString("title"); pages.put(page.id, page); } } JSONArray jEntries = getOptionalArray(log, "entries"); if (jEntries != null) { h.entries = new Entry[jEntries.length()]; for (int i = 0; i < jEntries.length(); i++) { JSONObject jEntry = jEntries.getJSONObject(i); Entry entry = new Entry(); h.entries[i] = entry; entry.pageref = pages.get(getOptionalProperty(jEntry, "pageref")); JSONObject jRequest = jEntry.getJSONObject("request"); Request request = new Request(); entry.request = request; request.httpVersion = jRequest.getString("httpVersion"); request.method = Method.valueOf(jRequest.getString("method")); try { request.url = new URL(jRequest.getString("url")); } catch (MalformedURLException e) { throw new JSONException(e.getMessage()); } JSONArray jHeaders = getOptionalArray(jRequest, "headers"); if (jHeaders != null) { request.headers = new HashMap<>(); for (int j = 0; j < jHeaders.length(); j++) { JSONObject jHeader = jHeaders.getJSONObject(j); request.headers.put(jHeader.getString("name"), jHeader.getString("value")); } } JSONArray jQueryString = getOptionalArray(jRequest, "queryString"); if (jQueryString != null) { request.queryString = new HashMap<>(); for (int j = 0; j < jQueryString.length(); j++) { JSONObject jQueryStringO = jQueryString.getJSONObject(j); request.queryString.put(jQueryStringO.getString("name"), jQueryStringO.getString("value")); } } JSONArray jCookies = getOptionalArray(jRequest, "cookies"); if (jCookies != null) { request.cookies = new Cookie[jCookies.length()]; for (int j = 0; j < jCookies.length(); j++) { JSONObject jCookie = jCookies.getJSONObject(j); Cookie cookie = new Cookie(); request.cookies[j] = cookie; cookie.name = jCookie.getString("name"); cookie.value = jCookie.getString("value"); } } JSONObject jPostData = getOptionalObject(jRequest, ("postData")); if (jPostData != null) { PostData pd = new PostData(); request.postData = pd; pd.mimeType = jPostData.getString("mimeType"); pd.text = getOptionalProperty(jPostData, "text"); JSONArray jPostParams = getOptionalArray(jPostData, "params"); if (jPostParams != null) { pd.params = new PostDataParam[jPostParams.length()]; for (int j = 0; j < jPostParams.length(); j++) { PostDataParam pdp = new PostDataParam(); JSONObject jPostDataParam = jPostParams.getJSONObject(j); pd.params[j] = pdp; pdp.name = getOptionalProperty(jPostDataParam, "name"); pdp.value = getOptionalProperty(jPostDataParam, "value"); pdp.contentType = getOptionalProperty(jPostDataParam, "contentType"); pdp.fileName = getOptionalProperty(jPostDataParam, "fileName"); } } } JSONObject jResponse = jEntry.getJSONObject("response"); Response response = new Response(); entry.response = response; response.httpVersion = jResponse.getString("httpVersion"); response.status = jResponse.getInt("status"); response.statusText = jResponse.getString("statusText"); jHeaders = getOptionalArray(jResponse, "headers"); if (jHeaders != null) { response.headers = new HashMap<>(); for (int j = 0; j < jHeaders.length(); j++) { JSONObject jHeader = jHeaders.getJSONObject(j); response.headers.put(jHeader.getString("name"), jHeader.getString("value")); } } jCookies = getOptionalArray(jResponse, "cookies"); if (jCookies != null) { response.cookies = new Cookie[jCookies.length()]; for (int j = 0; j < jCookies.length(); j++) { JSONObject jCookie = jCookies.getJSONObject(j); Cookie cookie = new Cookie(); response.cookies[j] = cookie; cookie.name = jCookie.getString("name"); cookie.value = jCookie.getString("value"); } } JSONObject jContent = getOptionalObject(jResponse, ("content")); if (jContent != null) { ResponseContent content = new ResponseContent(); response.content = content; content.size = jContent.getLong("size"); content.mimeType = jContent.getString("mimeType"); content.text = getOptionalProperty(jContent, ("text")); } } } return h; }
From source file:net.dv8tion.jda.core.handle.ChannelDeleteHandler.java
@Override protected Long handleInternally(JSONObject content) { ChannelType type = ChannelType.fromId(content.getInt("type")); long guildId = 0; if (type.isGuild()) { guildId = content.getLong("guild_id"); if (api.getGuildLock().isLocked(guildId)) return guildId; }/*from w w w .jav a 2 s .c om*/ final long channelId = content.getLong("id"); switch (type) { case TEXT: { GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId); TextChannel channel = api.getTextChannelMap().remove(channelId); if (channel == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent)); EventCache.LOG .debug("CHANNEL_DELETE attempted to delete a text channel that is not yet cached. JSON: " + content); return null; } guild.getTextChannelsMap().remove(channel.getIdLong()); api.getEventManager().handle(new TextChannelDeleteEvent(api, responseNumber, channel)); break; } case VOICE: { GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId); VoiceChannel channel = guild.getVoiceChannelMap().remove(channelId); if (channel == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent)); EventCache.LOG .debug("CHANNEL_DELETE attempted to delete a voice channel that is not yet cached. JSON: " + content); return null; } //We use this instead of getAudioManager(Guild) so we don't create a new instance. Efficiency! AudioManagerImpl manager = api.getAudioManagerMap().get(guild.getIdLong()); if (manager != null && manager.isConnected() && manager.getConnectedChannel().getIdLong() == channel.getIdLong()) { manager.closeAudioConnection(ConnectionStatus.DISCONNECTED_CHANNEL_DELETED); } guild.getVoiceChannelMap().remove(channel.getIdLong()); api.getEventManager().handle(new VoiceChannelDeleteEvent(api, responseNumber, channel)); break; } case PRIVATE: { PrivateChannel channel = api.getPrivateChannelMap().remove(channelId); if (channel == null) channel = api.getFakePrivateChannelMap().remove(channelId); if (channel == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent)); EventCache.LOG .debug("CHANNEL_DELETE attempted to delete a private channel that is not yet cached. JSON: " + content); return null; } if (channel.getUser().isFake()) api.getFakeUserMap().remove(channel.getUser().getIdLong()); ((UserImpl) channel.getUser()).setPrivateChannel(null); api.getEventManager().handle(new PrivateChannelDeleteEvent(api, responseNumber, channel)); break; } case GROUP: { //TODO: close call on group leave (kill audio manager) final long groupId = content.getLong("id"); GroupImpl group = (GroupImpl) ((JDAClientImpl) api.asClient()).getGroupMap().remove(groupId); if (group == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug( "CHANNEL_DELETE attempted to delete a group that is not yet cached. JSON: " + content); return null; } group.getUserMap().forEachEntry((userId, user) -> { //User is fake, has no privateChannel, is not in a relationship, and is not in any other groups // then we remove the fake user from the fake cache as it was only in this group //Note: we getGroups() which gets all groups, however we already removed the current group above. if (user.isFake() && !user.hasPrivateChannel() && ((JDAClientImpl) api.asClient()).getRelationshipMap().get(userId) == null && api.asClient().getGroups().stream().noneMatch(g -> g.getUsers().contains(user))) { api.getFakeUserMap().remove(userId); } return true; }); api.getEventManager().handle(new GroupLeaveEvent(api, responseNumber, group)); break; } default: throw new IllegalArgumentException("CHANNEL_DELETE provided an unknown channel type. JSON: " + content); } return null; }
From source file:au.id.tmm.anewreader.model.Model.java
/** * Retrieves the item ids for the given parameters. These ids can then be used to construct * corresponding Item objects./* w w w . j a v a 2s. c o m*/ */ private ListWithContinuation<String> getItemIdsFromApi(Feed feed, boolean onlyUnread, int numItemsLimit, Date olderThan, Continuation continuation) throws IOException, JSONException { final String BASE_ITEMS_URL = this.parentAccount.getReaderService().getBaseUrl() + "/reader/api/0/stream/items/ids?output=json"; final String READ_ITEMS_STREAM = "user/-/state/com.google/read"; String itemListUrl = BASE_ITEMS_URL + "&s=" + feed.getEncodedFeedAddress() + (onlyUnread ? "&xt=" + READ_ITEMS_STREAM : "") + "&n=" + String.valueOf(numItemsLimit) + "&r=d" + (olderThan != null ? "&ot=" + Long.toString(olderThan.getTime()) : "") + (continuation != null ? "&c=" + Long.toString(continuation.getCode()) : ""); ReaderServiceRequestHelper requestHelper = new ReaderServiceRequestHelper( this.parentAccount.getAuthHelper()); JSONObject itemsResponse; itemsResponse = new JSONObject(requestHelper.performGetRequest(itemListUrl)); JSONArray itemsResponseArray = itemsResponse.getJSONArray("itemRefs"); List<String> returnedIds = new ArrayList<String>(itemsResponseArray.length()); for (int i = 0; i < itemsResponseArray.length(); i++) { returnedIds.add(itemsResponseArray.getJSONObject(i).getString("id")); } Continuation returnedContinuation = null; if (itemsResponse.has("continuation")) { returnedContinuation = new Continuation(itemsResponse.getLong("continuation"), feed); } return new ListWithContinuation<String>(returnedIds, returnedContinuation); }
From source file:org.nuxeo.android.simpleclient.listing.ui.TaskItemAttributeUpdater.java
protected Date readDate(JSONObject dateObject) throws JSONException { return new Date(dateObject.getLong("time")); }
From source file:com.miz.apis.trakt.Movie.java
public Movie(JSONObject summaryJson) { try {/*from w ww . j a v a2 s. com*/ mTitle = summaryJson.getString("title"); mYear = summaryJson.getInt("year"); mReleased = summaryJson.getLong("released"); mUrl = summaryJson.getString("url"); mOverview = summaryJson.getString("overview"); mTagline = summaryJson.getString("tagline"); mRuntime = summaryJson.getInt("runtime"); mCertification = summaryJson.getString("certification"); mTmdbId = summaryJson.getInt("tmdb_id"); mImdbId = summaryJson.getString("imdb_id"); mPoster = summaryJson.getString("poster"); mFanart = summaryJson.getJSONObject("images").getString("fanart"); mRating = summaryJson.getJSONObject("ratings").getInt("percentage"); JSONArray genres = summaryJson.getJSONArray("genres"); for (int i = 0; i < genres.length(); i++) mGenres.add(genres.getString(i)); } catch (JSONException e) { } }
From source file:net.dv8tion.jda.core.handle.ChannelCreateHandler.java
@Override protected Long handleInternally(JSONObject content) { ChannelType type = ChannelType.fromId(content.getInt("type")); long guildId = 0; if (type.isGuild()) { guildId = content.getLong("guild_id"); if (api.getGuildLock().isLocked(guildId)) return guildId; }//from www.ja va 2 s . c om switch (type) { case TEXT: { api.getEventManager().handle(new TextChannelCreateEvent(api, responseNumber, api.getEntityBuilder().createTextChannel(content, guildId))); break; } case VOICE: { api.getEventManager().handle(new VoiceChannelCreateEvent(api, responseNumber, api.getEntityBuilder().createVoiceChannel(content, guildId))); break; } case PRIVATE: { api.getEventManager().handle(new PrivateChannelCreateEvent(api, responseNumber, api.getEntityBuilder().createPrivateChannel(content))); break; } case GROUP: { api.getEventManager() .handle(new GroupJoinEvent(api, responseNumber, api.getEntityBuilder().createGroup(content))); break; } default: throw new IllegalArgumentException( "Discord provided an CREATE_CHANNEL event with an unknown channel type! JSON: " + content); } api.getEventCache().playbackCache(EventCache.Type.CHANNEL, content.getLong("id")); return null; }
From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java
private void queryPageInfo(String lang, String pageId, PageInfo page) { Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("pageids", pageId); params.put("prop", "info"); try {//from w w w.j ava 2 s . c o m String urlString = StringUtils.replace(Configure.METADATA.API_ENDPOINT, lang) + "?" + StringUtils.mapToURLParameters(params); URL url = new URL(urlString); JSONObject response = queryForJSONResponse(url); try { JSONObject pageInfo = response.getJSONObject("query").getJSONObject("pages").getJSONObject(pageId); page.setTitle(pageInfo.getString("title")); page.setSize(pageInfo.getLong("length")); page.setLastRevisionId(Long.toString(pageInfo.getLong("lastrevid"))); } catch (JSONException ex) { LogHandler.log(this, LogLevel.WARN, "Error in response: " + urlString + ", " + response.toString() + ", " + ex.getMessage()); } } catch (UnsupportedEncodingException ex) { LogHandler.log(this, LogLevel.WARN, "Error in encoding: " + params.toString() + ", " + ex.getMessage()); } catch (MalformedURLException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } catch (IOException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } }
From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java
private List<Map<String, Object>> queryRevisionListWorker(String lang, String pageId, String cont, String start, String end) {/*from ww w . j av a 2 s . c om*/ Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("pageids", pageId); params.put("prop", "revisions"); params.put("rvprop", "ids|timestamp"); params.put("rvstart", start); params.put("rvend", end); params.put("rvdir", "newer"); if (cont != null) { params.put("rvcontinue", cont); } List<Map<String, Object>> result = new LinkedList<>(); try { String urlString = StringUtils.replace(Configure.METADATA.API_ENDPOINT, lang) + "?" + StringUtils.mapToURLParameters(params); URL url = new URL(urlString); JSONObject response = queryForJSONResponse(url); try { JSONObject pageRecord = response.getJSONObject("query").getJSONObject("pages") .getJSONObject(pageId); if (pageRecord.has("revisions")) { JSONArray revisions = pageRecord.getJSONArray("revisions"); for (int i = 0; i < revisions.length(); i++) { JSONObject revision = revisions.getJSONObject(i); Map<String, Object> record = new HashMap<>(); record.put("revid", Long.toString(revision.getLong("revid"))); record.put("timestamp", StringUtils.parseTimestamp(revision.getString("timestamp"), Configure.METADATA.TIMESTAMP_FORMAT)); result.add(record); } } String queryContinue = null; if (response.has("query-continue")) { queryContinue = response.getJSONObject("query-continue").getJSONObject("revisions") .get("rvcontinue").toString(); } if (queryContinue != null) { List<Map<String, Object>> moreResult = queryRevisionListWorker(lang, pageId, queryContinue, start, end); result.addAll(moreResult); } } catch (Exception ex) { LogHandler.log(this, LogLevel.WARN, "Error in response: " + urlString + ", " + response.toString() + ", " + ex.getMessage()); } } catch (UnsupportedEncodingException ex) { LogHandler.log(this, LogLevel.WARN, "Error in encoding: " + params.toString() + ", " + ex.getMessage()); } catch (MalformedURLException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } catch (IOException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } return result; }
From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java
private Map<String, String>[] queryPageIdsBatchWorker(String lang, String titles, String cont) { Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("titles", titles); params.put("prop", "info"); if (cont != null) { params.put("incontinue", cont); }/*w w w .ja va2 s . c om*/ Map<String, String> norm = new HashMap<>(); Map<String, String> result = new HashMap<>(); try { String urlString = StringUtils.replace(Configure.METADATA.API_ENDPOINT, lang) + "?" + StringUtils.mapToURLParameters(params); URL url = new URL(urlString); JSONObject response = queryForJSONResponse(url); if (response != null && response.has("query")) { JSONObject responseQuery = response.getJSONObject("query"); if (responseQuery.has("normalized")) { JSONArray normalizations = responseQuery.getJSONArray("normalized"); for (int i = 0; i < normalizations.length(); i++) { JSONObject normalization = normalizations.getJSONObject(i); norm.put(normalization.getString("from"), normalization.getString("to")); } } if (responseQuery.has("pages")) { JSONObject pages = responseQuery.getJSONObject("pages"); for (String pageKey : (Set<String>) pages.keySet()) { if (Long.parseLong(pageKey) > 0) { JSONObject page = pages.getJSONObject(pageKey); if (page.has("ns") && page.getLong("ns") == 0L) { result.put(page.getString("title"), Long.toString(page.getLong("pageid"))); } } } } String queryContinue = null; if (response.has("query-continue")) { queryContinue = response.getJSONObject("query-continue").getJSONObject("info") .getString("incontinue"); } if (queryContinue != null) { Map<String, String>[] moreResult = queryPageIdsBatchWorker(lang, titles, queryContinue); norm.putAll(moreResult[0]); result.putAll(moreResult[1]); } } } catch (UnsupportedEncodingException ex) { LogHandler.log(this, LogLevel.WARN, "Error in encoding: " + params.toString() + ", " + ex.getMessage()); } catch (MalformedURLException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } catch (IOException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } return new Map[] { norm, result }; }