List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:com.cubusmail.user.UserAccountDao.java
/** * @param preferencesJson//w ww . j av a 2 s.c o m * @param preferences */ private void json2Preferences(String preferencesJson, Preferences preferences) { try { JSONObject object = new JSONObject(preferencesJson); Field[] fields = Preferences.class.getFields(); if (fields != null) { for (Field field : fields) { Object value = object.has(field.getName()) ? object.get(field.getName()) : null; if (value != null) { if (value instanceof Integer) { field.setInt(preferences, ((Integer) value).intValue()); } else if (value instanceof Boolean) { field.setBoolean(preferences, ((Boolean) value).booleanValue()); } else if (value instanceof String) { field.set(preferences, value); } } } } } catch (JSONException e) { logger.error(e.getMessage(), e); } catch (NumberFormatException e) { logger.error(e.getMessage(), e); } catch (IllegalArgumentException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } }
From source file:com.basetechnology.s0.agentserver.field.HelpField.java
public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) { String type = fieldJson.optString("type"); if (type == null || !type.equals("string")) return null; String name = fieldJson.has("name") ? fieldJson.optString("name") : null; String help = fieldJson.has("help") ? fieldJson.optString("help") : null; return new HelpField(symbolTable, name, help); }
From source file:com.acrutiapps.browser.tasks.HistoryBookmarksImportTask.java
private String readAsJSON(File file) { List<ContentValues> insertValues = null; try {// w w w . j a va2 s .co m insertValues = new ArrayList<ContentValues>(); publishProgress(1, 0, 0); FileInputStream fis = new FileInputStream(file); StringBuilder sb = new StringBuilder(); String line; BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(fis, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); return e.getMessage(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } } JSONObject data = new JSONObject(sb.toString()); Map<Long, Folder> folders = new HashMap<Long, Folder>(); if (data.has("folders")) { JSONArray foldersArray = data.getJSONArray("folders"); int progress = 0; int total = foldersArray.length(); for (int i = 0; i < foldersArray.length(); i++) { publishProgress(3, progress, total); JSONObject folder = foldersArray.getJSONObject(i); long id = folder.getLong("id"); long parentId = folder.getLong("parentId"); String title = URLDecoder.decode(folder.getString("title"), "UTF-8"); ContentValues values = new ContentValues(); values.put(BookmarksProvider.Columns.TITLE, title); values.put(BookmarksProvider.Columns.BOOKMARK, 0); values.put(BookmarksProvider.Columns.IS_FOLDER, 1); values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, -1); Uri insertionUri = mContext.getContentResolver().insert(BookmarksProvider.BOOKMARKS_URI, values); String insertionString = insertionUri.toString(); // Get the new id for the current folder. long insertionId = -1; try { insertionId = Long .parseLong(insertionString.substring(insertionString.lastIndexOf('/') + 1)); } catch (NumberFormatException e) { insertionId = -1; } // Keep a relation between the id of the folder in the export file, its parent id (in the export file), and its new id. folders.put(id, new Folder(insertionId, parentId)); progress++; } publishProgress(4, 0, 0); // Correct folders parent ids. if (!folders.isEmpty()) { for (Folder folder : folders.values()) { // For each folder previously inserted, check if it had a parent folder in the export file. long oldParentId = folder.getOldParentId(); if (oldParentId != -1) { // Get the parent folder by its old Id, key of folders map. Folder parentFolder = folders.get(oldParentId); if (parentFolder != null) { ContentValues values = new ContentValues(); values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId()); String whereClause = BookmarksProvider.Columns._ID + " = " + folder.getNewId(); mContext.getContentResolver().update(BookmarksProvider.BOOKMARKS_URI, values, whereClause, null); } } } } } if (data.has("bookmarks")) { JSONArray bookmarksArray = data.getJSONArray("bookmarks"); int progress = 0; int total = bookmarksArray.length(); for (int i = 0; i < bookmarksArray.length(); i++) { publishProgress(5, progress, total); JSONObject bookmark = bookmarksArray.getJSONObject(i); long folderId = bookmark.getLong("folderId"); Folder parentFolder = null; if (folderId != -1) { parentFolder = folders.get(folderId); } String title = URLDecoder.decode(bookmark.getString("title"), "UTF-8"); String url = URLDecoder.decode(bookmark.getString("url"), "UTF-8"); ContentValues values = createContentValues(title, url, bookmark.getInt("visits"), bookmark.getLong("visitedDate"), bookmark.getLong("creationDate"), 1); if (parentFolder != null) { values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId()); } insertValues.add(values); progress++; } } if (data.has("history")) { JSONArray historyArray = data.getJSONArray("history"); int progress = 0; int total = historyArray.length(); for (int i = 0; i < historyArray.length(); i++) { publishProgress(6, progress, total); JSONObject history = historyArray.getJSONObject(i); String title = URLDecoder.decode(history.getString("title"), "UTF-8"); String url = URLDecoder.decode(history.getString("url"), "UTF-8"); ContentValues values = createContentValues(title, url, history.getInt("visits"), history.getLong("visitedDate"), 0, 0); insertValues.add(values); progress++; } } } catch (FileNotFoundException e) { e.printStackTrace(); return e.getMessage(); } catch (JSONException e) { e.printStackTrace(); return e.getMessage(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return e.getMessage(); } if (insertValues != null) { publishProgress(7, 0, 0); mContext.getContentResolver().bulkInsert(BookmarksProvider.BOOKMARKS_URI, insertValues.toArray(new ContentValues[insertValues.size()])); } return null; }
From source file:net.majorkernelpanic.spydroid.api.RequestHandler.java
/** * The implementation of all the possible requests is here * -> "sounds": returns a list of available sounds on the phone * -> "screen": returns the screen state (whether the app. is on the foreground or not) * -> "play": plays a sound on the phone * -> "set": update Spydroid's configuration * -> "get": returns Spydroid's configuration (framerate, bitrate...) * -> "state": returns a JSON containing information about the state of the application * -> "battery": returns an approximation of the battery level on the phone * -> "buzz": makes the phone buuz //from w ww .ja va 2 s .co m * -> "volume": sets or gets the volume * @throws JSONException * @throws IllegalAccessException * @throws IllegalArgumentException **/ static private void exec(JSONObject object, StringBuilder response) throws JSONException, IllegalArgumentException, IllegalAccessException { SpydroidApplication application = SpydroidApplication.getInstance(); Context context = application.getApplicationContext(); String action = object.getString("action"); // Returns a list of available sounds on the phone if (action.equals("sounds")) { Field[] raws = R.raw.class.getFields(); response.append("["); for (int i = 0; i < raws.length - 1; i++) { response.append("\"" + raws[i].getName() + "\","); } response.append("\"" + raws[raws.length - 1].getName() + "\"]"); } // Returns the screen state (whether the app. is on the foreground or not) else if (action.equals("screen")) { response.append(application.applicationForeground ? "\"1\"" : "\"0\""); } // Plays a sound on the phone else if (action.equals("play")) { Field[] raws = R.raw.class.getFields(); for (int i = 0; i < raws.length; i++) { if (raws[i].getName().equals(object.getString("name"))) { mSoundPool.load(application, raws[i].getInt(null), 0); } } response.append("[]"); } // Returns Spydroid's configuration (framerate, bitrate...) else if (action.equals("get")) { final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); response.append("{\"streamAudio\":" + settings.getBoolean("stream_audio", false) + ","); response.append("\"audioEncoder\":\"" + (application.audioEncoder == SessionBuilder.AUDIO_AMRNB ? "AMR-NB" : "AAC") + "\","); response.append("\"streamVideo\":" + settings.getBoolean("stream_video", true) + ","); response.append("\"videoEncoder\":\"" + (application.videoEncoder == SessionBuilder.VIDEO_H263 ? "H.263" : "H.264") + "\","); response.append("\"videoResolution\":\"" + application.videoQuality.resX + "x" + application.videoQuality.resY + "\","); response.append("\"videoFramerate\":\"" + application.videoQuality.framerate + " fps\","); response.append("\"videoBitrate\":\"" + application.videoQuality.bitrate / 1000 + " kbps\"}"); } // Update Spydroid's configuration else if (action.equals("set")) { final JSONObject settings = object.getJSONObject("settings"); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final Editor editor = prefs.edit(); editor.putBoolean("stream_video", settings.getBoolean("stream_video")); application.videoQuality = VideoQuality.parseQuality(settings.getString("video_quality")); editor.putInt("video_resX", application.videoQuality.resX); editor.putInt("video_resY", application.videoQuality.resY); editor.putString("video_framerate", String.valueOf(application.videoQuality.framerate)); editor.putString("video_bitrate", String.valueOf(application.videoQuality.bitrate / 1000)); editor.putString("video_encoder", settings.getString("video_encoder").equals("H.263") ? "2" : "1"); editor.putBoolean("stream_audio", settings.getBoolean("stream_audio")); editor.putString("audio_encoder", settings.getString("audio_encoder").equals("AMR-NB") ? "3" : "5"); editor.commit(); response.append("[]"); } // Returns a JSON containing information about the state of the application else if (action.equals("state")) { Exception exception = application.lastCaughtException; response.append("{"); if (exception != null) { // Used to display the message on the user interface String lastError = exception.getMessage(); // Useful to display additional information to the user depending on the error StackTraceElement[] stack = exception.getStackTrace(); StringBuilder builder = new StringBuilder( exception.getClass().getName() + " : " + lastError + "||"); for (int i = 0; i < stack.length; i++) builder.append("at " + stack[i].getClassName() + "." + stack[i].getMethodName() + " (" + stack[i].getFileName() + ":" + stack[i].getLineNumber() + ")||"); response.append("\"lastError\":\"" + (lastError != null ? lastError : "unknown error") + "\","); response.append("\"lastStackTrace\":\"" + builder.toString() + "\","); } response.append("\"activityPaused\":\"" + (application.applicationForeground ? "1" : "0") + "\""); response.append("}"); } else if (action.equals("clear")) { application.lastCaughtException = null; response.append("[]"); } // Returns an approximation of the battery level else if (action.equals("battery")) { response.append("\"" + application.batteryLevel + "\""); } // Makes the phone vibrates for 300ms else if (action.equals("buzz")) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(300); response.append("[]"); } // Sets or gets the system's volume else if (action.equals("volume")) { AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (object.has("set")) { audio.setStreamVolume(AudioManager.STREAM_MUSIC, object.getInt("set"), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); response.append("[]"); } else { int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC); int current = audio.getStreamVolume(AudioManager.STREAM_MUSIC); response.append("{\"max\":" + max + ",\"current\":" + current + "}"); } } }
From source file:io.selendroid.server.SelendroidSatusHandlerTest.java
public void assertThatGetStatusHandlerIsRegistered() throws Exception { HttpResponse response = HttpClientUtil.executeRequest(URL, HttpMethod.GET); SelendroidAssert.assertResponseIsOk(response); JSONObject result = HttpClientUtil.parseJsonResponse(response); SelendroidAssert.assertResponseIsOk(response); Assert.assertFalse(result.has("sessionId")); JSONObject value = result.getJSONObject("value"); Assert.assertEquals("dev", value.getJSONObject("build").getString("version")); }
From source file:org.apache.cordova.plugins.DownloadManager.DownloadManager.java
@Override public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) { if (action.equals("start")) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { /* Get OPTIONS */ JSONObject params = args.getJSONObject(0); String fileUrl = params.getString("url"); Boolean overwrite = params.getBoolean("overwrite"); String fileName = params.has("fileName") ? params.getString("fileName") : fileUrl.substring(fileUrl.lastIndexOf("/") + 1); String filePath = params.has("filePath") ? params.getString("filePath") : cordova.getActivity() .getString(cordova.getActivity().getResources().getIdentifier("app_name", "string", cordova.getActivity().getPackageName())); String startToast = params.has("startToast") ? params.getString("startToast") : "Download Start!"; String ticker = params.has("ticker") ? params.getString("ticker") : "Downloading..."; String endToast = params.has("endToast") ? params.getString("endToast") : "Download Complete!"; String cancelToast = params.has("cancelToast") ? params.getString("cancelToast") : "Download canceled!"; Boolean useNotificationBar = params.has("useNotificationBar") ? params.getBoolean("useNotificationBar") : true;/*from ww w . j a v a 2s .com*/ String notificationTitle = params.has("notificationTitle") ? params.getString("notificationTitle") : "Downloading: " + fileName; String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/" + filePath + "/"; // Get an ID: int downloader_id = new Random().nextInt(10000); String downloader_id_str = String.valueOf(downloader_id); // Instantiate Downloader with the ID: Downloader downloadFile = new Downloader(downloader_id_str, fileUrl, dirName, fileName, overwrite, startToast, ticker, notificationTitle, endToast, cancelToast, useNotificationBar, callbackContext, cordova, webView); // Store ID: ATT! GLobal Here! //DownloadControllerGlobals.ids.add(downloader_id_str); downloading_ids.add(downloader_id_str); // Start Download downloadFile.run(); } catch (JSONException e) { e.printStackTrace(); Log.e("PhoneGapLog", "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } catch (InterruptedException e) { e.printStackTrace(); Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); } } }); return true; } else if (action.equals("cancel")) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONObject params = args.getJSONObject(0); String cancelID = params.has("id") ? params.getString("id") : null; Log.d("PhoneGapLog", "Este es el ID que me llega para cancelar: " + cancelID); if (cancelID == null) { callbackContext .sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "ID not found")); } //if (DownloadControllerGlobals.ids.indexOf(cancelID) == -1) { if (!downloading_ids.isId(cancelID)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "The id has no download associated")); } else { //DownloadControllerGlobals.ids.remove(DownloadControllerGlobals.ids.indexOf(cancelID)); downloading_ids.del(cancelID); } } catch (JSONException e) { e.printStackTrace(); Log.e("PhoneGapLog", "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } } }); return true; } else if (action.equals("isdownloading")) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONObject params = args.getJSONObject(0); String cancelID = params.has("id") ? params.getString("id") : null; Log.d("PhoneGapLog", "Este es el ID que me llega para cancelar: " + cancelID); if (cancelID == null) { callbackContext.sendPluginResult( new PluginResult(PluginResult.Status.ERROR, "Error checking id")); } if (!downloading_ids.isId(cancelID)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, false)); } else { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true)); } } catch (JSONException e) { e.printStackTrace(); Log.e("PhoneGapLog", "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } } }); return true; } else { Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } }
From source file:io.teak.sdk.Session.java
private void identifyUser() { final Session _this = this; new Thread(new Runnable() { public void run() { synchronized (_this.stateMutex) { HashMap<String, Object> payload = new HashMap<>(); if (_this.state == State.UserIdentified) { payload.put("do_not_track_event", Boolean.TRUE); }/*from w w w. j a va 2 s.co m*/ TimeZone tz = TimeZone.getDefault(); long rawTz = tz.getRawOffset(); if (tz.inDaylightTime(new Date())) { rawTz += tz.getDSTSavings(); } long minutes = TimeUnit.MINUTES.convert(rawTz, TimeUnit.MILLISECONDS); String tzOffset = new DecimalFormat("#0.00").format(minutes / 60.0f); payload.put("timezone", tzOffset); String locale = Locale.getDefault().toString(); payload.put("locale", locale); if (_this.deviceConfiguration.advertsingInfo != null) { payload.put("android_ad_id", _this.deviceConfiguration.advertsingInfo.getId()); payload.put("android_limit_ad_tracking", _this.deviceConfiguration.advertsingInfo.isLimitAdTrackingEnabled()); } if (_this.facebookAccessToken != null) { payload.put("access_token", _this.facebookAccessToken); } if (_this.launchedFromTeakNotifId != null) { payload.put("teak_notif_id", Long.valueOf(_this.launchedFromTeakNotifId)); } if (_this.launchedFromDeepLink != null) { payload.put("deep_link", _this.launchedFromDeepLink); } if (_this.deviceConfiguration.gcmId != null) { payload.put("gcm_push_key", _this.deviceConfiguration.gcmId); } else { payload.put("gcm_push_key", ""); } Log.d(LOG_TAG, "Identifying user: " + _this.userId); Log.d(LOG_TAG, " Timezone: " + tzOffset); Log.d(LOG_TAG, " Locale: " + locale); new Request("/games/" + _this.appConfiguration.appId + "/users.json", payload, _this) { @Override protected void done(int responseCode, String responseBody) { try { JSONObject response = new JSONObject(responseBody); // TODO: Grab 'id' and 'game_id' from response and store for Parsnip // Enable verbose logging if flagged boolean enableVerboseLogging = response.optBoolean("verbose_logging"); if (Teak.debugConfiguration != null) { Teak.debugConfiguration.setPreferenceForceDebug(enableVerboseLogging); } // Server requesting new push key. if (response.optBoolean("reset_push_key", false)) { _this.deviceConfiguration.reRegisterPushToken(_this.appConfiguration); } if (response.has("country_code")) { _this.countryCode = response.getString("country_code"); } // Prevent warning for 'do_not_track_event' if (_this.state != State.UserIdentified) { _this.setState(State.UserIdentified); } } catch (Exception ignored) { } super.done(responseCode, responseBody); } }.run(); } } }).start(); }
From source file:net.dv8tion.jda.core.handle.UserUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { SelfUserImpl self = (SelfUserImpl) api.getSelfUser(); String name = content.getString("username"); String discriminator = content.getString("discriminator"); String avatarId = !content.isNull("avatar") ? content.getString("avatar") : null; Boolean verified = content.has("verified") ? content.getBoolean("verified") : null; Boolean mfaEnabled = content.has("mfa_enabled") ? content.getBoolean("mfa_enabled") : null; //Client only String email = !content.isNull("email") ? content.getString("email") : null; if (!Objects.equals(name, self.getName()) || !Objects.equals(discriminator, self.getDiscriminator())) { String oldName = self.getName(); String oldDiscriminator = self.getDiscriminator(); self.setName(name);//from w w w .j a v a 2 s . c o m self.setDiscriminator(discriminator); api.getEventManager().handle(new SelfUpdateNameEvent(api, responseNumber, oldName, oldDiscriminator)); } if (!Objects.equals(avatarId, self.getAvatarId())) { String oldAvatarId = self.getAvatarId(); self.setAvatarId(avatarId); api.getEventManager().handle(new SelfUpdateAvatarEvent(api, responseNumber, oldAvatarId)); } if (verified != null && verified != self.isVerified()) { boolean wasVerified = self.isVerified(); self.setVerified(verified); api.getEventManager().handle(new SelfUpdateVerifiedEvent(api, responseNumber, wasVerified)); } if (mfaEnabled != null && mfaEnabled != self.isMfaEnabled()) { boolean wasMfaEnabled = self.isMfaEnabled(); self.setMfaEnabled(mfaEnabled); api.getEventManager().handle(new SelfUpdateMFAEvent(api, responseNumber, wasMfaEnabled)); } if (api.getAccountType() == AccountType.CLIENT && !Objects.equals(email, self.getEmail())) { String oldEmail = self.getEmail(); self.setEmail(email); api.getEventManager().handle(new SelfUpdateEmailEvent(api, responseNumber, oldEmail)); } return null; }
From source file:com.atolcd.alfresco.AuditFilter.java
/** * @param request/*from w ww. ja v a 2s . c om*/ * @param userId * @param siteId * @param componentId * @param objectId * @return * @throws JSONException * @throws URIException * @throws UnsupportedEncodingException */ private String getNodeRefRemoteCall(HttpServletRequest request, String userId, String siteId, String componentId, String objectId) throws JSONException, URIException, UnsupportedEncodingException { Connector connector; try { connector = FrameworkUtil.getConnector(request.getSession(true), userId, AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID); // <url>/share-stats/slingshot/details/{siteId}/{componentId}/{objectId}</url> Response resp = connector.call("/share-stats/slingshot/details/" + siteId + "/" + componentId + "/" + URLEncoder.encode(objectId, "UTF-8")); if (resp.getStatus().getCode() == Status.STATUS_OK) { try { JSONObject json = new JSONObject(resp.getResponse()); if (json.has("nodeRef")) { return (String) json.get("nodeRef"); } } catch (JSONException e) { if (logger.isDebugEnabled()) { logger.debug(e.getMessage(), e); } } } } catch (ConnectorServiceException e) { if (logger.isDebugEnabled()) { logger.debug(e.getMessage(), e); } } return objectId; }
From source file:com.googlecode.goclipse.tooling.oracle.JSONParseHelpers.java
public static String readOptionalString(JSONObject jsonObject, String key) throws JSONException, CommonException { if (!jsonObject.has(key)) { return null; }/*from w w w. j av a 2 s.c o m*/ return readString(jsonObject, key); }