List of usage examples for org.json JSONException getMessage
public String getMessage()
From source file:com.aokyu.dev.pocket.PocketClient.java
public RetrieveResponse retrieve(AccessToken accessToken, RetrieveRequest retrieveRequest) throws IOException, InvalidRequestException, PocketException { String endpoint = PocketServer.getEndpoint(RequestType.RETRIEVE); URL requestUrl = new URL(endpoint); HttpHeaders headers = new HttpHeaders(); headers.put(HttpHeader.CONTENT_TYPE, ContentType.JSON_WITH_UTF8.get()); headers.put(HttpHeader.X_ACCEPT, ContentType.JSON.get()); headers.put(HttpHeader.HOST, requestUrl.getHost()); retrieveRequest.put(AddRequest.Parameter.ACCESS_TOKEN, accessToken.get()); retrieveRequest.put(AddRequest.Parameter.CONSUMER_KEY, mConsumerKey.get()); HttpParameters parameters = retrieveRequest.getHttpParameters(); HttpRequest request = new HttpRequest(HttpMethod.POST, requestUrl, headers, parameters); HttpResponse response = null;//from w ww . j a v a 2 s .com JSONObject jsonObj = null; Map<String, List<String>> responseHeaders = null; try { response = mClient.execute(request); if (response.getStatusCode() == HttpURLConnection.HTTP_OK) { jsonObj = response.getResponseAsJSONObject(); responseHeaders = response.getHeaderFields(); } else { ErrorResponse error = new ErrorResponse(response); mErrorHandler.handleResponse(error); } } catch (JSONException e) { throw new PocketException(e.getMessage()); } finally { if (response != null) { response.disconnect(); } } RetrieveResponse retrieveResponse = null; if (jsonObj != null) { try { retrieveResponse = new RetrieveResponse(jsonObj, responseHeaders); } catch (JSONException e) { throw new PocketException(e.getMessage()); } } return retrieveResponse; }
From source file:com.aokyu.dev.pocket.PocketClient.java
public ModifyResponse modify(AccessToken accessToken, ModifyRequest modifyRequest) throws IOException, InvalidRequestException, PocketException { String endpoint = PocketServer.getEndpoint(RequestType.MODIFY); URL requestUrl = new URL(endpoint); HttpHeaders headers = new HttpHeaders(); headers.put(HttpHeader.CONTENT_TYPE, ContentType.JSON_WITH_UTF8.get()); headers.put(HttpHeader.X_ACCEPT, ContentType.JSON.get()); headers.put(HttpHeader.HOST, requestUrl.getHost()); modifyRequest.put(AddRequest.Parameter.ACCESS_TOKEN, accessToken.get()); modifyRequest.put(AddRequest.Parameter.CONSUMER_KEY, mConsumerKey.get()); HttpParameters parameters = modifyRequest.getHttpParameters(); HttpRequest request = new HttpRequest(HttpMethod.POST, requestUrl, headers, parameters); HttpResponse response = null;/*from w w w . ja v a 2 s . c om*/ JSONObject jsonObj = null; Map<String, List<String>> responseHeaders = null; try { response = mClient.execute(request); if (response.getStatusCode() == HttpURLConnection.HTTP_OK) { jsonObj = response.getResponseAsJSONObject(); responseHeaders = response.getHeaderFields(); } else { ErrorResponse error = new ErrorResponse(response); mErrorHandler.handleResponse(error); } } catch (JSONException e) { throw new PocketException(e.getMessage()); } finally { if (response != null) { response.disconnect(); } } ModifyResponse modifyResponse = null; if (jsonObj != null) { try { modifyResponse = new ModifyResponse(jsonObj, responseHeaders); } catch (JSONException e) { throw new PocketException(e.getMessage()); } } return modifyResponse; }
From source file:com.facebook.share.internal.NativeDialogParameters.java
public static Bundle create(UUID callId, ShareContent shareContent, boolean shouldFailOnDataError) { Validate.notNull(shareContent, "shareContent"); Validate.notNull(callId, "callId"); Bundle nativeParams = null;/*from w w w .jav a 2s.com*/ if (shareContent instanceof ShareLinkContent) { final ShareLinkContent linkContent = (ShareLinkContent) shareContent; nativeParams = create(linkContent, shouldFailOnDataError); } else if (shareContent instanceof SharePhotoContent) { final SharePhotoContent photoContent = (SharePhotoContent) shareContent; List<String> photoUrls = ShareInternalUtility.getPhotoUrls(photoContent, callId); nativeParams = create(photoContent, photoUrls, shouldFailOnDataError); } else if (shareContent instanceof ShareVideoContent) { final ShareVideoContent videoContent = (ShareVideoContent) shareContent; String videoUrl = ShareInternalUtility.getVideoUrl(videoContent, callId); nativeParams = create(videoContent, videoUrl, shouldFailOnDataError); } else if (shareContent instanceof ShareOpenGraphContent) { final ShareOpenGraphContent openGraphContent = (ShareOpenGraphContent) shareContent; try { JSONObject openGraphActionJSON = ShareInternalUtility.toJSONObjectForCall(callId, openGraphContent); openGraphActionJSON = ShareInternalUtility.removeNamespacesFromOGJsonObject(openGraphActionJSON, false); nativeParams = create(openGraphContent, openGraphActionJSON, shouldFailOnDataError); } catch (final JSONException e) { throw new FacebookException( "Unable to create a JSON Object from the provided ShareOpenGraphContent: " + e.getMessage()); } } return nativeParams; }
From source file:app.com.example.kiran.sunshine.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/>/*from w ww. j a v a2 s.c o m*/ * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } // Sort order: Ascending, by date. String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis()); // Students: Uncomment the next lines to display what what you stored in the bulkInsert Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder); cVVector = new Vector<ContentValues>(cur.getCount()); if (cur.moveToFirst()) { do { ContentValues cv = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cur, cv); cVVector.add(cv); } while (cur.moveToNext()); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); //String resultStrs = convertContentValuesToUXFormat(cur); //return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } //return null; }
From source file:com.inbeacon.cordova.CordovaInbeaconManager.java
/** * Transform Android event data into JSON Object used by JavaScript * @param intent inBeacon SDK event data * @return a JSONObject with keys 'event', 'name' and 'data' *///from ww w .j a v a 2s . com private JSONObject getEventObject(Intent intent) { String action = intent.getAction(); String event = action.substring(action.lastIndexOf(".") + 1); // last part of action String message = intent.getStringExtra("message"); Bundle extras = intent.getExtras(); JSONObject eventObject = new JSONObject(); JSONObject data = new JSONObject(); try { if (extras != null) { Set<String> keys = extras.keySet(); for (String key : keys) { data.put(key, extras.get(key)); // Android API < 19 // data.put(key, JSONObject.wrap(extras.get(key))); // Android API >= 19 } } data.put("message", message); eventObject.put("name", event); eventObject.put("data", data); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } return eventObject; }
From source file:com.phonegap.BatteryListener.java
/** * Creates a JSONObject with the current battery information * /* www . j a va2s . c om*/ * @param batteryIntent the current battery information * @return a JSONObject containing the battery status information */ private JSONObject getBatteryInfo(Intent batteryIntent) { JSONObject obj = new JSONObject(); try { obj.put("level", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, 0)); obj.put("isPlugged", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_PLUGGED, -1) > 0 ? true : false); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); } return obj; }
From source file:org.eclipse.orion.internal.server.servlets.file.DirectoryHandlerV1.java
@Override public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, IFileStore dir) throws ServletException { try {/*from w w w . j av a 2 s.c om*/ switch (getMethod(request)) { case GET: return handleGet(request, response, dir); case PUT: return handlePut(request, response, dir); case POST: return handlePost(request, response, dir); case DELETE: return handleDelete(request, response, dir); } } catch (JSONException e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Syntax error in request", e)); } catch (CoreException e) { //core exception messages are designed for end user consumption, so use message directly return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e)); } catch (Exception e) { if (handleAuthFailure(request, response, e)) return true; //the exception message is probably not appropriate for end user consumption LogHelper.log(e); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An unknown failure occurred. Consult your server log or contact your system administrator.", e)); } return false; }
From source file:com.ryansmertz.sunshine.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./*from ww w . j a v a2 s . c o m*/ */ private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } // Sort order: Ascending, by date. String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis()); // Students: Uncomment the next lines to display what what you stored in the bulkInsert Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder); cVVector = new Vector<ContentValues>(cur.getCount()); if (cur.moveToFirst()) { do { ContentValues cv = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cur, cv); cVVector.add(cv); } while (cur.moveToNext()); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); String[] resultStrs = convertContentValuesToUXFormat(cVVector); return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:org.dasein.cloud.cloudsigma.CloudSigmaMethod.java
static public @Nullable String seekValue(@Nonnull String body, @Nonnull String key) { //dmayne 20130218: use JSON parsing rather than plain text body = body.trim();/*w ww. j a v a2 s . c om*/ if (body.length() > 0) { try { JSONObject obj = new JSONObject(body); if (obj != null) { JSONObject json = (JSONObject) obj; return json.getString(key); } } catch (JSONException e) { logger.error("Exception getting value: " + e.getMessage()); } } return null; }
From source file:com.projectgoth.mywebrtcdemo.WebSocketChannelClient.java
public void register(final String roomID, final String clientID) { checkIfCalledOnValidThread();//from w ww. j ava 2 s . c o m this.roomID = roomID; this.clientID = clientID; if (state != WebSocketConnectionState.CONNECTED) { Log.w(TAG, "WebSocket register() in state " + state); return; } Log.d(TAG, "Registering WebSocket for room " + roomID + ". CLientID: " + clientID); JSONObject json = new JSONObject(); try { json.put("cmd", "register"); json.put("roomid", roomID); json.put("clientid", clientID); Log.d(TAG, "C->WSS: " + json.toString()); ws.sendTextMessage(json.toString()); state = WebSocketConnectionState.REGISTERED; // Send any previously accumulated messages. for (String sendMessage : wsSendQueue) { send(sendMessage); } wsSendQueue.clear(); } catch (JSONException e) { reportError("WebSocket register JSON error: " + e.getMessage()); } }