List of usage examples for org.json JSONObject optString
public String optString(String key, String defaultValue)
From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeTest.java
@Test public void testMergeConflict() throws Exception { // clone a repo URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null); IPath clonePath = getClonePath(workspaceId, project); JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION); String branchesLocation = clone.getString(GitConstants.KEY_BRANCH); // get project metadata WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project = new JSONObject(response.getText()); JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT); assertNotNull(gitSection);//from ww w. ja v a2s. com String gitRemoteUri = gitSection.optString(GitConstants.KEY_REMOTE, null); assertNotNull(gitRemoteUri); // create branch 'a' branch(branchesLocation, "a"); // checkout 'a' Repository db1 = getRepositoryForContentLocation(cloneContentLocation); Git git = new Git(db1); assertBranchExist(git, "a"); checkoutBranch(cloneLocation, "a"); // modify while on 'a' JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "change in a"); gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); // "git add ." request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // commit all request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit on a", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // assert clean assertStatus(StatusResult.CLEAN, gitStatusUri); // checkout 'master' checkoutBranch(cloneLocation, Constants.MASTER); // modify the same file on master modifyFile(testTxt, "change in master"); gitSection = project.getJSONObject(GitConstants.KEY_GIT); gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); // "git add ." request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // commit all request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit on master", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // assert clean assertStatus(StatusResult.CLEAN, gitStatusUri); // merge: "git merge a" JSONObject merge = merge(gitHeadUri, "a"); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.CONFLICTING, mergeResult); // check status assertStatus(new StatusResult().setConflictingNames("test.txt"), gitStatusUri); request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); String[] responseLines = response.getText().split("\n"); assertEquals(5, responseLines.length); assertEquals("<<<<<<< HEAD", responseLines[0]); assertEquals("change in master", responseLines[1]); assertEquals("=======", responseLines[2]); assertEquals("change in a", responseLines[3]); // ignore the last line since it's different each time // assertEquals(">>>>>>> c5ddb0e22e7e829683bb3b336ca6cb24a1b5bb2e", responseLines[4]); // TODO: check commits, bug 340051 }
From source file:com.samsung.richnotification.RichNotificationHelper.java
public static List<SrnAction> createActions(Context mContext, CallbackContext callbackContext, RichNotificationOptions options) throws JSONException { ArrayList<SrnAction> actionsList = new ArrayList<SrnAction>(); JSONArray actions = options.actions; if (actions == null) return null; SrnAction action = null;// ww w . j a v a 2s . com for (int i = 0; i < actions.length(); i++) { JSONObject act = actions.optJSONObject(i); if (act == null) continue; String actionLabel = act.optString("actionLabel", EMPTY_STRING); if (actionLabel.isEmpty()) continue; Bitmap actionIcon = getIconBitmap(mContext, "file://" + act.optString("actionIcon")); SrnImageAsset actionImg = new SrnImageAsset(mContext, actionLabel, actionIcon); int actionType = act.optInt("type"); switch (actionType) { case ACTION_TYPE_CALL: SrnRemoteBuiltInAction call = new SrnRemoteBuiltInAction(actionLabel, OperationType.CALL); call.setData(Uri.parse(act.optString("dest"))); action = call; break; case ACTION_TYPE_SMS: SrnRemoteBuiltInAction sms = new SrnRemoteBuiltInAction(actionLabel, OperationType.SMS); sms.setData(Uri.fromParts("sms", act.optString("dest"), null)); action = sms; break; case ACTION_TYPE_EMAIL: Log.d(TAG, "Email to: '" + act.optString("dest") + "'"); Log.d(TAG, "Subject: '" + act.optString("subject") + "'"); Log.d(TAG, "Body: '" + act.optString("body") + "'"); SrnHostAction email = new SrnHostAction(actionLabel); Intent emailIntent = new Intent(Intent.ACTION_SENDTO); String uriText = "mailto:" + act.optString("dest") + "?subject=" + Uri.encode(act.optString("subject")) + "&body=" + Uri.encode(act.optString("body")); Uri uri = Uri.parse(uriText); emailIntent.setData(uri); email.setCallbackIntent(CallbackIntent.getActivityCallback(emailIntent)); email.setToast(act.optString("toast")); email.setIcon(actionImg); action = email; break; case ACTION_TYPE_VIEW: SrnHostAction view = new SrnHostAction(actionLabel); Intent viewIntent = new Intent(Intent.ACTION_VIEW); String urlText = act.optString("dest"); Uri url = Uri.parse(urlText); viewIntent.setData(url); view.setCallbackIntent(CallbackIntent.getActivityCallback(viewIntent)); view.setToast(act.optString("toast")); view.setIcon(actionImg); action = view; break; case ACTION_TYPE_INPUT_KEYBOARD: case ACTION_TYPE_INPUT_SINGLE_SELECT: case ACTION_TYPE_INPUT_MULTI_SELECT: SrnRemoteInputAction input = getRemoteInputAction(mContext, act); if (input == null) { continue; } Intent inputIntent = new Intent("com.samsung.cordova.richnotification.remote_input_receiver"); inputIntent.putExtra("callbackID", callbackContext.getCallbackId()); String actionID = act.optString("actionID", EMPTY_STRING); if (actionID.isEmpty()) { continue; } else { inputIntent.putExtra("actionID", actionID); } input.setCallbackIntent(CallbackIntent.getBroadcastCallback(inputIntent)); input.setIcon(actionImg); action = input; break; default: Log.e(TAG, "Invalid action type: " + actionType); continue; } Log.d(TAG, "Action type created: " + actionType); actionsList.add(action); } return actionsList; }
From source file:org.schedulesdirect.grabber.ScheduleTask.java
protected void fetchStations(Map<String, Collection<String>> ids) { if (ids == null || ids.size() == 0) { LOG.info("No stale schedules identified; skipping schedule download!"); return;//from w w w . jav a 2s. c o m } DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULES, clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl()); JSONArray data = new JSONArray(); Iterator<String> idItr = ids.keySet().iterator(); while (idItr.hasNext()) { String id = idItr.next(); JSONObject o = new JSONObject(); o.put("stationID", id); Collection<String> dates = new ArrayList<>(); for (String date : ids.get(id)) dates.add(date); o.put("date", dates); data.put(o); } try { JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONArray.class); for (int i = 0; i < resp.length(); ++i) { JSONObject o = resp.getJSONObject(i); if (!JsonResponseUtils.isErrorResponse(o)) { JSONArray sched = o.getJSONArray("programs"); String schedId = o.getString("stationID"); Date expiry = new Date(System.currentTimeMillis() - Grabber.MAX_AIRING_AGE); for (int j = 0; j < sched.length(); ++j) { try { JSONObject airing = sched.getJSONObject(j); Date end = AiringUtils.getEndDate(airing); String progId = airing.getString("programID"); if (!end.before(expiry)) { String md5 = airing.getString("md5"); cache.markIfDirty(progId, md5); } else LOG.debug(String.format("Expired airing discovered and ignored! [%s; %s; %s]", progId, o.getString("stationID"), end)); synchronized (ScheduleTask.class) { List<JSONObject> objs = FULL_SCHEDS.get(schedId); if (objs == null) { objs = new ArrayList<JSONObject>(); FULL_SCHEDS.put(schedId, objs); } objs.add(airing); } } catch (JSONException e) { LOG.warn(String.format("JSONException [%s]", o.optString("stationID", "unknown")), e); } } } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.SCHEDULE_QUEUED) LOG.warn(String.format( "StationID %s is queued server side and will be downloaded on next EPG update!", o.getString("stationID"))); else throw new InvalidJsonObjectException("Error received for schedule", o.toString(3)); } } catch (JSONException | JsonParseException e) { Grabber.failedTask = true; LOG.fatal("Fatal JSON error!", e); throw new RuntimeException(e); } catch (IOException e) { Grabber.failedTask = true; LOG.error("IOError receiving schedule data! Filling cache with empty schedules!", e); try { JSONArray schedIds = this.req; for (int i = 0; i < schedIds.length(); ++i) { String id = schedIds.getString(i); Path p = vfs.getPath("schedules", String.format("%s.txt", id)); if (!Files.exists(p)) { JSONObject emptySched = new JSONObject(); emptySched.put("stationID", id); emptySched.put("programs", new JSONArray()); Files.write(p, emptySched.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET)); } } } catch (Exception x) { LOG.error("Unexpected error!", x); throw new RuntimeException(x); } } }
From source file:com.marianhello.cordova.bgloc.Config.java
public static Config fromJSONArray(JSONArray data) throws JSONException { JSONObject jObject = data.getJSONObject(0); Config config = new Config(); config.setStationaryRadius((float) jObject.optDouble("stationaryRadius", config.getStationaryRadius())); config.setDistanceFilter(jObject.optInt("distanceFilter", config.getDistanceFilter())); config.setDesiredAccuracy(jObject.optInt("desiredAccuracy", config.getDesiredAccuracy())); config.setDebugging(jObject.optBoolean("debug", config.isDebugging())); config.setNotificationTitle(jObject.optString("notificationTitle", config.getNotificationTitle())); config.setNotificationText(jObject.optString("notificationText", config.getNotificationText())); config.setStopOnTerminate(jObject.optBoolean("stopOnTerminate", config.getStopOnTerminate())); config.setStartOnBoot(jObject.optBoolean("startOnBoot", config.getStartOnBoot())); config.setServiceProvider(jObject.optInt("locationService", config.getServiceProvider().asInt())); config.setInterval(jObject.optInt("interval", config.getInterval())); config.setFastestInterval(jObject.optInt("fastestInterval", config.getFastestInterval())); config.setActivitiesInterval(jObject.optInt("activitiesInterval", config.getActivitiesInterval())); config.setNotificationIconColor(//from w w w . ja v a 2 s . co m jObject.optString("notificationIconColor", config.getNotificationIconColor())); config.setLargeNotificationIcon( jObject.optString("notificationIconLarge", config.getLargeNotificationIcon())); config.setSmallNotificationIcon( jObject.optString("notificationIconSmall", config.getSmallNotificationIcon())); config.setStartForeground(jObject.optBoolean("startForeground", config.getStartForeground())); config.setUrl(jObject.optString("url", config.getUrl())); config.setMethod(jObject.optString("method", config.getMethod())); config.setHeaders(jObject.optJSONObject("headers")); config.setParams(jObject.optJSONObject("params")); return config; }
From source file:me.tassoevan.cordova.ForegroundService.java
@SuppressLint("NewApi") @SuppressWarnings("deprecation") private Notification makeNotification() { JSONObject settings = BackgroundPlugin.settings; Context context = getApplicationContext(); String pkgName = context.getPackageName(); Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName); Notification.Builder notification = new Notification.Builder(context) .setContentTitle(settings.optString("title", "")).setContentText(settings.optString("text", "")) .setTicker(settings.optString("ticker", "")).setOngoing(true).setSmallIcon(getIconResId()); if (intent != null && settings.optBoolean("resume")) { PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT); notification.setContentIntent(contentIntent); }/* www . j a v a 2 s . com*/ if (Build.VERSION.SDK_INT < 16) { return notification.getNotification(); } else { return notification.build(); } }
From source file:com.vk.sdkweb.api.model.VKApiUser.java
/** * Fills an user object from server response. */// w w w . ja v a 2 s . c o m public VKApiUser parse(JSONObject from) { super.parse(from); first_name = from.optString("first_name", first_name); last_name = from.optString("last_name", last_name); online = ParseUtils.parseBoolean(from, FIELD_ONLINE); online_mobile = ParseUtils.parseBoolean(from, FIELD_ONLINE_MOBILE); photo_50 = from.optString(FIELD_PHOTO_50, photo_50); if (!TextUtils.isEmpty(photo_50)) { photo.add(VKApiPhotoSize.create(photo_50, 50)); } photo_100 = from.optString(FIELD_PHOTO_100, photo_100); if (!TextUtils.isEmpty(photo_100)) { photo.add(VKApiPhotoSize.create(photo_100, 100)); } photo_200 = from.optString(FIELD_PHOTO_200, null); if (!TextUtils.isEmpty(photo_200)) { photo.add(VKApiPhotoSize.create(photo_200, 200)); } photo.sort(); return this; }
From source file:gov.sfmta.sfpark.MyAnnotation.java
public void rateStructureHandle(JSONObject rateObject) { // want null if fail not 'empty string' ? beg = rateObject.optString(BEG_STR, null); end = rateObject.optString(END_STR, null); rate = rateObject.optString(RATE_STR, null); rq = rateObject.optString(RQ_STR, null); }
From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;//from w w w . ja va 2 s . co m try { Double btcRate = 0.0; boolean cryptsyValue = true; Object result = getCoinValueBTC(); if (result == null) { result = getCoinValueBTC_BTER(); cryptsyValue = false; if (result == null) return null; } btcRate = (Double) result; connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); for (final String field : fields) { String rateStr = o.optString(field, null); if (rateStr != null) { try { double rateForBTC = Double.parseDouble(rateStr); rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", "."); final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, rate, url.getHost())); break; } } catch (final ArithmeticException x) { log.warn("problem fetching {} exchange rate from {}: {}", new Object[] { currencyCode, url, x.getMessage() }); } } } } } log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start)); //Add Bitcoin information if (rates.size() == 0) { int i = 0; i++; } else { rates.put(CoinDefinition.cryptsyMarketCurrency, new ExchangeRate(CoinDefinition.cryptsyMarketCurrency, GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0), cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com")); rates.put("m" + CoinDefinition.cryptsyMarketCurrency, new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency, GenericUtils.toNanoCoins( String.format("%.5f", btcRate * 1000).replace(",", "."), 0), cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com")); } return rates; } else { log.warn("http status {} when fetching {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.altcanvas.asocial.Twitter.java
public JSONObject verifyCreds() throws AsocialException { try {/* w w w .j a v a 2 s. c om*/ JSONObject json = new JSONObject(Http.get(twitterURL + "account/verify_credentials.json", headers)); // Authentication failed if (json.optString("error", null) != null) return null; return json; } catch (HttpException he) { throw new AsocialException(he.responseCode, he.toString()); } catch (JSONException je) { throw new AsocialException(AsocialException.JSONE, je.toString()); } catch (IOException ioe) { throw new AsocialException(AsocialException.IOE, ioe.toString()); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitResetTest.java
@Test @Ignore("see bug 339397") public void testResetAutocrlfTrue() throws Exception { // "git config core.autocrlf true" Git git = new Git(db); StoredConfig config = git.getRepository().getConfig(); config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, Boolean.TRUE);//from ww w.java 2s. c om config.save(); URI workspaceLocation = createWorkspace(getMethodName()); String projectName = getMethodName(); JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString()); String projectId = project.getString(ProtocolConstants.KEY_ID); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT); // CRLF JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "f" + "\r\n" + "older"); addFile(testTxt); // commit WebRequest request = GitCommitTest.getPostGitCommitRequest(gitCommitUri, "added new line - crlf", false); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // assert there is nothing to commit assertStatus(StatusResult.CLEAN, gitStatusUri); // create new file String fileName = "new.txt"; // TODO: don't create URIs out of thin air request = getPostFilesRequest(projectId + "/", getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject file = new JSONObject(response.getText()); String location = file.optString(ProtocolConstants.KEY_LOCATION, null); assertNotNull(location); // LF JSONObject newTxt = getChild(project, "new.txt"); modifyFile(newTxt, "i'm" + "\n" + "new"); // "git add ." request = GitAddTest.getPutGitIndexRequest(gitIndexUri /* stage all */); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // reset request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.MIXED); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertStatus(new StatusResult().setUntracked(1), gitStatusUri); }