List of usage examples for org.json JSONObject optString
public String optString(String key, String defaultValue)
From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java
/** * This method is called when the JavaScript sends a message to the native side. * This method should be overridden in subclasses. * @param message : the JSON-message sent by JavaScript. * @return true if the message was handled by the native, false otherwise * @details some basic operations are already implemented : navigation, logs, toasts, native alerts, web alerts * @details this method may be called from a secondary thread. */// www .ja v a 2 s . c o m // This method must be public !!! @JavascriptInterface public boolean onCobaltMessage(String message) { try { final JSONObject jsonObj = new JSONObject(message); // TYPE if (jsonObj.has(Cobalt.kJSType)) { String type = jsonObj.getString(Cobalt.kJSType); //CALLBACK if (type.equals(Cobalt.JSTypeCallBack)) { String callbackID = jsonObj.getString(Cobalt.kJSCallback); JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData); return handleCallback(callbackID, data); } // COBALT IS READY else if (type.equals(Cobalt.JSTypeCobaltIsReady)) { String versionWeb = jsonObj.optString(Cobalt.kJSVersion, null); String versionNative = getResources().getString(R.string.version_name); if (versionWeb != null && !versionWeb.equals(versionNative)) Log.e(TAG, "Warning : Cobalt version mismatch : Android Cobalt version is " + versionNative + " but Web Cobalt version is " + versionWeb + ". You should fix this. "); onCobaltIsReady(); return true; } // EVENT else if (type.equals(Cobalt.JSTypeEvent)) { String event = jsonObj.getString(Cobalt.kJSEvent); JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData); String callback = jsonObj.optString(Cobalt.kJSCallback, null); return handleEvent(event, data, callback); } // INTENT else if (type.equals(Cobalt.JSTypeIntent)) { String action = jsonObj.getString(Cobalt.kJSAction); // OPEN EXTERNAL URL if (action.equals(Cobalt.JSActionIntentOpenExternalUrl)) { JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData); String url = data.getString(Cobalt.kJSUrl); openExternalUrl(url); return true; } // UNHANDLED INTENT else { onUnhandledMessage(jsonObj); } } // LOG else if (type.equals(Cobalt.JSTypeLog)) { String text = jsonObj.getString(Cobalt.kJSValue); Log.d(Cobalt.TAG, "JS LOG: " + text); return true; } // NAVIGATION else if (type.equals(Cobalt.JSTypeNavigation)) { String action = jsonObj.getString(Cobalt.kJSAction); // PUSH if (action.equals(Cobalt.JSActionNavigationPush)) { JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData); String page = data.getString(Cobalt.kJSPage); String controller = data.optString(Cobalt.kJSController, null); push(controller, page); return true; } // POP else if (action.equals(Cobalt.JSActionNavigationPop)) { JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData); if (data != null) { String page = data.getString(Cobalt.kJSPage); String controller = data.optString(Cobalt.kJSController, null); pop(controller, page); } else pop(); return true; } // MODAL else if (action.equals(Cobalt.JSActionNavigationModal)) { JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData); String page = data.getString(Cobalt.kJSPage); String controller = data.optString(Cobalt.kJSController, null); String callbackId = jsonObj.optString(Cobalt.kJSCallback, null); presentModal(controller, page, callbackId); return true; } // DISMISS else if (action.equals(Cobalt.JSActionNavigationDismiss)) { // TODO: not present in iOS JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData); String controller = data.getString(Cobalt.kJSController); String page = data.getString(Cobalt.kJSPage); dismissModal(controller, page); return true; } //REPLACE else if (action.equals(Cobalt.JSActionNavigationReplace)) { JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData); String controller = data.getString(Cobalt.kJSController); String page = data.getString(Cobalt.kJSPage); boolean animated = data.optBoolean(Cobalt.kJSAnimated); replace(controller, page, animated); return true; } // UNHANDLED NAVIGATION else { onUnhandledMessage(jsonObj); } } // PLUGIN else if (type.equals(Cobalt.JSTypePlugin)) { mPluginManager.onMessage(mContext, this, jsonObj); } // UI else if (type.equals(Cobalt.JSTypeUI)) { String control = jsonObj.getString(Cobalt.kJSUIControl); JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData); String callback = jsonObj.optString(Cobalt.kJSCallback, null); return handleUi(control, data, callback); } // WEB LAYER else if (type.equals(Cobalt.JSTypeWebLayer)) { String action = jsonObj.getString(Cobalt.kJSAction); // SHOW if (action.equals(Cobalt.JSActionWebLayerShow)) { final JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData); mHandler.post(new Runnable() { @Override public void run() { showWebLayer(data); } }); return true; } // UNHANDLED WEB LAYER else { onUnhandledMessage(jsonObj); } } // UNHANDLED TYPE else { onUnhandledMessage(jsonObj); } } // UNHANDLED MESSAGE else { onUnhandledMessage(jsonObj); } } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: JSONException"); exception.printStackTrace(); } catch (NullPointerException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: NullPointerException"); exception.printStackTrace(); } return false; }
From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java
private boolean handleUi(String control, JSONObject data, String callback) { try {/* w w w . j av a 2 s . c o m*/ // PICKER switch (control) { case Cobalt.JSControlPicker: String type = data.getString(Cobalt.kJSType); // DATE if (type.equals(Cobalt.JSPickerDate)) { JSONObject date = data.optJSONObject(Cobalt.kJSDate); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); if (date != null && date.has(Cobalt.kJSYear) && date.has(Cobalt.kJSMonth) && date.has(Cobalt.kJSDay)) { year = date.getInt(Cobalt.kJSYear); month = date.getInt(Cobalt.kJSMonth) - 1; day = date.getInt(Cobalt.kJSDay); } JSONObject texts = data.optJSONObject(Cobalt.kJSTexts); String title = texts.optString(Cobalt.kJSTitle, null); //String delete = texts.optString(Cobalt.kJSDelete, null); String clear = texts.optString(Cobalt.kJSClear, null); String cancel = texts.optString(Cobalt.kJSCancel, null); String validate = texts.optString(Cobalt.kJSValidate, null); showDatePickerDialog(year, month, day, title, clear, cancel, validate, callback); return true; } break; case Cobalt.JSControlAlert: showAlertDialog(data, callback); return true; case Cobalt.JSControlToast: String message = data.getString(Cobalt.kJSMessage); Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show(); return true; default: break; } } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException"); exception.printStackTrace(); } // UNHANDLED UI try { JSONObject jsonObj = new JSONObject(); jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeUI); jsonObj.put(Cobalt.kJSUIControl, control); jsonObj.put(Cobalt.kJSData, data); jsonObj.put(Cobalt.kJSCallback, callback); onUnhandledMessage(jsonObj); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException"); exception.printStackTrace(); } return false; }
From source file:de.schildbach.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String source, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;/*from www . ja va 2 s .c om*/ try { 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.addRequestProperty("Accept-Encoding", "gzip"); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { final String contentEncoding = connection.getContentEncoding(); InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); if ("gzip".equalsIgnoreCase(contentEncoding)) is = new GZIPInputStream(is); reader = new InputStreamReader(is, Charsets.UTF_8); final StringBuilder content = new StringBuilder(); final long length = 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) { final String rateStr = o.optString(field, null); if (rateStr != null) { try { final Fiat rate = Fiat.parseFiat(currencyCode, rateStr); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate( new org.bitcoinj.utils.ExchangeRate(rate), source)); break; } } catch (final NumberFormatException x) { log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode, url, contentEncoding, x.getMessage()); } } } } } log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length, System.currentTimeMillis() - start); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", 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.aniruddhc.acemusic.player.GMusicHelpers.WebClientPlaylistsSchema.java
@Override public WebClientPlaylistsSchema fromJsonObject(JSONObject jsonObject) { if (jsonObject != null) { mTitle = jsonObject.optString("title", null); mPlaylistId = jsonObject.optString("playlistId", null); mRequestTime = jsonObject.optLong("requestTime"); mContinuationToken = jsonObject.optString("continuationToken", null); mDifferentialUpdate = jsonObject.optBoolean("differentialUpdate"); mContinuation = jsonObject.optBoolean("continuation"); JSONArray songsArray = jsonObject.optJSONArray("playlist"); mPlaylist = fromJsonArray(songsArray); }/*w w w . jav a 2 s.com*/ //This method returns itself to support chaining. return this; }
From source file:com.google.blockly.model.FieldNumber.java
public static FieldNumber fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name", null); if (name == null) { throw new BlockLoadingException("Number fields must have name field."); }/* ww w . j a v a2 s. co m*/ FieldNumber field = new FieldNumber(name); if (json.has("value")) { try { field.setValue(json.getDouble("value")); } catch (JSONException e) { throw new BlockLoadingException( "Cannot parse field_number value: " + json.optString("value", "[object or array]")); } } try { field.setConstraints(json.optDouble("min", NO_CONSTRAINT), json.optDouble("max", NO_CONSTRAINT), json.optDouble("precision", NO_CONSTRAINT)); } catch (IllegalArgumentException e) { throw new BlockLoadingException(e); } return field; }
From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java
/** * Sends the registration request, receives the request and parses the response back *///from w ww.j av a2 s. c o m public void authorizeDevice(DeviceInfo device, String email, String password, boolean bFailover) throws LibException { String host = mHost; { SharedPreferences preferenceSettings = PreferenceKeys.getSecurePreferences(mContext); preferenceSettings.edit().putString(PreferenceKeys.User.USER_EMAIL, email).commit(); preferenceSettings.edit().putString(PreferenceKeys.Miscellaneous.KEY_GCM_REG_ID, "").commit(); try { HttpURLConnection connection = RegistrationRequest.POSTConnection(host, device, email, password, true); //verifyResponse throws an MMCException if (verifyConnectionResponse(connection)) { String contents = readString(connection); //getResponseString(response); JSONObject json = new JSONObject(contents); mApiKey = json.optString(JSON_API_KEY, ""); int dormant = json.optInt("dormant", 0); int userID = json.optInt(USER_ID_KEY, 0); if (mApiKey.length() > 0) { //SharedPreferences preferenceSettings = PreferenceManager.getDefaultSharedPreferences(mContext); preferenceSettings.edit().putString(PreferenceKeys.User.APIKEY, mApiKey).commit(); // Also save email for this version so it can be copied to the contact email setting for email raw data preferenceSettings.edit().putString(PreferenceKeys.User.USER_EMAIL, email).commit(); preferenceSettings.edit().putString(PreferenceKeys.User.CONTACT_EMAIL, email).commit(); PreferenceManager.getDefaultSharedPreferences(mContext).edit() .putString(PreferenceKeys.User.CONTACT_EMAIL, email).commit(); preferenceSettings.edit().putBoolean(PreferenceKeys.Miscellaneous.SIGNED_OUT, false) .commit(); PreferenceManager.getDefaultSharedPreferences(mContext).edit() .putInt(PreferenceKeys.Miscellaneous.USAGE_DORMANT_MODE, (int) dormant).commit(); } else { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice", "api key is empty"); throw new LibException("api key was empty"); } if (userID > 0) { preferenceSettings.edit().putInt(PreferenceKeys.User.USER_ID, userID).commit(); LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "authorizeDevice", "userID=" + userID); } else { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice", "user id is empty"); } } } catch (IOException e) { //Just log the exception for now LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice", "fail to send authorization", e); // if (bFailover) // AuthorizeWindows (email); throw new LibException(e); } catch (JSONException e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice", "fail to recieve authorization", e); // if (bFailover) // AuthorizeWindows (email); throw new LibException(e); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice", "fail to recieve authorization", e); // if (bFailover) // AuthorizeWindows (email); throw new LibException(e); } } }
From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java
protected static boolean verifyConnectionResponse(HttpURLConnection connection) throws LibException { int responseCode = 0; try {// ww w. ja v a2 s . c om responseCode = connection.getResponseCode(); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "verifyConnectionResponse", "getResponseCode", e); throw new LibException(e); } String contents = ""; if (responseCode < HttpURLConnection.HTTP_OK || responseCode >= 400) { try { contents = readString(connection); LoggerUtil.logToFile(LoggerUtil.Level.WTF, TAG, "verifyResponse", "response = " + contents); if (contents != null) { JSONObject json = new JSONObject(contents); String message = json.optString(JSON_ERROR_KEY, "response had no error message"); throw new LibException(message); } //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "verifyResponse", "error in request " // + responseCode + " " + message); throw new LibException("response " + responseCode); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "verifyResponse", contents, e); throw new LibException(e); } } else { //If the response is valid, evaluate if we need to parse the content switch (responseCode) { case HttpURLConnection.HTTP_OK: return true; case HttpURLConnection.HTTP_CREATED: return true; case HttpURLConnection.HTTP_NO_CONTENT: return false; default: return false; } } }
From source file:com.ubikod.capptain.android.sdk.reach.CapptainReachInteractiveContent.java
CapptainReachInteractiveContent(String jid, String rawXml, Element root) throws JSONException { super(jid, rawXml, root); mTitle = XmlUtil.getTagText(root, "title", root.getLocalName()); mActionLabel = XmlUtil.getTagText(root, "label", "action"); mExitLabel = XmlUtil.getTagText(root, "label", "exit"); /* Behavior */ mBehavior = Behavior.ANYTIME;// ww w .j a v a 2 s . co m Element behavior = XmlUtil.getTag(root, "behavior", null); if (behavior != null) if (XmlUtil.getTag(behavior, "session", null) != null) mBehavior = Behavior.SESSION; else { mAllowedActivities = new HashSet<String>(); NodeList activities = behavior.getElementsByTagNameNS(REACH_NAMESPACE, "activity"); if (activities.getLength() > 0) { mBehavior = Behavior.ACTIVITY; for (int i = 0; i < activities.getLength(); i++) mAllowedActivities.add(XmlUtil.getText(activities.item(i))); } } /* Notification */ Element notification = XmlUtil.getTag(root, "notification", null); if (notification != null) { /* By default, system, unless "activity" is specified */ mSystemNotification = !"activity".equals(notification.getAttribute("type")); /* The notification can be closed unless closeable is set to a non "true" value */ mNotiticationCloseable = XmlUtil.getBooleanAttribute(notification, "closeable", true); /* The notification has a content icon unless icon attribute set to a non "true" value. */ mNotificationIcon = XmlUtil.getBooleanAttribute(notification, "icon", true); /* Sound and vibration */ mNotificationSound = XmlUtil.getBooleanAttribute(notification, "sound", false); mNotificationVibrate = XmlUtil.getBooleanAttribute(notification, "vibrate", false); /* Parse texts */ mNotificationTitle = XmlUtil.getTagText(notification, "title", null); mNotificationMessage = XmlUtil.getTagText(notification, "message", null); /* Get image data, we decode the bitmap in a lazy way */ mNotificationImageString = XmlUtil.getTagText(notification, "image", null); /* Options */ String options = XmlUtil.getTagText(notification, "options", null); if (options != null) { JSONObject jOptions = new JSONObject(options); mNotificationBigText = jOptions.optString("bigText", null); mNotificationBigPicture = jOptions.optString("bigPicture", null); } } }
From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java
/***************************************************************** * Gets the URI of the song stream using the specified song Id. * The URI is dynamically generated by Google's servers and * expires after one minute of no usage. This method uses the * WebClient endpoint.//from ww w . java 2 s . co m * * @param songId The id of the song that needs to be streamed. * @return Returns the URI of the song stream. * @throws JSONException * @throws URISyntaxException ******************************************************************/ public static final URI getSongStream(String songId) throws JSONException, URISyntaxException { RequestParams params = new RequestParams(); params.put("u", "0"); params.put("songid", songId); params.put("pt", "e"); String response = mHttpClient.get("https://play.google.com/music/play", params); if (response != null) { JSONObject jsonObject = new JSONObject(response); return new URI(jsonObject.optString("url", null)); } return null; }
From source file:com.jsonstore.api.JSONStoreFindOptions.java
/** * @exclude Used internally//from w ww. j a va2 s . c o m */ public JSONStoreFindOptions(JSONObject options) throws JSONException, JSONStoreInvalidSortObjectException { filter = new HashMap<String, Boolean>(); sort = new LinkedHashMap<String, SortDirection>(); String limitStr = options.optString(JSONStoreFindOptions.OPTION_LIMIT, null); if (limitStr != null) { Integer limitParse = Integer.parseInt(limitStr); setLimit(limitParse); } String offsetStr = options.optString(JSONStoreFindOptions.OPTION_OFFSET, null); if (offsetStr != null) { Integer offsetParse = Integer.parseInt(offsetStr); setOffset(offsetParse); } JSONArray sortArray = options.optJSONArray(JSONStoreFindOptions.OPTION_SORT_ARRAY); if (sortArray != null) { for (int idx = 0; idx < sortArray.length(); idx++) { JSONObject sortObject = sortArray.getJSONObject(idx); Iterator<String> keys = sortObject.keys(); String key = keys.next(); if (keys.hasNext()) { throw new JSONStoreInvalidSortObjectException( "One of the sort objects in the sort array has more than one field."); } //Parse the direction of the sort for this search field: String sortDirectionStr = sortObject.getString(key); if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.ASCENDING)) { sortBySearchFieldAscending(key); } else if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.DESCENDING)) { sortBySearchFieldDescending(key); } else { throw new JSONStoreInvalidSortObjectException( "Invalid sorting direction (ascending or descending) specified."); } } } JSONArray filterParse = options.optJSONArray(JSONStoreFindOptions.OPTION_FILTER); if (filterParse != null) { for (int idx = 0; idx < filterParse.length(); idx++) { addSearchFilter(filterParse.getString(idx)); } } }