List of usage examples for org.json JSONObject optInt
public int optInt(String key, int defaultValue)
From source file:com.google.android.gcm.demo.app.GcmBroadcastReceiver.java
@Override public void onReceive(Context context, Intent intent) { GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); ctx = context;//from www . ja va 2 s . c om String messageType = gcm.getMessageType(intent); if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + intent.getExtras().toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + intent.getExtras().toString()); } else { sendNotification("Received: " + intent.getExtras().toString()); // "urn":"soundcloud:sounds:125","finished_at":"0001-01-01T00:00:00Z","last_played_at":"0001-01-01T00:00:00Z","progress":0} LLQueue queue = LLQueue.get(); if (queue == null) return; //queue.loadListenLaterQueue(); if (intent.hasExtra("set")) { String set = intent.getStringExtra("set"); try { JSONObject obj = new JSONObject(set); String urn = obj.optString("urn"); Log.d(TAG, "GCM set with urn:" + urn); if (!TextUtils.isEmpty(urn)) { queue.addUrn(urn); } } catch (JSONException e) { Log.w(TAG, e); } } else if (intent.hasExtra("delete")) { String delete = intent.getStringExtra("delete"); try { JSONObject obj = new JSONObject(delete); String urn = obj.optString("urn"); Log.d(TAG, "GCM set with urn:" + urn); if (!TextUtils.isEmpty(urn)) { queue.removeUrn(urn); } } catch (JSONException e) { Log.w(TAG, e); } } else if (intent.hasExtra("play")) { String play = intent.getStringExtra("play"); try { JSONObject obj = new JSONObject(play); String urn = obj.optString("urn"); String toggleAt = obj.optString("toggle_at"); long progress = obj.optInt("progress", 0); Log.d(TAG, "GCM play with urn:" + urn + " ,togglet_at:" + toggleAt); Intent playIntent = new Intent(); queue.playUrn(urn, progress); if (!TextUtils.isEmpty(toggleAt)) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");//spec for RFC3339 (with fractional seconds) try { Date date = format.parse(toggleAt); Log.d(TAG, "parsed date:" + date); // AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), PendingIntent.getActivity(context, 0, playIntent, 0)); } catch (ParseException e) { Log.w(TAG, e); } } else { } } catch (JSONException e) { Log.w(TAG, e); } } } setResultCode(Activity.RESULT_OK); }
From source file:org.apache.usergrid.chop.webapp.view.chart.layout.ChartLayout.java
protected void pointClicked(JSONObject json) throws JSONException { params.setCommitId(json.optString("commitId")); params.setRunNumber(json.optInt("runNumber", 0)); detailsTable.setContent(json);/*from w w w .j a v a2 s . com*/ noteLayout.load(params.getCommitId(), params.getRunNumber()); }
From source file:com.facebook.share.internal.LikeActionController.java
private static LikeActionController deserializeFromJson(String controllerJsonString) { LikeActionController controller;//from www . j av a2 s . c o 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; } String objectId = controllerJson.getString(JSON_STRING_OBJECT_ID_KEY); int objectTypeInt = controllerJson.optInt(JSON_INT_OBJECT_TYPE_KEY, LikeView.ObjectType.UNKNOWN.getValue()); controller = new LikeActionController(objectId, LikeView.ObjectType.fromInt(objectTypeInt)); // 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); JSONObject analyticsJSON = controllerJson.optJSONObject(JSON_BUNDLE_FACEBOOK_DIALOG_ANALYTICS_BUNDLE); if (analyticsJSON != null) { controller.facebookDialogAnalyticsBundle = 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.internal.server.servlets.xfer.SFTPTransfer.java
private void transferWithExceptions() throws ServletException, IOException, URISyntaxException, JSONException { String host, remotePath, user, passphrase; int port;/*from www .j av a 2 s . c o m*/ try { JSONObject requestInfo = OrionServlet.readJSONRequest(request); host = requestInfo.getString(ProtocolConstants.KEY_HOST); remotePath = requestInfo.getString(ProtocolConstants.KEY_PATH); port = requestInfo.optInt(ProtocolConstants.KEY_PORT, 22); user = requestInfo.getString(ProtocolConstants.KEY_USER_NAME); passphrase = requestInfo.getString(ProtocolConstants.KEY_PASSPHRASE); } catch (Exception e) { handleException("Request body is not in the expected format", e, HttpServletResponse.SC_BAD_REQUEST); return; } File localFile; try { localFile = localRoot.toLocalFile(EFS.NONE, null); } catch (CoreException e) { handleException(NLS.bind("Import is not supported at this location: {0}", localRoot.toString()), e, HttpServletResponse.SC_NOT_IMPLEMENTED); return; } SFTPTransferJob job; if (TransferServlet.PREFIX_IMPORT.equals(new Path(request.getPathInfo()).segment(0))) { job = new SFTPImportJob(TaskJobHandler.getUserId(request), localFile, host, port, new Path(remotePath), user, passphrase, options); } else { job = new SFTPExportJob(TaskJobHandler.getUserId(request), localFile, host, port, new Path(remotePath), user, passphrase, options); } job.schedule(); TaskInfo task = job.getTask(); JSONObject result = task.toJSON(); //Not nice that the import service knows the location of the task servlet, but task service doesn't know this either URI requestLocation = ServletResourceHandler.getURI(request); URI taskLocation = new URI(requestLocation.getScheme(), requestLocation.getAuthority(), "/task/temp/" + task.getId(), null, null); //$NON-NLS-1$ result.put(ProtocolConstants.KEY_LOCATION, taskLocation); response.setHeader(ProtocolConstants.HEADER_LOCATION, ServletResourceHandler.resovleOrionURI(request, taskLocation).toString()); OrionServlet.writeJSONResponse(request, response, result); response.setStatus(HttpServletResponse.SC_ACCEPTED); }
From source file:org.uiautomation.ios.wkrdp.internal.DefaultMessageHandler.java
private void process(String rawMessage) { IOSMessage message = factory.create(rawMessage); for (MessageListener l : listeners) { l.onMessage(message);//w w w . jav a 2s. com } if (message instanceof ApplicationDataMessage) { JSONObject content = ((ApplicationDataMessage) message).getMessage(); if ((content.optInt("id", -1) != -1)) { defaultFinder.addResponse(content); } } }
From source file:com.vk.sdkweb.api.model.ParseUtils.java
/** * Parse boolean from JSONObject with given name. * * @param from server response like this format: {@code field: 1} * @param name name of field to read/*from ww w . j av a 2s . co m*/ */ public static boolean parseBoolean(JSONObject from, String name) { return from != null && from.optInt(name, 0) == 1; }
From source file:com.vk.sdkweb.api.model.ParseUtils.java
/** * Parse int from JSONObject with given name. * * @param from server response like this format: {@code field: 34} * @param name name of field to read//ww w. j av a2 s .co m */ public static int parseInt(JSONObject from, String name) { if (from == null) return 0; return from.optInt(name, 0); }
From source file:fr.haploid.webservices.WebServicesTask.java
public WebServicesTask(CobaltFragment fragment, JSONObject call) { mFragment = fragment;//from w w w .j a va 2 s . c om mCall = call; try { mCallId = call.getLong(kJSCallId); JSONObject data = call.getJSONObject(Cobalt.kJSData); mSendCacheResult = data.optBoolean(kJSSendCacheResult); mUrl = data.optString(kJSUrl, null); if (mUrl != null) { mHeaders = data.optJSONObject(kJSHeaders); mParams = data.optString(kJSParams); mTimeout = data.optInt(kJSTimeout, -1); mType = data.getString(kJSType); mSaveToStorage = data.optBoolean(kJSSaveToStorage); } if (mSendCacheResult || mUrl != null) mProcessData = data.optJSONObject(kJSProcessData); if (mSendCacheResult || (mUrl != null && mSaveToStorage)) { mStorageKey = data.getString(kJSStorageKey); } } catch (JSONException exception) { if (Cobalt.DEBUG) { Log.e(WebServicesPlugin.TAG, TAG + ": check your Webservice call. Known issues: \n" + "\t- missing data field, \n" + "\t- url field is defined but but missing type field, \n" + "\t- sendCacheResult field is true or url field is defined and saveToStorage field is true but missing storageKey field.\n"); exception.printStackTrace(); } } }
From source file:fr.haploid.webservices.WebServicesTask.java
@Override protected void onPostExecute(JSONObject response) { super.onPostExecute(response); if (response != null) { try {//from w ww .j a v a2 s . c om JSONObject message = new JSONObject(); message.put(Cobalt.kJSType, Cobalt.JSTypePlugin); message.put(Cobalt.kJSPluginName, JSPluginNameWebservices); if (response.getBoolean(kJSSuccess)) message.put(Cobalt.kJSAction, JSOnWSResult); else message.put(Cobalt.kJSAction, JSOnWSError); JSONObject data = new JSONObject(); data.put(kJSCallId, mCallId); int statusCode = response.optInt(kJSStatusCode, -1); if (statusCode != -1) data.put(kJSStatusCode, statusCode); String text = response.optString(kJSText, null); if (text != null) { try { JSONObject responseData = new JSONObject(text); responseData = WebServicesPlugin.treatData(responseData, mProcessData, mFragment); data.put(Cobalt.kJSData, responseData); } catch (JSONException exception) { Log.w(Cobalt.TAG, TAG + " - onPostExecute: response could not be parsed as JSON. Response: " + text); exception.printStackTrace(); data.put(kJSText, text); } } message.put(Cobalt.kJSData, data); if (response.getBoolean(kJSSuccess) || WebServicesPlugin.handleError(mCall, message, mFragment)) mFragment.sendMessage(message); if (mSaveToStorage && mStorageKey != null) { WebServicesPlugin.storeValue(text, mStorageKey, mFragment); } else if (Cobalt.DEBUG) { Log.w(Cobalt.TAG, TAG + " - onPostExecute: missing storageKey field \n" + "Web service response will not be stored in cache."); } } catch (JSONException exception) { exception.printStackTrace(); } } else if (Cobalt.DEBUG) { Log.d(Cobalt.TAG, TAG + " - onPostExecute: url and/or type fields were empty, Webservice has not been called."); } }
From source file:com.richtodd.android.quiltdesign.block.PaperPiecedBlock.java
static final PaperPiecedBlock createFromJSONObject(JSONObject jsonObject) throws JSONException { float width = (float) jsonObject.optDouble("width", 0); float height = (float) jsonObject.optDouble("height", 0); int backgroundColor = jsonObject.optInt("backgroundColor", Color.WHITE); PaperPiecedBlock block = new PaperPiecedBlock(width, height, backgroundColor); JSONArray jsonPieces = jsonObject.getJSONArray("pieces"); for (int idx = 0; idx < jsonPieces.length(); ++idx) { JSONObject jsonPiece = jsonPieces.getJSONObject(idx); block.m_pieces.add(PaperPiecedBlockPiece.createFromJSONObject(jsonPiece)); }// w ww. jav a 2 s . c o m return block; }