List of usage examples for org.json JSONException getMessage
public String getMessage()
From source file:org.jabsorb.ng.serializer.impl.DictionarySerializer.java
@Override public Object unmarshall(final SerializerState state, final Class<?> clazz, final Object o) throws UnmarshallException { final JSONObject jso = (JSONObject) o; String java_class; // Hint check try {/*from w ww . jav a 2 s . c om*/ java_class = jso.getString("javaClass"); } catch (final JSONException e) { throw new UnmarshallException("Could not read javaClass", e); } if (java_class == null) { throw new UnmarshallException("no type hint"); } // Create the dictionary Hashtable<Object, Object> dictionary; if (java_class.equals("java.util.Dictionary") || java_class.equals("java.util.Hashtable")) { dictionary = new Hashtable<Object, Object>(); } else if (java_class.equals("java.util.Properties")) { dictionary = new Properties(); } else { throw new UnmarshallException("not a Dictionary"); } // Parse the JSON map JSONObject jsonmap; try { jsonmap = jso.getJSONObject("map"); } catch (final JSONException e) { throw new UnmarshallException("map missing", e); } if (jsonmap == null) { throw new UnmarshallException("map missing"); } state.setSerialized(o, dictionary); final Iterator<?> i = jsonmap.keys(); String key = null; try { while (i.hasNext()) { key = (String) i.next(); dictionary.put(key, ser.unmarshall(state, null, jsonmap.get(key))); } } catch (final UnmarshallException e) { throw new UnmarshallException("key " + key + " " + e.getMessage(), e); } catch (final JSONException e) { throw new UnmarshallException("key " + key + " " + e.getMessage(), e); } return dictionary; }
From source file:org.jabsorb.ng.serializer.impl.SetSerializer.java
@Override public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException { final Set<?> set = (Set<?>) o; final JSONObject obj = new JSONObject(); final JSONArray setdata = new JSONArray(); if (ser.getMarshallClassHints()) { try {/*w w w .j a v a 2s. co m*/ obj.put("javaClass", o.getClass().getName()); } catch (final JSONException e) { throw new MarshallException("javaClass not found!", e); } } try { obj.put("set", setdata); state.push(o, setdata, "set"); } catch (final JSONException e) { throw new MarshallException("Could not set 'set': " + e.getMessage(), e); } Object value = null; int idx = 0; final Iterator<?> i = set.iterator(); try { while (i.hasNext()) { value = i.next(); final Object json = ser.marshall(state, setdata, value, idx); // omit the object entirely if it's a circular reference or // duplicate // it will be regenerated in the fixups phase if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) { setdata.put(idx, json); } idx++; } } catch (final MarshallException e) { throw new MarshallException("set value " + value + " " + e.getMessage(), e); } catch (final JSONException e) { throw new MarshallException("set value " + value + " " + e.getMessage(), e); } finally { state.pop(); } return obj; }
From source file:org.jabsorb.ng.serializer.impl.SetSerializer.java
@Override public ObjectMatch tryUnmarshall(final SerializerState state, final Class<?> clazz, final Object o) throws UnmarshallException { JSONArray jsonset;//from ww w.j av a2 s . c o m if (o instanceof JSONArray) { jsonset = (JSONArray) o; } else if (o instanceof JSONObject) { final JSONObject jso = (JSONObject) o; String java_class; // Hint presence try { java_class = jso.getString("javaClass"); } catch (final JSONException e) { throw new UnmarshallException("Could not read javaClass", e); } if (java_class == null) { throw new UnmarshallException("no type hint"); } // Class compatibility check if (!classNameCheck(java_class)) { throw new UnmarshallException("not a Set"); } // JSON Format check try { jsonset = jso.getJSONArray("set"); } catch (final JSONException e) { throw new UnmarshallException("set missing", e); } } else { throw new UnmarshallException("Given object is not JSON object/array"); } if (jsonset == null) { throw new UnmarshallException("set missing"); } // Content check final ObjectMatch m = new ObjectMatch(-1); state.setSerialized(o, m); int idx = 0; try { for (idx = 0; idx < jsonset.length(); idx++) { m.setMismatch(ser.tryUnmarshall(state, null, jsonset.get(idx)).max(m).getMismatch()); } } catch (final UnmarshallException e) { throw new UnmarshallException("index " + idx + " " + e.getMessage(), e); } catch (final JSONException e) { throw new UnmarshallException("index " + idx + " " + e.getMessage(), e); } return m; }
From source file:org.jabsorb.ng.serializer.impl.SetSerializer.java
@Override public Object unmarshall(final SerializerState state, final Class<?> clazz, final Object o) throws UnmarshallException { final JSONArray jsonset; final Set<Object> abset; if (o instanceof JSONArray) { jsonset = (JSONArray) o;// w ww. j av a2 s .c om abset = new LinkedHashSet<Object>(); } else if (o instanceof JSONObject) { final JSONObject jso = (JSONObject) o; String java_class; // Hint check try { java_class = jso.getString("javaClass"); } catch (final JSONException e) { throw new UnmarshallException("Could not read javaClass", e); } if (java_class == null) { throw new UnmarshallException("no type hint"); } // Create the set if (java_class.equals("java.util.Set") || java_class.equals("java.util.AbstractSet") || java_class.equals("java.util.HashSet")) { abset = new HashSet<Object>(); } else if (java_class.equals("java.util.TreeSet")) { abset = new TreeSet<Object>(); } else if (java_class.equals("java.util.LinkedHashSet")) { abset = new LinkedHashSet<Object>(); } else { throw new UnmarshallException("not a Set"); } // Parse the JSON set try { jsonset = jso.getJSONArray("set"); } catch (final JSONException e) { throw new UnmarshallException("set missing", e); } } else { throw new UnmarshallException("Given object is not JSON object/array"); } if (jsonset == null) { throw new UnmarshallException("set missing"); } state.setSerialized(o, abset); int idx = 0; try { for (idx = 0; idx < jsonset.length(); idx++) { abset.add(ser.unmarshall(state, null, jsonset.get(idx))); } } catch (final UnmarshallException e) { throw new UnmarshallException("index " + idx + " " + e.getMessage(), e); } catch (final JSONException e) { throw new UnmarshallException("index " + idx + " " + e.getMessage(), e); } return abset; }
From source file:com.example.jz.mysunshine.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 w w. java 2 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); } int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + "Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } }
From source file:com.fsa.en.dron.activity.MainActivity.java
private void fetchImages() { pDialog.setMessage("Levantando vuelo..."); pDialog.setCanceledOnTouchOutside(false); pDialog.show();/*from w w w.ja v a 2 s . c o m*/ JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, endpoint, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); pDialog.hide(); JSONArray array = null; try { JSONObject user = response.getJSONObject("photos"); array = user.getJSONArray("photo"); } catch (JSONException e) { e.printStackTrace(); } images.clear(); for (int i = 0; i < array.length(); i++) { try { JSONObject object = array.getJSONObject(i); Image image = new Image(); image.setSmall("https://farm2.staticflickr.com/" + object.getString("server") + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg"); image.setMedium("https://farm2.staticflickr.com/" + object.getString("server") + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg"); image.setLarge("https://farm2.staticflickr.com/" + object.getString("server") + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg"); image.setUrl("https://farm2.staticflickr.com/" + object.getString("server") + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg"); image.setId(object.getString("id")); Log.i("uuu", "" + "https://farm2.staticflickr.com/" + object.getString("server") + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg"); images.add(image); } catch (JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); } } mAdapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(req); }
From source file:org.vaadin.addons.locationtextfield.GoogleGeocoder.java
protected Collection<GeocodedLocation> createLocations(String address, String input) throws GeocodingException { final Set<GeocodedLocation> locations = new LinkedHashSet<GeocodedLocation>(); try {/*from w w w . j a v a 2s . com*/ JSONObject obj = new JSONObject(input); if ("OK".equals(obj.getString("status"))) { JSONArray results = obj.getJSONArray("results"); boolean ambiguous = results.length() > 1; int limit = results.length(); if (this.getLimit() > 0) limit = Math.min(this.getLimit(), limit); for (int i = 0; i < limit; i++) { JSONObject result = results.getJSONObject(i); GeocodedLocation loc = new GeocodedLocation(); loc.setAmbiguous(ambiguous); loc.setOriginalAddress(address); loc.setGeocodedAddress(result.getString("formatted_address")); JSONArray components = result.getJSONArray("address_components"); for (int j = 0; j < components.length(); j++) { JSONObject component = components.getJSONObject(j); String value = component.getString("short_name"); JSONArray types = component.getJSONArray("types"); for (int k = 0; k < types.length(); k++) { String type = types.getString(k); if ("street_number".equals(type)) loc.setStreetNumber(value); else if ("route".equals(type)) loc.setRoute(value); else if ("locality".equals(type)) loc.setLocality(value); else if ("administrative_area_level_1".equals(type)) loc.setAdministrativeAreaLevel1(value); else if ("administrative_area_level_2".equals(type)) loc.setAdministrativeAreaLevel2(value); else if ("country".equals(type)) loc.setCountry(value); else if ("postal_code".equals(type)) loc.setPostalCode(value); } } JSONObject location = result.getJSONObject("geometry").getJSONObject("location"); loc.setLat(location.getDouble("lat")); loc.setLon(location.getDouble("lng")); loc.setType(getLocationType(result)); locations.add(loc); } } } catch (JSONException e) { throw new GeocodingException(e.getMessage(), e); } return locations; }
From source file:com.phonegap.plugins.discoverscanar.DiscoverScanAR.java
/** * Called when the barcode scanner intent completes. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). *///from w w w .j a va 2s . c o m @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { // logging goes to logcat. LOG.d for debug(), LOG.e for error() // http://www.vogella.com/tutorials/AndroidLogging/article.html //Log.d(LOG_TAG, "#### onActivityResult"); if (requestCode == REQUEST_SCAN_CODE) { if (resultCode == Activity.RESULT_OK) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, intent.getStringExtra("SCAN_RESULT")); obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT")); obj.put(CANCELLED, false); this.callbackContext.success(obj); Log.e(LOG_TAG, "#### Found text: " + intent.getStringExtra("SCAN_RESULT") + " AND Called callback on success"); } catch (JSONException e) { Log.d(LOG_TAG, "This should never happen"); this.callbackContext.error("Scan intent. Unexpected error: " + e.getMessage()); } //this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback); //this.callbackContext.success(obj); } else if (resultCode == Activity.RESULT_CANCELED) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, ""); obj.put(FORMAT, ""); obj.put(CANCELLED, true); //Log.e(LOG_TAG, "#### Found no text"); this.callbackContext.success(obj); } catch (JSONException e) { Log.d(LOG_TAG, "This should never happen"); this.callbackContext.error("Scan intent. Unexpected error: " + e.getMessage()); } //this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback); //this.callbackContext.success(obj); } else { //this.error(new PluginResult(PluginResult.Status.ERROR), this.callback); this.callbackContext.error("Scan intent. Unexpected error"); } } else if (requestCode == REQUEST_ARSCAN_CODE) { if (resultCode == Activity.RESULT_OK) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, intent.getStringExtra("ARSCAN_RESULT")); obj.put(CANCELLED, false); this.callbackContext.success(obj); } catch (JSONException e) { Log.d(LOG_TAG, "ARScan intent (RESULT_OK) threw an exception: This should never happen"); this.callbackContext.error("ARScan intent. Unexpected error: " + e.getMessage()); } //this.callbackContext.success(obj); } else if (resultCode == Activity.RESULT_CANCELED) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, ""); obj.put(CANCELLED, true); this.callbackContext.success(obj); } catch (JSONException e) { Log.d(LOG_TAG, "ARScan intent (RESULT_CANCELED) threw an exception. This should never happen"); this.callbackContext.error("ARScan intent. Unexpected error: " + e.getMessage()); } //this.callbackContext.success(obj); } else { //this.error(new PluginResult(PluginResult.Status.ERROR), this.callback); this.callbackContext.error("ARScan intent. Unexpected error"); } } }
From source file:eu.trentorise.smartcampus.ac.network.RemoteConnector.java
/** * @param string// ww w . ja va 2 s . c o m * @param refresh * @param clientId * @param clientSecret * @throws AACException */ public static TokenData refreshToken(String service, String refresh, String clientId, String clientSecret) throws AACException { HttpResponse resp = null; HttpEntity entity = null; Log.i(TAG, "refreshing token: " + refresh); String url = service + PATH_TOKEN + "?grant_type=refresh_token&refresh_token=" + refresh + "&client_id=" + clientId + "&client_secret=" + clientSecret; HttpPost post = new HttpPost(url); post.setEntity(entity); post.setHeader("Accept", "application/json"); try { resp = getHttpClient().execute(post); String response = EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { TokenData data = TokenData.valueOf(response); Log.v(TAG, "Successful authentication"); return data; } Log.e(TAG, "Error validating " + resp.getStatusLine()); try { JSONObject error = new JSONObject(response); if (error != null && error.has("error")) { throw new AACException(HttpStatus.SC_UNAUTHORIZED, "OAuth error " + error.optString("error_description")); } } catch (JSONException e) { Log.w(TAG, "Unknown response message:" + resp.getStatusLine()); } throw new AACException("Error validating " + resp.getStatusLine()); // } catch (Exception e) { // Log.e(TAG, "Exception when getting authtoken", e); // if (resp != null) { // throw new AACException(resp.getStatusLine().getStatusCode(), ""+e.getMessage()); // } else { // throw new AACException(e); // } } catch (ClientProtocolException e) { if (resp != null) { throw new AACException(resp.getStatusLine().getStatusCode(), "" + e.getMessage()); } else { throw new AACException(e); } } catch (IOException e) { if (resp != null) { throw new AACException(resp.getStatusLine().getStatusCode(), "" + e.getMessage()); } else { throw new AACException(e); } } finally { Log.v(TAG, "refresh token completing"); } }
From source file:de.duenndns.ssl.MemorizingTrustManager.java
private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) { Log.d("mtm", "downloading json for " + domain + " from " + url); try {/*from ww w .j av a2 s .c om*/ List<String> results = new ArrayList<>(); HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder builder = new StringBuilder(); while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } JSONObject jsonObject = new JSONObject(builder.toString()); in.close(); int expires = jsonObject.getInt("expires"); if (expires <= 0) { return new ArrayList<>(); } if (maxTtl >= 0) { expires = Math.min(maxTtl, expires); } String redirect; try { redirect = jsonObject.getString("url"); } catch (JSONException e) { redirect = null; } if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) { return getPoshFingerprintsFromServer(domain, redirect, expires, false); } JSONArray fingerprints = jsonObject.getJSONArray("fingerprints"); for (int i = 0; i < fingerprints.length(); i++) { JSONObject fingerprint = fingerprints.getJSONObject(i); String sha256 = fingerprint.getString("sha-256"); if (sha256 != null) { results.add(sha256); } } writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis()); return results; } catch (Exception e) { Log.d("mtm", "error fetching posh " + e.getMessage()); return new ArrayList<>(); } }