List of usage examples for org.json JSONObject optString
public String optString(String key, String defaultValue)
From source file:org.schedulesdirect.grabber.ProgramTask.java
@Override public void run() { long start = System.currentTimeMillis(); DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.PROGRAMS, clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl()); try {/*from ww w . j ava2 s . c o m*/ JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(this.req), JSONArray.class); for (int i = 0; i < resp.length(); ++i) { JSONObject o = resp.getJSONObject(i); String id = o.optString("programID", "<unknown>"); if (!JsonResponseUtils.isErrorResponse(o)) { if (id.startsWith("EP")) seriesIds.add(Program.convertToSeriesId(id)); Path p = vfs.getPath(targetDir, String.format("%s.txt", id)); Files.write(p, o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.INVALID_PROGID || JsonResponseUtils.getErrorCode(o) == ApiResponse.PROGRAMID_QUEUED) { String msg = String.format("Missing program object: %s", id); if (!logMissingAtDebug) LOG.warn(msg); else LOG.debug(msg); if (retrySet != null) retrySet.add(id); } else throw new InvalidJsonObjectException("Error received for Program", o.toString(3)); } } catch (JSONException | JsonParseException e) { Grabber.failedTask = true; LOG.error("JSONError!", e); throw new RuntimeException(e); } catch (IOException e) { Grabber.failedTask = true; LOG.error("IOError receiving program data; filling in empty program info for non-existent program ids!", e); try { JSONArray ids = this.req; for (int i = 0; i < ids.length(); ++i) { String id = ids.getString(i); Path p = vfs.getPath(targetDir, String.format("%s.txt", id)); if (!Files.exists(p)) Files.write(p, Program.EMPTY_PROGRAM.getBytes(ZipEpgClient.ZIP_CHARSET)); } } catch (Exception x) { LOG.error("Unexpected error!", x); throw new RuntimeException(x); } } LOG.info(String.format("Completed ProgramTask in %dms [%d programs]", System.currentTimeMillis() - start, this.req.length())); }
From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java
private String[] refreshContacts(boolean requestIdentityToken, String nonce, String userName) { try {//from ww w. j ava 2 s . c om String url = "https://layer-identity-provider.herokuapp.com/apps/" + appId + "/atlas_identities"; HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "application/json"); post.setHeader("X_LAYER_APP_ID", appId); JSONObject rootObject = new JSONObject(); if (requestIdentityToken) { rootObject.put("nonce", nonce); rootObject.put("name", userName); } else { rootObject.put("name", "Web"); // name must be specified to make entiry valid } StringEntity entity = new StringEntity(rootObject.toString(), "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = (new DefaultHttpClient()).execute(post); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode() && HttpStatus.SC_CREATED != response.getStatusLine().getStatusCode()) { StringBuilder sb = new StringBuilder(); sb.append("Got status ").append(response.getStatusLine().getStatusCode()).append(" [") .append(response.getStatusLine()).append("] when logging in. Request: ").append(url); if (requestIdentityToken) sb.append(" login: ").append(userName).append(", nonce: ").append(nonce); Log.e(TAG, sb.toString()); return new String[] { null, sb.toString() }; } String responseString = EntityUtils.toString(response.getEntity()); JSONObject jsonResp = new JSONObject(responseString); JSONArray atlasIdentities = jsonResp.getJSONArray("atlas_identities"); List<Participant> participants = new ArrayList<Participant>(atlasIdentities.length()); for (int i = 0; i < atlasIdentities.length(); i++) { JSONObject identity = atlasIdentities.getJSONObject(i); Participant participant = new Participant(); participant.firstName = identity.getString("name"); participant.userId = identity.getString("id"); participants.add(participant); } if (participants.size() > 0) { setParticipants(participants); save(); if (debug) Log.d(TAG, "refreshContacts() contacts: " + atlasIdentities); } if (requestIdentityToken) { String error = jsonResp.optString("error", null); String identityToken = jsonResp.optString("identity_token"); return new String[] { identityToken, error }; } return new String[] { null, "Refreshed " + participants.size() + " contacts" }; } catch (Exception e) { Log.e(TAG, "Error when fetching identity token", e); return new String[] { null, "Cannot obtain identity token. " + e }; } }
From source file:com.trk.aboutme.facebook.FacebookRequestError.java
static FacebookRequestError checkResponseAndCreateError(JSONObject singleResult, Object batchResult, HttpURLConnection connection) { try {/*from ww w . j a va 2 s. c om*/ if (singleResult.has(CODE_KEY)) { int responseCode = singleResult.getInt(CODE_KEY); Object body = Utility.getStringPropertyAsJSON(singleResult, BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY); if (body != null && body instanceof JSONObject) { JSONObject jsonBody = (JSONObject) body; // Does this response represent an error from the service? We might get either an "error" // with several sub-properties, or else one or more top-level fields containing error info. String errorType = null; String errorMessage = null; int errorCode = INVALID_ERROR_CODE; int errorSubCode = INVALID_ERROR_CODE; boolean hasError = false; if (jsonBody.has(ERROR_KEY)) { // We assume the error object is correctly formatted. JSONObject error = (JSONObject) Utility.getStringPropertyAsJSON(jsonBody, ERROR_KEY, null); errorType = error.optString(ERROR_TYPE_FIELD_KEY, null); errorMessage = error.optString(ERROR_MESSAGE_FIELD_KEY, null); errorCode = error.optInt(ERROR_CODE_FIELD_KEY, INVALID_ERROR_CODE); errorSubCode = error.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE); hasError = true; } else if (jsonBody.has(ERROR_CODE_KEY) || jsonBody.has(ERROR_MSG_KEY) || jsonBody.has(ERROR_REASON_KEY)) { errorType = jsonBody.optString(ERROR_REASON_KEY, null); errorMessage = jsonBody.optString(ERROR_MSG_KEY, null); errorCode = jsonBody.optInt(ERROR_CODE_KEY, INVALID_ERROR_CODE); errorSubCode = jsonBody.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE); hasError = true; } if (hasError) { return new FacebookRequestError(responseCode, errorCode, errorSubCode, errorType, errorMessage, jsonBody, singleResult, batchResult, connection); } } // If we didn't get error details, but we did get a failure response code, report it. if (!HTTP_RANGE_SUCCESS.contains(responseCode)) { return new FacebookRequestError(responseCode, INVALID_ERROR_CODE, INVALID_ERROR_CODE, null, null, singleResult.has(BODY_KEY) ? (JSONObject) Utility.getStringPropertyAsJSON(singleResult, BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY) : null, singleResult, batchResult, connection); } } } catch (JSONException e) { // defer the throwing of a JSONException to the graph object proxy } return null; }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Open the notification in NotificationActivity * @param args//w w w . j a va 2 s . c om * @param callbackContext */ protected void openNotification(JSONArray args, final CallbackContext callbackContext) { Log.d(TAG, "OPENNOTIFICATION"); try { JSONObject notificationJSON = args.getJSONObject(0); // Workaround for pre-1.1.1 SDK notificationJSON.put("_id", notificationJSON.get("notificationId")); NotificareNotification notification = new NotificareNotification(notificationJSON); Intent notificationIntent = new Intent() .setClass(Notificare.shared().getApplicationContext(), NotificationActivity.class) .setAction(Notificare.INTENT_ACTION_NOTIFICATION_OPENED) .putExtra(Notificare.INTENT_EXTRA_NOTIFICATION, notification) .putExtra(Notificare.INTENT_EXTRA_DISPLAY_MESSAGE, Notificare.shared().getDisplayMessage()) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); if (notificationJSON.optString("itemId", null) != null) { notificationIntent.putExtra(Notificare.INTENT_EXTRA_INBOX_ITEM_ID, notificationJSON.getString("itemId")); } cordova.getActivity().startActivity(notificationIntent); if (callbackContext == null) { return; } callbackContext.success(); } catch (JSONException e) { if (callbackContext == null) { return; } callbackContext.error("JSON parse error"); } }
From source file:com.phelps.liteweibo.model.weibo.CommentList.java
public static CommentList parse(String jsonString) { if (TextUtils.isEmpty(jsonString)) { return null; }/*from w w w.j a v a2 s . co m*/ CommentList comments = new CommentList(); try { JSONObject jsonObject = new JSONObject(jsonString); comments.previous_cursor = jsonObject.optString("previous_cursor", "0"); comments.next_cursor = jsonObject.optString("next_cursor", "0"); comments.total_number = jsonObject.optInt("total_number", 0); JSONArray jsonArray = jsonObject.optJSONArray("comments"); if (jsonArray != null && jsonArray.length() > 0) { int length = jsonArray.length(); comments.commentList = new ArrayList<Comment>(length); for (int ix = 0; ix < length; ix++) { comments.commentList.add(Comment.parse(jsonArray.optJSONObject(ix))); } } } catch (JSONException e) { e.printStackTrace(); } return comments; }
From source file:org.b3log.solo.processor.util.Filler.java
/** * Processes the abstract of the specified article with the specified preference. * /*from w w w . ja va 2 s . c o m*/ * <p> * <ul> * <li>If the abstract is {@code null}, sets it with ""</li> * <li>If user configured preference "titleOnly", sets the abstract with ""</li> * <li>If user configured preference "titleAndContent", sets the abstract with the content of the article</li> * </ul> * </p> * * @param preference the specified preference * @param article the specified article */ private void processArticleAbstract(final JSONObject preference, final JSONObject article) { final String articleAbstract = article.optString(Article.ARTICLE_ABSTRACT, null); if (null == articleAbstract) { article.put(Article.ARTICLE_ABSTRACT, ""); } final String articleListStyle = preference.optString(Preference.ARTICLE_LIST_STYLE); if ("titleOnly".equals(articleListStyle)) { article.put(Article.ARTICLE_ABSTRACT, ""); } else if ("titleAndContent".equals(articleListStyle)) { article.put(Article.ARTICLE_ABSTRACT, article.optString(Article.ARTICLE_CONTENT)); } }
From source file:com.andybotting.tramhunter.objects.FavouriteList.java
/** * Get the favourite items//from w w w . j a v a 2 s . c o m * @return */ public ArrayList<Favourite> getFavouriteItems() { ArrayList<Favourite> favourites = new ArrayList<Favourite>(); JSONArray favouriteJSONArray = null; TramHunterDB db = new TramHunterDB(); // Fetch JSON favourite stops string from preferences String favouriteString = mPreferenceHelper.getStarredStopsString(); if (LOGV) Log.i(TAG, "Parsing favourite string: " + favouriteString); // Check to see if we even have any favourites if (favouriteString.length() > 1) { // Convert any old favourites - if not a JSON Array if (!favouriteString.contains("[")) favouriteString = convertOldFavourites(favouriteString); try { favouriteJSONArray = new JSONArray(favouriteString); for (int i = 0; i < favouriteJSONArray.length(); i++) { JSONObject favouriteJSONObject = favouriteJSONArray.getJSONObject(i); int tramTrackerID = favouriteJSONObject.optInt("stop"); int routeID = favouriteJSONObject.optInt("route", -1); String name = favouriteJSONObject.optString("name", null); Stop stop = db.getStop(tramTrackerID); Route route = null; if (routeID != -1) route = db.getRoute(routeID); favourites.add(new Favourite(stop, route, name)); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } db.close(); return favourites; }
From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java
/** * *//* w w w . j av a 2s. c o m*/ @Override protected void onPostExecute(final JSONArray resultList) { try { if (serverConn.hasError()) hasError = true; else if (resultList != null && resultList.length() > 0) { JSONObject resultListItem; try { resultListItem = resultList.getJSONObject(0); /* UUID */ final String uuid = resultListItem.optString("uuid", ""); if (uuid != null && uuid.length() != 0) ConfigHelper.setUUID(activity.getApplicationContext(), uuid); /* urls */ final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings(); final JSONObject urls = resultListItem.optJSONObject("urls"); if (urls != null) { final Iterator<String> keys = urls.keys(); while (keys.hasNext()) { final String key = keys.next(); final String value = urls.optString(key, null); if (value != null) { volatileSettings.put("url_" + key, value); if ("statistics".equals(key)) { ConfigHelper.setCachedStatisticsUrl(value, activity); } else if ("control_ipv4_only".equals(key)) { ConfigHelper.setCachedControlServerNameIpv4(value, activity); } else if ("control_ipv6_only".equals(key)) { ConfigHelper.setCachedControlServerNameIpv6(value, activity); } else if ("url_ipv4_check".equals(key)) { ConfigHelper.setCachedIpv4CheckUrl(value, activity); } else if ("url_ipv6_check".equals(key)) { ConfigHelper.setCachedIpv6CheckUrl(value, activity); } } } } /* qos names */ final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc"); if (qosNames != null) { final Map<String, String> qosNamesMap = new HashMap<String, String>(); for (int i = 0; i < qosNames.length(); i++) { JSONObject json = qosNames.getJSONObject(i); qosNamesMap.put(json.optString("test_type"), json.optString("name")); } ConfigHelper.setCachedQoSNames(qosNamesMap, activity); } /* map server */ final JSONObject mapServer = resultListItem.optJSONObject("map_server"); if (mapServer != null) { final String host = mapServer.optString("host"); final int port = mapServer.optInt("port"); final boolean ssl = mapServer.optBoolean("ssl"); if (host != null && port > 0) ConfigHelper.setMapServer(host, port, ssl); } /* control server version */ final JSONObject versions = resultListItem.optJSONObject("versions"); if (versions != null) { if (versions.has("control_server_version")) { ConfigHelper.setControlServerVersion(activity, versions.optString("control_server_version")); } } // /////////////////////////////////////////////////////// // HISTORY / FILTER final JSONObject historyObject = resultListItem.getJSONObject("history"); final JSONArray deviceArray = historyObject.getJSONArray("devices"); final JSONArray networkArray = historyObject.getJSONArray("networks"); final String historyDevices[] = new String[deviceArray.length()]; for (int i = 0; i < deviceArray.length(); i++) historyDevices[i] = deviceArray.getString(i); final String historyNetworks[] = new String[networkArray.length()]; for (int i = 0; i < networkArray.length(); i++) historyNetworks[i] = networkArray.getString(i); // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// activity.setSettings(historyDevices, historyNetworks); activity.setHistoryDirty(true); } catch (final JSONException e) { e.printStackTrace(); } } else Log.i(DEBUG_TAG, "LEERE LISTE"); } finally { if (endTaskListener != null) endTaskListener.taskEnded(resultList); } }
From source file:com.facebook.internal.LikeActionController.java
private static LikeActionController deserializeFromJson(String controllerJsonString) { LikeActionController controller;// w w w . j a v a 2 s . co m try { JSONObject controllerJson = new JSONObject(controllerJsonString); int version = controllerJson.optInt(JSON_INT_VERSION_KEY, -1); if (version != LIKE_ACTION_CONTROLLER_VERSION) { // Don't attempt to deserialize a controller that might be serialized differently than expected. return null; } controller = new LikeActionController(Session.getActiveSession(), controllerJson.getString(JSON_STRING_OBJECT_ID_KEY)); // Make sure to default to null and not empty string, to keep the logic elsewhere functioning properly. controller.likeCountStringWithLike = controllerJson.optString(JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY, null); controller.likeCountStringWithoutLike = controllerJson .optString(JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY, null); controller.socialSentenceWithLike = controllerJson.optString(JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY, null); controller.socialSentenceWithoutLike = controllerJson .optString(JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY, null); controller.isObjectLiked = controllerJson.optBoolean(JSON_BOOL_IS_OBJECT_LIKED_KEY); controller.unlikeToken = controllerJson.optString(JSON_STRING_UNLIKE_TOKEN_KEY, null); String pendingCallIdString = controllerJson.optString(JSON_STRING_PENDING_CALL_ID_KEY, null); if (!Utility.isNullOrEmpty(pendingCallIdString)) { controller.pendingCallId = UUID.fromString(pendingCallIdString); } JSONObject analyticsJSON = controllerJson.optJSONObject(JSON_BUNDLE_PENDING_CALL_ANALYTICS_BUNDLE); if (analyticsJSON != null) { controller.pendingCallAnalyticsBundle = BundleJSONConverter.convertToBundle(analyticsJSON); } } catch (JSONException e) { Log.e(TAG, "Unable to deserialize controller from JSON", e); controller = null; } return controller; }
From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java
@Test public void testGetListOfConfigEntries() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project metadata WebRequest request = getGetRequest(contentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject project = new JSONObject(response.getText()); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG); JSONObject configResponse = listConfigEntries(gitConfigUri); JSONArray configEntries = configResponse.getJSONArray(ProtocolConstants.KEY_CHILDREN); for (int i = 0; i < configEntries.length(); i++) { JSONObject configEntry = configEntries.getJSONObject(i); assertNotNull(configEntry.optString(GitConstants.KEY_CONFIG_ENTRY_KEY, null)); assertNotNull(configEntry.optString(GitConstants.KEY_CONFIG_ENTRY_VALUE, null)); assertConfigUri(configEntry.getString(ProtocolConstants.KEY_LOCATION)); assertCloneUri(configEntry.getString(GitConstants.KEY_CLONE)); assertEquals(ConfigOption.TYPE, configEntry.getString(ProtocolConstants.KEY_TYPE)); }/* w ww . j a va 2 s.c o m*/ } }