List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRealtime.java
@Override public void run() { try {//from w ww . ja v a 2s . c o m final String urlString = Trafikanten.getApiUrl() + "/reisrest/realtime/GetAllDepartures/" + stationId; Log.i(TAG, "Loading realtime data : " + urlString); final StreamWithTime streamWithTime = HelperFunctions.executeHttpRequest(context, new HttpGet(urlString), true); ThreadHandleTimeData(streamWithTime.timeDifference); /* * Parse json */ //long perfSTART = System.currentTimeMillis(); //Log.i(TAG,"PERF : Getting realtime data"); final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(streamWithTime.stream)); final int arraySize = jsonArray.length(); for (int i = 0; i < arraySize; i++) { final JSONObject json = jsonArray.getJSONObject(i); RealtimeData realtimeData = new RealtimeData(); try { realtimeData.expectedDeparture = HelperFunctions .jsonToDate(json.getString("ExpectedDepartureTime")); } catch (org.json.JSONException e) { realtimeData.expectedDeparture = HelperFunctions .jsonToDate(json.getString("ExpectedArrivalTime")); } try { realtimeData.lineId = json.getInt("LineRef"); } catch (org.json.JSONException e) { realtimeData.lineId = -1; } try { realtimeData.vehicleMode = json.getInt("VehicleMode"); } catch (org.json.JSONException e) { realtimeData.vehicleMode = 0; // default = bus } try { realtimeData.destination = json.getString("DestinationName"); } catch (org.json.JSONException e) { realtimeData.destination = "Ukjent"; } try { realtimeData.departurePlatform = json.getString("DeparturePlatformName"); if (realtimeData.departurePlatform.equals("null")) { realtimeData.departurePlatform = ""; } } catch (org.json.JSONException e) { realtimeData.departurePlatform = ""; } try { realtimeData.realtime = json.getBoolean("Monitored"); } catch (org.json.JSONException e) { realtimeData.realtime = false; } try { realtimeData.lineName = json.getString("PublishedLineName"); } catch (org.json.JSONException e) { realtimeData.lineName = ""; } try { if (json.has("InCongestion")) { realtimeData.inCongestion = json.getBoolean("InCongestion"); } } catch (org.json.JSONException e) { // can happen when incongestion is empty string. } try { if (json.has("VehicleFeatureRef")) { realtimeData.lowFloor = json.getString("VehicleFeatureRef").equals("lowFloor"); } } catch (org.json.JSONException e) { // lowfloor = false by default } try { if (json.has("TrainBlockPart") && !json.isNull("TrainBlockPart")) { JSONObject trainBlockPart = json.getJSONObject("TrainBlockPart"); if (trainBlockPart.has("NumberOfBlockParts")) { realtimeData.numberOfBlockParts = trainBlockPart.getInt("NumberOfBlockParts"); } } } catch (org.json.JSONException e) { // trainblockpart is initialized by default } ThreadHandlePostData(realtimeData); } //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms"); } catch (Exception e) { if (e.getClass() == InterruptedException.class) { ThreadHandlePostExecute(null); return; } ThreadHandlePostExecute(e); return; } ThreadHandlePostExecute(null); }
From source file:com.norman0406.slimgress.API.Interface.Interface.java
public void request(final Handshake handshake, final String requestString, final Location playerLocation, final JSONObject requestParams, final RequestResult result) throws InterruptedException { if (!handshake.isValid() || handshake.getXSRFToken().length() == 0) throw new RuntimeException("handshake is not valid"); new Thread(new Runnable() { public void run() { // create post String postString = mApiBaseURL + mApiRequest + requestString; HttpPost post = new HttpPost(postString); // set additional parameters JSONObject params = new JSONObject(); if (requestParams != null) { if (requestParams.has("params")) params = requestParams; else { try { params.put("params", requestParams); // add persistent request parameters if (playerLocation != null) { String loc = String.format("%08x,%08x", playerLocation.getLatitude(), playerLocation.getLongitude()); params.getJSONObject("params").put("playerLocation", loc); params.getJSONObject("params").put("location", loc); }//from w ww .j av a 2s.co m params.getJSONObject("params").put("knobSyncTimestamp", getCurrentTimestamp()); JSONArray collectedEnergy = new JSONArray(); // TODO: add collected energy guids params.getJSONObject("params").put("energyGlobGuids", collectedEnergy); } catch (JSONException e) { e.printStackTrace(); } } } else { try { params.put("params", null); } catch (JSONException e) { e.printStackTrace(); } } try { StringEntity entity = new StringEntity(params.toString(), "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // set header post.setHeader("Content-Type", "application/json;charset=UTF-8"); post.setHeader("Accept-Encoding", "gzip"); post.setHeader("User-Agent", "Nemesis (gzip)"); post.setHeader("X-XsrfToken", handshake.getXSRFToken()); post.setHeader("Host", mApiBase); post.setHeader("Connection", "Keep-Alive"); post.setHeader("Cookie", "SACSID=" + mCookie); // execute and get the response. try { HttpResponse response = null; String content = null; synchronized (Interface.this) { response = mClient.execute(post); assert (response != null); if (response.getStatusLine().getStatusCode() == 401) { // token expired or similar //isAuthenticated = false; response.getEntity().consumeContent(); } else { HttpEntity entity = response.getEntity(); // decompress gzip if necessary Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) content = decompressGZIP(entity); else content = EntityUtils.toString(entity); entity.consumeContent(); } } // handle request result if (content != null) { JSONObject json = new JSONObject(content); RequestResult.handleRequest(json, result); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }).start(); }
From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java
/** * MetaWeblog requests processing./* ww w .j ava 2s. co m*/ * * @param request the specified http servlet request * @param response the specified http servlet response * @param context the specified http request context */ @RequestProcessing(value = "/apis/metaweblog", method = HTTPRequestMethod.POST) public void metaWeblog(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) { final TextXMLRenderer renderer = new TextXMLRenderer(); context.setRenderer(renderer); String responseContent = null; try { final ServletInputStream inputStream = request.getInputStream(); final String xml = IOUtils.toString(inputStream, "UTF-8"); final JSONObject requestJSONObject = XML.toJSONObject(xml); final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL); final String methodName = methodCall.getString(METHOD_NAME); LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName); final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param"); if (METHOD_DELETE_POST.equals(methodName)) { params.remove(0); // Removes the first argument "appkey" } final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value") .getString("string"); final JSONObject user = userQueryService.getUserByEmail(userEmail); if (null == user) { throw new Exception("No user[email=" + userEmail + "]"); } final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").getString("string"); if (!user.getString(User.USER_PASSWORD).equals(userPwd)) { throw new Exception("Wrong password"); } if (METHOD_GET_USERS_BLOGS.equals(methodName)) { responseContent = getUsersBlogs(); } else if (METHOD_GET_CATEGORIES.equals(methodName)) { responseContent = getCategories(); } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) { final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value") .getInt("int"); responseContent = getRecentPosts(numOfPosts); } else if (METHOD_NEW_POST.equals(methodName)) { final JSONObject article = parsetPost(methodCall); article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail); addArticle(article); final StringBuilder stringBuilder = new StringBuilder( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>") .append(article.getString(Keys.OBJECT_ID)) .append("</string></value></param></params></methodResponse>"); responseContent = stringBuilder.toString(); } else if (METHOD_GET_POST.equals(methodName)) { final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value") .getString("string"); responseContent = getPost(postId); } else if (METHOD_EDIT_POST.equals(methodName)) { final JSONObject article = parsetPost(methodCall); final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value") .getString("string"); article.put(Keys.OBJECT_ID, postId); article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail); final JSONObject updateArticleRequest = new JSONObject(); updateArticleRequest.put(Article.ARTICLE, article); articleMgmtService.updateArticle(updateArticleRequest); final StringBuilder stringBuilder = new StringBuilder( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>") .append(postId).append("</string></value></param></params></methodResponse>"); responseContent = stringBuilder.toString(); } else if (METHOD_DELETE_POST.equals(methodName)) { final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value") .getString("string"); articleMgmtService.removeArticle(postId); final StringBuilder stringBuilder = new StringBuilder( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><boolean>") .append(true).append("</boolean></value></param></params></methodResponse>"); responseContent = stringBuilder.toString(); } else { throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]"); } } catch (final Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); responseContent = ""; final StringBuilder stringBuilder = new StringBuilder( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><fault><value><struct>") .append("<member><name>faultCode</name><value><int>500</int></value></member>") .append("<member><name>faultString</name><value><string>").append(e.getMessage()) .append("</string></value></member></struct></value></fault></methodResponse>"); responseContent = stringBuilder.toString(); } renderer.setContent(responseContent); }
From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java
/** * Parses the specified method call for an article. * // w w w . jav a 2 s.c o m * @param methodCall the specified method call * @return article * @throws Exception exception */ private JSONObject parsetPost(final JSONObject methodCall) throws Exception { final JSONObject ret = new JSONObject(); final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param"); final JSONObject post = params.getJSONObject(INDEX_POST).getJSONObject("value").getJSONObject("struct"); final JSONArray members = post.getJSONArray("member"); for (int i = 0; i < members.length(); i++) { final JSONObject member = members.getJSONObject(i); final String name = member.getString("name"); if ("dateCreated".equals(name)) { final JSONObject preference = preferenceQueryService.getPreference(); final String dateString = member.getJSONObject("value").getString("dateTime.iso8601"); Date date = null; try { date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject(dateString); } catch (final ParseException e) { LOGGER.log(Level.WARNING, "Parses article create date failed with ISO8601, retry to parse with pattern[yyyy-MM-dd'T'HH:mm:ss]"); final String timeZoneId = preference.getString(Preference.TIME_ZONE_ID); final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId); final DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss"); format.setTimeZone(timeZone); date = format.parse(dateString); } ret.put(Article.ARTICLE_CREATE_DATE, date); } else if ("title".equals(name)) { ret.put(Article.ARTICLE_TITLE, member.getJSONObject("value").getString("string")); } else if ("description".equals(name)) { final String content = member.getJSONObject("value").getString("string"); ret.put(Article.ARTICLE_CONTENT, content); final String plainTextContent = Jsoup.parse(content).text(); if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) { ret.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH)); } else { ret.put(Article.ARTICLE_ABSTRACT, plainTextContent); } } else if ("categories".equals(name)) { final StringBuilder tagBuilder = new StringBuilder(); final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data"); if (0 == data.length()) { throw new Exception("At least one Tag"); } final Object value = data.get("value"); if (value instanceof JSONArray) { final JSONArray tags = (JSONArray) value; for (int j = 0; j < tags.length(); j++) { final String tagTitle = tags.getJSONObject(j).getString("string"); tagBuilder.append(tagTitle); if (j < tags.length() - 1) { tagBuilder.append(","); } } } else { final JSONObject tag = (JSONObject) value; tagBuilder.append(tag.getString("string")); } ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString()); } } final boolean publish = 1 == params.getJSONObject(INDEX_PUBLISH).getJSONObject("value").getInt("boolean") ? true : false; ret.put(Article.ARTICLE_IS_PUBLISHED, publish); ret.put(Article.ARTICLE_COMMENTABLE, true); ret.put(Article.ARTICLE_VIEW_PWD, ""); return ret; }
From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java
/** * Builds a post (post struct) with the specified post id. * /*from ww w . j a v a 2s.com*/ * @param postId the specified post id * @return blog info XML * @throws Exception exception */ private String buildPost(final String postId) throws Exception { final StringBuilder stringBuilder = new StringBuilder(); final JSONObject result = articleQueryService.getArticle(postId); if (null == result) { throw new Exception("Not found article[id=" + postId + "]"); } final JSONObject article = result.getJSONObject(Article.ARTICLE); final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE); final String articleTitle = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE)); stringBuilder.append("<struct>"); stringBuilder.append("<member><name>dateCreated</name>").append("<value><dateTime.iso8601>") .append(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(createDate)) .append("</dateTime.iso8601></value></member>"); stringBuilder.append("<member><name>description</name>").append("<value>") .append(StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT))) .append("</value></member>"); stringBuilder.append("<member><name>title</name>").append("<value>").append(articleTitle) .append("</value></member>"); stringBuilder.append("<member><name>categories</name>").append("<value><array><data>"); final JSONArray tags = article.getJSONArray(Article.ARTICLE_TAGS_REF); for (int i = 0; i < tags.length(); i++) { final String tagTitle = tags.getJSONObject(i).getString(Tag.TAG_TITLE); stringBuilder.append("<value>").append(tagTitle).append("</value>"); } stringBuilder.append("</data></array></value></member></struct>"); return stringBuilder.toString(); }
From source file:org.aosutils.android.youtube.YtApiClientV3.java
private static SearchResultIds searchYtIds(String query, String type, int maxResults, String pageToken, String apiKey) throws IOException, JSONException { ArrayList<String> ids = new ArrayList<>(); Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com") .path("/youtube/v3/search").appendQueryParameter("key", apiKey).appendQueryParameter("part", "id") .appendQueryParameter("order", "relevance") .appendQueryParameter("maxResults", Integer.toString(maxResults)).appendQueryParameter("q", query); if (type != null) { uriBuilder.appendQueryParameter("type", type); }/*from w w w. ja va2s. com*/ if (pageToken != null) { uriBuilder.appendQueryParameter("pageToken", pageToken); } String uri = uriBuilder.build().toString(); String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT); JSONObject jsonObject = new JSONObject(output); String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null; JSONArray items = jsonObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); JSONObject id = item.getJSONObject("id"); ids.add(id.has("videoId") ? id.getString("videoId") : id.getString("playlistId")); } SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken); return searchResult; }
From source file:org.aosutils.android.youtube.YtApiClientV3.java
private static SearchResultIds playlistVideoIds(String playlistId, int maxResults, String pageToken, String apiKey) throws IOException, JSONException { ArrayList<String> ids = new ArrayList<>(); Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com") .path("/youtube/v3/playlistItems").appendQueryParameter("key", apiKey) .appendQueryParameter("part", "id,snippet") .appendQueryParameter("maxResults", Integer.toString(maxResults)) .appendQueryParameter("playlistId", playlistId); if (pageToken != null) { uriBuilder.appendQueryParameter("pageToken", pageToken); }// www .j a v a 2s . c om String uri = uriBuilder.build().toString(); String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT); JSONObject jsonObject = new JSONObject(output); String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null; JSONArray items = jsonObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); JSONObject snippet = item.getJSONObject("snippet"); JSONObject resourceId = snippet.getJSONObject("resourceId"); ids.add(resourceId.getString("videoId")); } SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken); return searchResult; }
From source file:org.aosutils.android.youtube.YtApiClientV3.java
public static ArrayList<YtPlaylist> getPlaylistInfo(Collection<String> playlistIds, String apiKey) throws IOException, JSONException { ArrayList<YtPlaylist> playlists = new ArrayList<>(); String uri = new Uri.Builder().scheme("https").authority("www.googleapis.com").path("/youtube/v3/playlists") .appendQueryParameter("key", apiKey).appendQueryParameter("part", "id,snippet") .appendQueryParameter("id", TextUtils.join(",", playlistIds)).build().toString(); String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT); JSONObject jsonObject = new JSONObject(output); JSONArray items = jsonObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); String playlistId = item.getString("id"); String title = item.getJSONObject("snippet").getString("title"); String description = item.getJSONObject("snippet").getString("description"); YtPlaylist playlist = new YtPlaylist(playlistId, title, description); playlists.add(playlist);// w w w.j a va 2 s . c om } return playlists; }
From source file:org.aosutils.android.youtube.YtApiClientV3.java
public static ArrayList<YtVideo> getVideoInfo(Collection<String> videoIds, String apiKey) throws IOException, JSONException { ArrayList<YtVideo> videos = new ArrayList<>(); String uri = new Uri.Builder().scheme("https").authority("www.googleapis.com").path("/youtube/v3/videos") .appendQueryParameter("key", apiKey).appendQueryParameter("part", "id,snippet,contentDetails") .appendQueryParameter("id", TextUtils.join(",", videoIds)).build().toString(); String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT); JSONObject jsonObject = new JSONObject(output); JSONArray items = jsonObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); String videoId = item.getString("id"); String title = item.getJSONObject("snippet").getString("title"); String description = item.getJSONObject("snippet").getString("description"); String durationStr = item.getJSONObject("contentDetails").getString("duration"); int hours = !durationStr.contains("H") ? 0 : Integer.parseInt( durationStr.substring(durationStr.indexOf("PT") + 2, durationStr.indexOf("H"))); int minutes = !durationStr.contains("M") ? 0 : hours > 0/*from w w w . ja va 2 s .c o m*/ ? Integer.parseInt( durationStr.substring(durationStr.indexOf("H") + 1, durationStr.indexOf("M"))) : Integer.parseInt( durationStr.substring(durationStr.indexOf("PT") + 2, durationStr.indexOf("M"))); int seconds = !durationStr.contains("S") ? 0 : minutes > 0 ? Integer.parseInt( durationStr.substring(durationStr.indexOf("M") + 1, durationStr.indexOf("S"))) : hours > 0 ? Integer.parseInt(durationStr.substring(durationStr.indexOf("H") + 1, durationStr.indexOf("S"))) : Integer.parseInt(durationStr.substring(durationStr.indexOf("PT") + 2, durationStr.indexOf("S"))); int duration = (hours * 60 * 60) + (minutes * 60) + seconds; boolean licensedContent = item.getJSONObject("contentDetails").getBoolean("licensedContent"); YtVideo video = new YtVideo(videoId, title, description, duration); video.setIsLicensedContent(licensedContent); videos.add(video); } return videos; }
From source file:com.kkurahar.locationmap.JsonParserTask.java
@Override protected String doInBackground(String... params) { String shortUrl = new String(); HttpConnection con = new HttpConnection(); // http?M?iGET?jJSON?iZ?kURL??j String jsonObj = con.doGet(createGetParam(params[0])); // GET?MJSONIuWFNg?uShortUrl?vl?o try {/* ww w.ja va2 s. c o m*/ // ?ubit.ly?vdl JSONObject jsonObject = new JSONObject(jsonObj); JSONObject resultsObject = jsonObject.getJSONObject("results"); JSONObject paramObject = resultsObject.getJSONObject(params[0]); shortUrl = paramObject.getString("shortUrl"); } catch (JSONException e) { e.printStackTrace(); } return shortUrl; }