List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static RadioSong GetSongVoteScore(Context context, RadioRedditApplication application, RadioSong radiosong) {/*from w ww .j av a 2 s .com*/ try { // get vote score String reddit_info_url = context.getString(R.string.reddit_link_by) + URLEncoder.encode(radiosong.Reddit_url); String outputRedditInfo = ""; boolean errorGettingRedditInfo = false; try { outputRedditInfo = HTTPUtil.get(context, reddit_info_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingRedditInfo = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) { // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length()); // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that. (We can probably safely ignore this for now) JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo); JSONObject reddit_info_json = new JSONObject(reddit_info_tokener); JSONObject data = reddit_info_json.getJSONObject("data"); // default value of score String score = context.getString(R.string.vote_to_submit_song); String likes = "null"; String name = ""; JSONArray children_array = data.getJSONArray("children"); // Song hasn't been submitted yet if (children_array.length() > 0) { JSONObject children = children_array.getJSONObject(0); JSONObject children_data = children.getJSONObject("data"); score = children_data.getString("score"); likes = children_data.getString("likes"); name = children_data.getString("name"); } radiosong.Score = score; radiosong.Likes = likes; radiosong.Name = name; } else { radiosong.Score = "?"; radiosong.Likes = "null"; radiosong.Name = ""; } } catch (Exception ex) { // We fail to get the vote information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); // return error message?? radiosong.ErrorMessage = context.getString(R.string.error_GettingVoteInformation); //return radiosong; } return radiosong; }
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static RadioEpisode GetEpisodeVoteScore(Context context, RadioRedditApplication application, RadioEpisode radioepisode) {/*from w ww . j a va 2 s . c o m*/ try { // get vote score String reddit_info_url = context.getString(R.string.reddit_link_by) + URLEncoder.encode(radioepisode.Reddit_url); String outputRedditInfo = ""; boolean errorGettingRedditInfo = false; try { outputRedditInfo = HTTPUtil.get(context, reddit_info_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingRedditInfo = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) { // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length()); // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that. (We can probably safely ignore this for now) JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo); JSONObject reddit_info_json = new JSONObject(reddit_info_tokener); JSONObject data = reddit_info_json.getJSONObject("data"); // default value of score String score = context.getString(R.string.vote_to_submit_song); String likes = "null"; String name = ""; JSONArray children_array = data.getJSONArray("children"); // Song hasn't been submitted yet if (children_array.length() > 0) { JSONObject children = children_array.getJSONObject(0); JSONObject children_data = children.getJSONObject("data"); score = children_data.getString("score"); likes = children_data.getString("likes"); name = children_data.getString("name"); } radioepisode.Score = score; radioepisode.Likes = likes; radioepisode.Name = name; } else { radioepisode.Score = "?"; radioepisode.Likes = "null"; radioepisode.Name = ""; } } catch (Exception ex) { // We fail to get the vote information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); // return error message?? radioepisode.ErrorMessage = context.getString(R.string.error_GettingVoteInformation); //return radiosong; } return radioepisode; }
From source file:to.networld.fbtosemweb.FacebookToSIOC.java
/** * TODO: If a link was posted, add also the link to the SIOC block. * @throws IOException//from w ww . j a v a 2 s . c o m * @throws JSONException */ public void createSIOC() throws IOException, JSONException { Element rootNode = this.rdfDocument.addElement(new QName("RDF", RDF_NS)); rootNode.add(SIOC_NS); rootNode.add(DCT_NS); JSONArray wallEntries = this.object.getJSONArray("data"); for (int count = 0; count < wallEntries.length(); count++) { JSONObject wallEntry = (JSONObject) wallEntries.get(count); Element siocPost = rootNode.addElement(new QName("Post", SIOC_NS)).addAttribute( new QName("about", RDF_NS), "http://graph.facebook.com/" + wallEntry.getString("id")); siocPost.addElement(new QName("content", SIOC_NS)).setText(wallEntry.getString("message")); String creatorID = wallEntry.getJSONObject("from").getString("id"); siocPost.addElement(new QName("hasCreator", SIOC_NS)).addAttribute(new QName("resource", RDF_NS), "http://graph.facebook.com/" + creatorID); try { siocPost.addElement(new QName("created", SIOC_NS)).setText(wallEntry.getString("created_time")); } catch (JSONException e) { } try { siocPost.addElement(new QName("modified", SIOC_NS)).setText(wallEntry.getString("updated_time")); } catch (JSONException e) { } try { JSONArray comments = wallEntry.getJSONObject("comments").getJSONArray("data"); for (int count1 = 0; count1 < comments.length(); count1++) { JSONObject comment = comments.getJSONObject(count1); Element replyNode = siocPost.addElement(new QName("has_reply", SIOC_NS)); Element replyPost = replyNode.addElement(new QName("Post", SIOC_NS)); replyPost.addAttribute(new QName("about", RDF_NS), "http://graph.facebook.com/" + comment.getString("id")); replyPost.addElement(new QName("content", SIOC_NS)).setText(comment.getString("message")); String replierID = comment.getJSONObject("from").getString("id"); replyPost.addElement(new QName("hasCreator", SIOC_NS)) .addAttribute(new QName("resource", RDF_NS), "http://graph.facebook.com/" + replierID); try { replyPost.addElement(new QName("created", SIOC_NS)) .setText(comment.getString("created_time")); } catch (JSONException e) { } try { replyPost.addElement(new QName("modified", SIOC_NS)) .setText(comment.getString("updated_time")); } catch (JSONException e) { } } } catch (JSONException e) { // TODO: Log here something, at least during development. } } }
From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java
private MDocument parseDocumentResult(MDocument mdoc, String strResponse) throws JSONException { JSONObject doc = new JSONObject(strResponse); try {//from w ww .j av a 2s. c o m mdoc.title = doc.getString("title"); } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document title"); } try { mdoc.year = doc.getString("year"); } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document year"); } try { mdoc.notes = doc.getString("notes"); } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document notes"); } try { mdoc.type = doc.getString("type"); } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document type"); } try { mdoc.urls = new String[] { doc.getString("url") }; } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document url"); } try { mdoc.pages = doc.getString("pages"); } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document pages"); } try { mdoc.docabstract = doc.getString("abstract"); } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document abstract"); } try { JSONArray authors = doc.getJSONArray("authors"); String[] strAuthors = new String[authors.length()]; for (int j = 0; j < authors.length(); j++) { strAuthors[j] = authors.getString(j); } mdoc.authors = strAuthors; } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document authors"); } try { JSONArray tags = doc.getJSONArray("tags"); String[] mtags = new String[tags.length()]; for (int j = 0; j < tags.length(); j++) { mtags[j] = tags.getString(j); } mdoc.tags = mtags; } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document tags"); } try { JSONObject ids = doc.getJSONObject("identifiers"); mdoc.identifiers = new HashMap<String, String>(); JSONArray names = ids.names(); for (int j = 0; j < names.length(); j++) { mdoc.identifiers.put(names.getString(j), ids.getString(names.getString(j))); } } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document identifiers"); } try { JSONObject ids = doc.getJSONObject("discipline"); mdoc.discipline = new HashMap<String, String>(); JSONArray names = ids.names(); for (int j = 0; j < names.length(); j++) { mdoc.discipline.put(names.getString(j), ids.getString(names.getString(j))); } } catch (JSONException e) { Log.w("WebConnector", "Parsing error while getting document disciplines"); } return mdoc; }
From source file:com.microsoft.services.sharepoint.DocLibClient.java
/** * Retrieves the value of property with a given path and library * /*from w w w .j a v a 2s . co m*/ * @param property * @param path * @param library * @return */ public ListenableFuture<Object> getProperty(final String property, String path, String library) { if (path == null || path.length() == 0) { throw new IllegalArgumentException("Path cannot be null or empty"); } if (property == null || property.length() == 0) { throw new IllegalArgumentException("Property cannot be null or empty"); } String getPropertyUrl; if (library == null) { getPropertyUrl = getSiteUrl() + String.format("_api/files('%s')/%s", urlEncode(path), property); } else { String url = getSiteUrl() + "_api/web/Lists/GetByTitle('%s')/files('%s')/%s"; getPropertyUrl = String.format(url, urlEncode(library.trim()), urlEncode(path), property); } final SettableFuture<Object> result = SettableFuture.create(); ListenableFuture<JSONObject> request = executeRequestJson(getPropertyUrl, "GET"); Futures.addCallback(request, new FutureCallback<JSONObject>() { @Override public void onFailure(Throwable t) { result.setException(t); } @Override public void onSuccess(JSONObject json) { Object propertyResult; try { propertyResult = json.getJSONObject("d").get(property); result.set(propertyResult); } catch (JSONException e) { result.setException(e); } } }); return result; }
From source file:pubsub.io.processing.Pubsub.java
/** * React to messages.../*from ww w .j av a2 s .c o m*/ */ @Override public void onMessage(JSONObject msg) { if (DEBUG) System.out.println(DEBUGTAG + msg.toString()); int callback_id = 0; callback_id = msg.getInt("id"); if (msg.optJSONObject("doc") != null) { JSONObject doc = msg.getJSONObject("doc"); // Get the callback method Method eventMethod = callbacks.get(callback_id); if (eventMethod != null) { try { // Invoke only if the method existed eventMethod.invoke(myParent, doc); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } else if (msg.optJSONArray("doc") != null) { JSONArray doc = msg.getJSONArray("doc"); // Get the callback method Method eventMethod = callbacks.get(callback_id); if (eventMethod != null) { try { // Invoke only if the method existed eventMethod.invoke(myParent, doc); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } else { // Neither... } }
From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java
private void store_set(Storage storage, UIRequest request, String path) throws UIException { try {/*from ww w .j a v a 2s. co m*/ JSONObject restrictions = new JSONObject(); JSONObject data = request.getJSONBody(); if (this.base.equals("role")) { JSONObject fields = data.optJSONObject("fields"); if ((fields.optString("roleName") == null || fields.optString("roleName").equals("")) && fields.optString("displayName") != null) { String test = fields.optString("displayName"); test = test.toUpperCase(); test.replaceAll("\\W", "_"); fields.put("roleName", "ROLE_" + test); data.put("fields", fields); } // If we are updating a role, then we need to clear the userperms cache // Note that creating a role does not impact things until we assign it if (!create) { ResponseCache.clearCache(ResponseCache.USER_PERMS_CACHE); } } if (this.record.getID().equals("media")) { JSONObject fields = data.optJSONObject("fields"); // Handle linked media references if (!fields.has("blobCsid") || StringUtils.isEmpty(fields.getString("blobCsid"))) { // If has blobCsid, already has media link so do nothing more // No media, so consider the source // "sourceUrl" is not a declared field in the app layer config, but the UI passes it in // Can consider mapping srcUri to this if want to clean that up if (fields.has("sourceUrl")) { // We have a source - see where it is from String uri = fields.getString("sourceUrl"); if (uri.contains(BLOBS_SERVICE_URL_PATTERN)) { // This is an uploaded blob, so just pull the csid and set into blobCsid String[] parts = uri.split(BLOBS_SERVICE_URL_PATTERN); // Split to get CSID String[] bits = parts[1].split("/"); // Strip off anything trailing the CSID fields.put("blobCsid", bits[0]); } else { // This must be an external Url source // External Source is handled as params to the CREATE/UPDATE of the media record restrictions.put(Record.BLOB_SOURCE_URL, uri); // Tell the Services to delete the original after creating derivatives restrictions.put(Record.BLOB_PURGE_ORIGINAL, Boolean.toString(true)); } fields.remove("sourceUrl"); data.put("fields", fields); } } } if (this.record.getID().equals("output")) { // // Invoke a report // ReportUtils.invokeReport(this, storage, request, path); } else if (this.record.getID().equals("batchoutput")) { //do a read instead of a create as reports are special and evil JSONObject fields = data.optJSONObject("fields"); JSONObject payload = new JSONObject(); payload.put("mode", "single"); if (fields.has("mode")) { payload.put("mode", fields.getString("mode")); } if (fields.has("docType")) { String type = spec.getRecordByWebUrl(fields.getString("docType")).getServicesTenantSg(); payload.put("docType", type); } if (fields.has("singleCSID")) { payload.put("singleCSID", fields.getString("singleCSID")); } else if (fields.has("groupCSID")) { payload.put("singleCSID", fields.getString("csid")); } JSONObject out = storage.retrieveJSON(base + "/" + path, payload); byte[] data_array = (byte[]) out.get("getByteBody"); String contentDisp = out.has("contentdisposition") ? out.getString("contentdisposition") : null; request.sendUnknown(data_array, out.getString("contenttype"), contentDisp); request.setCacheMaxAgeSeconds(0); // Ensure we do not cache report output. //request.sendJSONResponse(out); request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE); } else { // // <Please document this clause.> // FieldSet displayNameFS = this.record.getDisplayNameField(); String displayNameFieldName = (displayNameFS != null) ? displayNameFS.getID() : null; boolean remapDisplayName = false; String remapDisplayNameValue = null; boolean quickie = false; if (create) { quickie = (data.has("_view") && data.getString("_view").equals("autocomplete")); remapDisplayName = quickie && !"displayName".equals(displayNameFieldName); // Check to see if displayName field needs remapping from UI if (remapDisplayName) { // Need to map the field for displayName, and put it into a proper structure JSONObject fields = data.getJSONObject("fields"); remapDisplayNameValue = fields.getString("displayName"); if (remapDisplayNameValue != null) { // This needs generalizing, in case the remapped name is nested /* * From vocab handling where we know where the termDisplayName is FieldSet parentTermGroup = (FieldSet)displayNameFS.getParent(); JSONArray parentTermInfoArray = new JSONArray(); JSONObject termInfo = new JSONObject(); termInfo.put(displayNameFieldName, remapDisplayNameValue); parentTermInfoArray.put(termInfo); */ fields.put(displayNameFieldName, remapDisplayNameValue); fields.remove("displayName"); } } path = sendJSON(storage, null, data, restrictions); // REM - We needed a way to send query params, so I'm adding "restrictions" here data.put("csid", path); data.getJSONObject("fields").put("csid", path); // Is this needed??? /* String refName = data.getJSONObject("fields").getString("refName"); data.put("urn", refName); data.getJSONObject("fields").put("urn", refName); // This seems wrong - especially when we create from existing. if(remapDisplayName){ JSONObject newdata = new JSONObject(); newdata.put("urn", refName); newdata.put("displayName",quickieDisplayName); data = newdata; } */ } else { path = sendJSON(storage, path, data, restrictions); } if (path == null) { throw new UIException("Insufficient data for create (no fields?)"); } if (this.base.equals("role")) { assignPermissions(storage, path, data); } if (this.base.equals("termlist")) { assignTerms(storage, path, data); } data = reader.getJSON(storage, path); // We do a GET now to read back what we created. if (quickie) { JSONObject newdata = new JSONObject(); JSONObject fields = data.getJSONObject("fields"); String displayName = fields.getString(remapDisplayName ? displayNameFieldName : "displayName"); newdata.put("displayName", remapDisplayNameValue); String refName = fields.getString("refName"); newdata.put("urn", refName); data = newdata; } request.sendJSONResponse(data); request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE); if (create) request.setSecondaryRedirectPath(new String[] { url_base, path }); } } catch (JSONException x) { throw new UIException("Failed to parse JSON: " + x, x); } catch (ExistException x) { UIException uiexception = new UIException(x.getMessage(), 0, "", x); request.sendJSONResponse(uiexception.getJSON()); } catch (UnimplementedException x) { throw new UIException("Unimplemented exception: " + x, x); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x); request.setStatus(x.getStatus()); request.setFailure(true, uiexception); request.sendJSONResponse(uiexception.getJSON()); } catch (Exception x) { throw new UIException(x); } }
From source file:com.example.espn.headlines.Util.java
/** * Parse a server response into a JSON Object. This is a basic * implementation using org.json.JSONObject representation. More * sophisticated applications may wish to do their own parsing. * * The parsed JSON is checked for a variety of error fields and * a FacebookException is thrown if an error condition is set, * populated with the error message and error type or code if * available./* w w w.j a v a2s . c o m*/ * * @param response - string representation of the response * @return the response as a JSON Object * @throws JSONException - if the response is not valid JSON * @throws FacebookError - if an error condition is set */ public static JSONObject parseJson(String response) throws JSONException, FacebookError { // Edge case: when sending a POST request to /[post_id]/likes // the return value is 'true' or 'false'. Unfortunately // these values cause the JSONObject constructor to throw // an exception. if (response.equals("false")) { throw new FacebookError("request failed"); } if (response.equals("true")) { response = "{value : true}"; } JSONObject json = new JSONObject(response); // errors set by the server are not consistent // they depend on the method and endpoint if (json.has("error")) { JSONObject error = json.getJSONObject("error"); throw new FacebookError(error.getString("message"), error.getString("type"), 0); } if (json.has("error_code") && json.has("error_msg")) { throw new FacebookError(json.getString("error_msg"), "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_code")) { throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_msg")) { throw new FacebookError(json.getString("error_msg")); } if (json.has("error_reason")) { throw new FacebookError(json.getString("error_reason")); } return json; }
From source file:com.appdynamics.monitors.nginx.statsExtractor.ServerZoneStatsExtractor.java
@Override public Map<String, String> extractStats(JSONObject respJson) { JSONObject serverZones = respJson.getJSONObject("server_zones"); Map<String, String> serverZonesStats = getServerZonesStats(serverZones); return serverZonesStats; }
From source file:com.appdynamics.monitors.nginx.statsExtractor.ServerZoneStatsExtractor.java
private Map<String, String> getServerZonesStats(JSONObject serverZones) { Map<String, String> serverZonesStats = new HashMap<String, String>(); Set<String> serverZoneNames = serverZones.keySet(); for (String serverZoneName : serverZoneNames) { JSONObject serverZone = serverZones.getJSONObject(serverZoneName); long processing = serverZone.getLong("processing"); serverZonesStats.put("server_zones|" + serverZoneName + "|processing", String.valueOf(processing)); long requests = serverZone.getLong("requests"); serverZonesStats.put("server_zones|" + serverZoneName + "|requests", String.valueOf(requests)); JSONObject responses = serverZone.getJSONObject("responses"); long resp1xx = responses.getLong("1xx"); serverZonesStats.put("server_zones|" + serverZoneName + "|responses|1xx", String.valueOf(resp1xx)); long resp2xx = responses.getLong("2xx"); serverZonesStats.put("server_zones|" + serverZoneName + "|responses|2xx", String.valueOf(resp2xx)); long resp3xx = responses.getLong("3xx"); serverZonesStats.put("server_zones|" + serverZoneName + "|responses|3xx", String.valueOf(resp3xx)); long resp4xx = responses.getLong("4xx"); serverZonesStats.put("server_zones|" + serverZoneName + "|responses|4xx", String.valueOf(resp4xx)); long resp5xx = responses.getLong("5xx"); serverZonesStats.put("server_zones|" + serverZoneName + "|responses|5xx", String.valueOf(resp5xx)); long respTotal = responses.getLong("total"); serverZonesStats.put("server_zones|" + serverZoneName + "|responses|total", String.valueOf(respTotal)); long received = serverZone.getLong("received"); serverZonesStats.put("server_zones|" + serverZoneName + "|received", String.valueOf(received)); long sent = serverZone.getLong("sent"); serverZonesStats.put("server_zones|" + serverZoneName + "|sent", String.valueOf(sent)); }//from w ww . j a v a2 s . c o m return serverZonesStats; }