List of usage examples for org.json JSONException getMessage
public String getMessage()
From source file:com.webXells.ImageResizer.ImageResizePlugin.java
@Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) { JSONObject params;/* w ww.j a v a2 s . c o m*/ String imageData; String imageDataType; String format; Bitmap bmp; Log.d("PLUGIN", action); try { // parameters (forst object of the json array) params = data.getJSONObject(0); // image data, either base64 or url imageData = params.getString("data"); // which data type is that, defaults to base64 imageDataType = params.has("imageDataType") ? params.getString("imageDataType") : DEFAULT_IMAGE_DATA_TYPE; // which format should be used, defaults to jpg format = params.has("format") ? params.getString("format") : DEFAULT_FORMAT; // create the Bitmap object, needed for all functions bmp = getBitmap(imageData, imageDataType); } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } catch (IOException e) { callbackContext.error(e.getMessage()); return false; } // resize the image Log.d("PLUGIN", "passed init"); if (action.equals("resizeImage")) { try { double widthFactor; double heightFactor; // compression quality int quality = params.getInt("quality"); // Pixels or Factor resize String resizeType = params.getString("resizeType"); // Get width and height parameters double width = params.getDouble("width"); double height = params.getDouble("height"); if (resizeType.equals(RESIZE_TYPE_PIXEL)) { widthFactor = width / ((double) bmp.getWidth()); heightFactor = height / ((double) bmp.getHeight()); } else { widthFactor = width; heightFactor = height; } Bitmap resized = getResizedBitmap(bmp, (float) widthFactor, (float) heightFactor); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (format.equals(FORMAT_PNG)) { resized.compress(Bitmap.CompressFormat.PNG, quality, baos); } else { resized.compress(Bitmap.CompressFormat.JPEG, quality, baos); } byte[] b = baos.toByteArray(); String returnString = Base64.encodeToString(b, Base64.DEFAULT); // return object JSONObject res = new JSONObject(); res.put("imageData", returnString); res.put("width", resized.getWidth()); res.put("height", resized.getHeight()); callbackContext.success(res); return true; } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } } else if (action.equals("imageSize")) { try { JSONObject res = new JSONObject(); res.put("width", bmp.getWidth()); res.put("height", bmp.getHeight()); Log.d("PLUGIN", "finished get image size"); callbackContext.success(res); return true; } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } } else if (action.equals("storeImage")) { try { // Obligatory Parameters, throw JSONException if not found String filename = params.getString("filename"); filename = (filename.contains(".")) ? filename : filename + "." + format; String directory = params.getString("directory"); directory = directory.startsWith("/") ? directory : "/" + directory; int quality = params.getInt("quality"); OutputStream outStream; // store the file locally using the external storage directory File file = new File(Environment.getExternalStorageDirectory().toString() + directory, filename); try { outStream = new FileOutputStream(file); if (format.equals(FORMAT_PNG)) { bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream); } else { bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream); } outStream.flush(); outStream.close(); JSONObject res = new JSONObject(); res.put("url", "file://" + file.getAbsolutePath()); callbackContext.success(res); return true; } catch (IOException e) { callbackContext.error(e.getMessage()); return false; } } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } } Log.d("PLUGIN", "unknown action"); return false; }
From source file:com.samknows.measurement.schedule.condition.ConditionResult.java
public void generateOut(String id, String... data) { DCSStringBuilder b = new DCSStringBuilder(); b.append(id);//from w w w .j av a 2 s .c om long time = System.currentTimeMillis(); b.append(time); if (isSuccess) { b.append(Constants.RESULT_OK); } else { b.append(Constants.RESULT_FAIL); } for (String s : data) { if (s != null) { b.append(s); } } outString = b.build(); outJSON = new JSONObject(); try { outJSON.put(JSON_TYPE, id); outJSON.put(JSON_TIMESTAMP, time / 1000 + ""); outJSON.put(JSON_DATETIME, new java.util.Date(time).toString()); outJSON.put(JSON_SUCCESS, Boolean.toString(isSuccess)); if (json_fields != null && json_fields.length == data.length) { for (int i = 0; i < json_fields.length; i++) { outJSON.put(json_fields[i], data[i]); } } } catch (JSONException je) { Logger.e(this, "error in updating JSONObject: " + je.getMessage()); } }
From source file:com.example.jumpnote.android.SyncAdapter.java
@Override public void onPerformSync(final Account account, Bundle extras, String authority, final ContentProviderClient provider, final SyncResult syncResult) { TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String clientDeviceId = tm.getDeviceId(); final long newSyncTime = System.currentTimeMillis(); final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false); C2DMReceiver.refreshAppC2DMRegistrationState(mContext); Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name); // Read this account's sync metadata final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0); long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0); long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0); // Check for changes in either app-wide auto sync registration information, or changes in // the user's preferences for auto sync on this account; if either changes, piggy back the // new registration information in this sync. long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext); boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically() && ContentResolver.getSyncAutomatically(account, JumpNoteContract.AUTHORITY); boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false); // Will be 0 for no change, -1 for unregister, 1 for register. final int deviceRegChange; JsonRpcClient.Call deviceRegCall = null; if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize || manualSync) {/*from w ww . j av a 2s.co m*/ String registrationId = C2DMessaging.getRegistrationId(mContext); deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1; if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Auto sync selection or registration information has changed, " + (deviceRegChange == 1 ? "registering" : "unregistering") + " messaging for this device, for account " + account.name); } try { if (deviceRegChange == 1) { // Register device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesRegister.METHOD); JSONObject params = new JSONObject(); DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId); params.put(JumpNoteProtocol.DevicesRegister.ARG_DEVICE, device.toJSON()); deviceRegCall.setParams(params); } else { // Unregister device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesUnregister.METHOD); JSONObject params = new JSONObject(); params.put(JumpNoteProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId); deviceRegCall.setParams(params); } } catch (JSONException e) { logErrorMessage("Error generating device registration remote RPC parameters.", manualSync); e.printStackTrace(); return; } } else { deviceRegChange = 0; } // Get the list of locally changed notes. If this is an upload-only sync and there were // no local changes, cancel the sync. List<ModelJava.Note> locallyChangedNotes = null; try { locallyChangedNotes = getLocallyChangedNotes(provider, account, new Date(lastSyncTime)); } catch (RemoteException e) { logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync); e.printStackTrace(); syncResult.stats.numIoExceptions++; return; } if (uploadOnly && locallyChangedNotes.isEmpty() && deviceRegCall == null) { Log.i(TAG, "No local changes; upload-only sync canceled."); return; } // Set up the RPC sync calls final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext, Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL); try { jsonRpcClient.blockingAuthenticateAccount(account, manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION, false); } catch (AuthenticationException e) { logErrorMessage("Authentication exception when attempting to sync.", manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } catch (OperationCanceledException e) { Log.i(TAG, "Sync for account " + account.name + " manually canceled."); return; } catch (RequestedUserAuthenticationException e) { syncResult.stats.numAuthExceptions++; return; } catch (InvalidAuthTokenException e) { logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.", manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } // Set up the notes sync call. JsonRpcClient.Call notesSyncCall = new JsonRpcClient.Call(JumpNoteProtocol.NotesSync.METHOD); try { JSONObject params = new JSONObject(); params.put(JumpNoteProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId); params.put(JumpNoteProtocol.NotesSync.ARG_SINCE_DATE, Util.formatDateISO8601(new Date(lastServerSyncTime))); JSONArray locallyChangedNotesJson = new JSONArray(); for (ModelJava.Note locallyChangedNote : locallyChangedNotes) { locallyChangedNotesJson.put(locallyChangedNote.toJSON()); } params.put(JumpNoteProtocol.NotesSync.ARG_LOCAL_NOTES, locallyChangedNotesJson); notesSyncCall.setParams(params); } catch (JSONException e) { logErrorMessage("Error generating sync remote RPC parameters.", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>(); jsonRpcCalls.add(notesSyncCall); if (deviceRegChange != 0) jsonRpcCalls.add(deviceRegCall); jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() { public void onData(Object[] data) { if (data[0] != null) { // Read notes sync data. JSONObject dataJson = (JSONObject) data[0]; try { List<ModelJava.Note> changedNotes = new ArrayList<ModelJava.Note>(); JSONArray notesJson = dataJson.getJSONArray(JumpNoteProtocol.NotesSync.RET_NOTES); for (int i = 0; i < notesJson.length(); i++) { changedNotes.add(new ModelJava.Note(notesJson.getJSONObject(i))); } reconcileSyncedNotes(provider, account, changedNotes, syncResult.stats); // If sync is successful (no exceptions thrown), update sync metadata long newServerSyncTime = Util .parseDateISO8601(dataJson.getString(JumpNoteProtocol.NotesSync.RET_NEW_SINCE_DATE)) .getTime(); syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit(); syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit(); Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime)); } catch (JSONException e) { logErrorMessage("Error parsing note sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (ParseException e) { logErrorMessage("Error parsing note sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (RemoteException e) { logErrorMessage("RemoteException in reconcileSyncedNotes: " + e.getMessage(), manualSync); e.printStackTrace(); return; } catch (OperationApplicationException e) { logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(), manualSync); e.printStackTrace(); return; } finally { provider.release(); } } // Read device reg data. if (deviceRegChange != 0) { // data[1] will be null in case of an error (successful unregisters // will have an empty JSONObject, not null). boolean registered = (data[1] != null && deviceRegChange == 1); syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered)); } } } public void onError(int callIndex, JsonRpcException e) { if (e.getHttpCode() == 403) { Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token"); jsonRpcClient.invalidateAccountAcsidToken(account); } provider.release(); logErrorMessage("Error calling remote note sync RPC", manualSync); e.printStackTrace(); } }); }
From source file:com.google.devrel.mobiledevicelab.spi.helper.DeviceLabApiHelper.java
/** * @param gcmId The registration id obtained from GCM service on the device * @param urlStr The url to push to the device * @param browserPackageName The package name for the browser to push the url * to on the device/*from w w w .j a v a 2 s.c o m*/ * @return null if success, or error message. Error message can be one of the * following: - as directly received from GCM server, - status code * received from GCm server if not 200 - one of the following * exceptions: JSONException, UnsupportedEncodingException, * MalformedURLException, and IOException */ private static String pushUrlToDevice(String gcmId, String urlStr, String browserPackageName) { try { JSONObject json = new JSONObject(); JSONArray array = new JSONArray().put(gcmId); json.put("registration_ids", array); JSONObject data = new JSONObject(); data.put("url", urlStr); data.put("pkg", browserPackageName); json.put("data", data); String jsonString = json.toString(); log.info("JSON payload: " + jsonString); com.google.appengine.api.urlfetch.HTTPResponse response; URL url; HTTPRequest httpRequest; String GCM_URL = "https://android.googleapis.com/gcm/send"; url = new URL(GCM_URL); httpRequest = new HTTPRequest(url, HTTPMethod.POST); httpRequest.addHeader(new HTTPHeader("Content-Type", "application/json")); log.info("ApiKey: " + Constants.API_KEY); httpRequest.addHeader(new HTTPHeader("Authorization", "key=" + Constants.API_KEY)); httpRequest.setPayload(jsonString.getBytes("UTF-8")); log.info("Sending POST request to: " + GCM_URL); response = URLFetchServiceFactory.getURLFetchService().fetch(httpRequest); String responseString = null; log.info("Status: " + response.getResponseCode()); if (response.getContent() != null) { responseString = new String(response.getContent(), "UTF-8"); log.info("Response " + responseString); } String GCMError = getGCMError(responseString); if (response.getResponseCode() == 200 && GCMError == null) { return null; } else if (response.getResponseCode() == 200 && GCMError != null) { return GCMError; } else { return "Status code: " + response.getResponseCode(); } } catch (JSONException e1) { log.info("JSONException" + e1.getMessage()); } catch (UnsupportedEncodingException e1) { log.info("UnsupportedEncodingException" + e1.getMessage()); } catch (MalformedURLException e1) { log.info("MalformedURLException" + e1.getMessage()); } catch (IOException e1) { log.info("IOException" + e1.getMessage()); } return "Exception thrown - see logs"; }
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 {/*w ww. ja v a2s. 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>> queryFileListWorker(String lang, String pageId, String cont) { Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("pageids", pageId); params.put("prop", "images"); if (cont != null) { params.put("imcontinue", cont); }//from ww w . j a v a2 s . c om 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("images")) { JSONArray images = pageRecord.getJSONArray("images"); for (int i = 0; i < images.length(); i++) { JSONObject image = images.getJSONObject(i); Map<String, Object> record = new HashMap<>(); record.put("title", image.getString("title")); result.add(record); } } String queryContinue = null; if (response.has("query-continue")) { queryContinue = response.getJSONObject("query-continue").getJSONObject("images") .getString("imcontinue"); } if (queryContinue != null) { List<Map<String, Object>> moreResult = queryFileListWorker(lang, pageId, queryContinue); result.addAll(moreResult); } } 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); } return result; }
From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java
private void queryFileInfo(String lang, String title, FileInfo file) { Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("titles", title); params.put("prop", "imageinfo"); params.put("iiprop", "size"); try {//from w w w . ja v a 2 s.co m String urlString = StringUtils.replace(Configure.METADATA.API_ENDPOINT, lang) + "?" + StringUtils.mapToURLParameters(params); URL url = new URL(urlString); JSONObject response = queryForJSONResponse(url); try { JSONObject pageMap = response.getJSONObject("query").getJSONObject("pages"); JSONObject pageRecord = pageMap.getJSONObject((String) pageMap.keys().next()); if (pageRecord.has("imageinfo")) { JSONArray fileInfoList = pageRecord.getJSONArray("imageinfo"); file.setSize(fileInfoList.getJSONObject(0).getLong("size")); } else { file.setSize(0L); } } 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:org.kaoriha.phonegap.plugins.licensing.LicenseVerificationPlugin.java
/** * Executes the request and returns PluginResult * // w w w .j a va 2s . c o m * @param action Action to execute * @param data JSONArray of arguments to the plugin * @param callbackId The callback id used when calling back into JavaScript * * @return A PluginRequest object with some result * */ @Override public PluginResult execute(String action, JSONArray data, String callbackId) { LicenseServiceConnection conn = new LicenseServiceConnection(ctx); PluginResult result; if (ACTION.equals(action)) { try { String nonce = data.getString(0); PLicenseQuery q = new PLicenseQuery(Integer.parseInt(nonce), callbackId); conn.offer(q); result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); } catch (JSONException e) { Log.w(TAG, "Got JSON Exception: " + e.getMessage()); result = new PluginResult(Status.JSON_EXCEPTION); } } else { Log.w(TAG, "Invalid action : " + action + " passed"); result = new PluginResult(Status.INVALID_ACTION); } Log.i(TAG, "execute OK"); return result; }
From source file:com.microsoft.graph.connect.ConnectActivity.java
@Override public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException authorizationException) { if (tokenResponse != null) { // get the UserInfo from the auth response JSONObject claims = AuthenticationManager.getInstance().getClaims(tokenResponse.idToken); String name = ""; String preferredUsername = ""; try {// w w w . j a v a2s . co m name = claims.getString("name"); preferredUsername = claims.getString("preferred_username"); } catch (JSONException je) { Log.e(TAG, je.getMessage()); } // start the SendMailActivity Intent sendMailActivity = new Intent(ConnectActivity.this, SendMailActivity.class); // take the user's info along sendMailActivity.putExtra(SendMailActivity.ARG_GIVEN_NAME, name); sendMailActivity.putExtra(SendMailActivity.ARG_DISPLAY_ID, preferredUsername); // actually start the Activity startActivity(sendMailActivity); resetUIForConnect(); } else if (authorizationException != null) { showConnectErrorUI(); } }
From source file:fi.helsinki.cs.iot.hub.IotHubHTTPDTest.java
@Test public void testPluginAPI() { //At this point, the list should be empty String res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET", "http://127.0.0.1:" + port + "/plugins/", null); assertEquals("[]", res.trim()); String pluginName = "MyPlugin"; //now I want to had a javascript plugin File pluginFile = makePluginFile(pluginName); JSONObject jsonObject = makeJsonObjectForPlugin(pluginName, null, Type.JAVASCRIPT, pluginFile, false); assertNotNull(jsonObject);//from w w w . ja va 2 s. c o m //First check the if I can had it with get res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET", "http://127.0.0.1:" + port + "/plugins/", jsonObject.toString()); assertEquals("[]", res.trim()); PluginInfo pluginInfo = new PluginInfo(1, Type.JAVASCRIPT, pluginName, null, null); res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST", "http://127.0.0.1:" + port + "/plugins/", jsonObject.toString()); try { assertEquals(pluginInfo.toJSON().toString(), res.trim()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(e.getMessage()); } assertEquals(1, IotHubDataAccess.getInstance().getPlugins().size()); //Now going to delete the plugininfo res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("DELETE", "http://127.0.0.1:" + port + "/plugins?id=1&type=enabler", null); try { assertEquals(pluginInfo.toJSON().toString(), res.trim()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(e.getMessage()); } assertEquals(0, IotHubDataAccess.getInstance().getPlugins().size()); }