Example usage for org.json JSONException getMessage

List of usage examples for org.json JSONException getMessage

Introduction

In this page you can find the example usage for org.json JSONException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.tune.reporting.base.endpoints.EndpointBase.java

/**
 * Parse response and gather report url.
 *
 * @param response @see TuneServiceResponse
 *
 * @return String   Report URL download from Export queue.
 * @throws TuneSdkException If error within SDK.
 * @throws TuneServiceException If service fails to handle post request.
 *///from w ww. j a  v  a  2  s . c om
public static String parseResponseReportUrl(final TuneServiceResponse response)
        throws IllegalArgumentException, TuneSdkException, TuneServiceException {

    if (null == response) {
        throw new IllegalArgumentException("Parameter 'response' is not defined.");
    }

    JSONObject jdata = (JSONObject) response.getData();
    if (null == jdata) {
        throw new TuneServiceException("Report export response failed to get data.");
    }

    if (!jdata.has("data")) {
        throw new TuneSdkException(
                String.format("Export data does not contain report 'data', response: %s", response.toString()));
    }

    JSONObject jdataInternal = null;
    try {
        jdataInternal = jdata.getJSONObject("data");
    } catch (JSONException ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    }

    if (null == jdataInternal) {
        throw new TuneServiceException(String
                .format("Export data response does not contain 'data', response: %s", response.toString()));
    }

    if (!jdataInternal.has("url")) {
        throw new TuneSdkException(String.format("Export response 'data' does not contain 'url', response: %s",
                response.toString()));
    }

    String jdataInternalUrl = null;
    try {
        jdataInternalUrl = jdataInternal.getString("url");
    } catch (JSONException ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    }

    if ((null == jdataInternalUrl) || jdataInternalUrl.isEmpty()) {
        throw new TuneSdkException(
                String.format("Export response 'url' is not defined, response: %s", response.toString()));
    }

    return jdataInternalUrl;
}

From source file:com.mobeelizer.mobile.android.types.FileFieldTypeHelper.java

@Override
public void setValueFromDatabaseToMap(final Cursor cursor, final Map<String, String> values,
        final MobeelizerFieldAccessor field, final Map<String, String> options) {
    int columnIndex = cursor.getColumnIndex(field.getName() + _GUID);

    if (cursor.isNull(columnIndex)) {
        values.put(field.getName(), null);
    } else {/* w  w w  .  j  a  v a 2 s.  c om*/
        try {
            JSONObject json = new JSONObject();
            json.put(JSON_GUID, cursor.getString(columnIndex));
            json.put(JSON_NAME, cursor.getString(cursor.getColumnIndex(field.getName() + _NAME)));

            values.put(field.getName(), json.toString());
        } catch (JSONException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}

From source file:com.mobeelizer.mobile.android.types.FileFieldTypeHelper.java

@Override
protected void setNotNullValueFromMapToDatabase(final ContentValues values, final String value,
        final MobeelizerFieldAccessor field, final Map<String, String> options,
        final MobeelizerErrorsBuilder errors) {
    try {//from  w w w. j  a  va 2s  .c  om
        JSONObject json = new JSONObject(value);
        values.put(field.getName() + _GUID, json.getString(JSON_GUID));
        values.put(field.getName() + _NAME, json.getString(JSON_NAME));
    } catch (JSONException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.polyvi.xface.view.XWebChromeClient.java

@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
        JsPromptResult result) {//from  w  w w .ja  va 2 s. c  o m
    boolean reqOk = false;
    if (url.startsWith("file://") || Config.isUrlWhiteListed(url)) {
        reqOk = true;
    }
    if (reqOk && defaultValue != null && defaultValue.equals("xFace_close_application:")) {
        XAppWebView appView = ((XAppWebView) view);
        int viewId = appView.getViewId();
        XEvent evt = XEvent.createEvent(XEventType.CLOSE_APP, viewId);
        ((XFaceMainActivity) mInterface.getActivity()).getEventCenter().sendEventSync(evt);
        result.confirm("");
        return true;
    } else if (reqOk && defaultValue != null && defaultValue.equals("xFace_app_send_message:")) {
        try {
            JSONArray args = new JSONArray(message);
            Pair<XAppWebView, String> appMessage = new Pair<XAppWebView, String>((XAppWebView) view,
                    args.getString(0));
            XEvent evt = XEvent.createEvent(XEventType.XAPP_MESSAGE, appMessage);
            ((XFaceMainActivity) mInterface.getActivity()).getEventCenter().sendEventSync(evt);
        } catch (JSONException e) {
            XLog.e(CLASS_NAME, "");
            XLog.e(CLASS_NAME, e.getMessage());
        }
        result.confirm("");
        return true;
    }
    return super.onJsPrompt(view, url, message, defaultValue, result);
}

From source file:com.downloadfacebook.AsyncRequestListener.java

public void onComplete(String response, final Object state) {
    try {//from  ww w.j a  va  2  s. co  m
        JSONObject obj = Util.parseJson(response);
        onComplete(obj, state);
    } catch (JSONException e) {
        e.printStackTrace();
        Log.e("facebook-stream", "JSON Error:" + e.getMessage());
    } catch (FacebookError e) {
        Log.e("facebook-stream", "Facebook Error:" + e.getMessage());
    }

}

From source file:com.ota.updates.json.ROMJSONParser.java

/**
 * Parse the Rom object within the selected JSON string
 *//*from  w  ww  . j a  v  a 2 s  .  c om*/
public void parse() {
    try {
        JSONObject jObj = new JSONObject(mJSONString);

        JSONObject romObj = jObj.getJSONObject(NAME_ROM);

    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    }
}

From source file:com.autburst.picture.facebook.AsyncRequestListener.java

public void onComplete(String response) {
    try {//ww  w. j  a  va2s  . c  om
        JSONObject obj = Util.parseJson(response);
        onComplete(obj);
    } catch (JSONException e) {
        e.printStackTrace();
        Log.e("facebook-stream", "JSON Error:" + e.getMessage());
    } catch (FacebookError e) {
        Log.e("facebook-stream", "Facebook Error:" + e.getMessage());
    }

}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

/**
* Create an error object based on the passed in errorCode
* @param errorCode      the error//from   w w  w .j av a  2  s.  c o m
* @return JSONObject containing the error
*/
private static JSONObject createFileTransferError(int errorCode, String source, String target, String body,
        Integer httpStatus) {
    JSONObject error = null;
    try {
        error = new JSONObject();
        error.put("code", errorCode);
        error.put("source", source);
        error.put("target", target);
        if (body != null) {
            error.put("body", body);
        }
        if (httpStatus != null) {
            error.put("http_status", httpStatus);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return error;
}

From source file:com.acrutiapps.browser.tasks.HistoryBookmarksExportTask.java

private String writeAsJSON(Cursor... params) {
    try {//from  ww w.j  a  v  a2s. c  o  m
        String fileName = mContext.getString(R.string.ApplicationName) + "-" + getNowForFileName() + ".json";

        File file = new File(Environment.getExternalStorageDirectory(), fileName);
        FileWriter writer = new FileWriter(file);

        FoldersJSONArray foldersArray = new FoldersJSONArray();
        BookmarksJSONArray bookmarksArray = new BookmarksJSONArray();
        HistoryJSONArray historyArray = new HistoryJSONArray();

        Cursor c = params[0];
        if (c.moveToFirst()) {

            int current = 0;
            int total = c.getCount();

            int idIndex = c.getColumnIndex(BookmarksProvider.Columns._ID);
            int titleIndex = c.getColumnIndex(BookmarksProvider.Columns.TITLE);
            int urlIndex = c.getColumnIndex(BookmarksProvider.Columns.URL);
            int creationDateIndex = c.getColumnIndex(BookmarksProvider.Columns.CREATION_DATE);
            int visitedDateIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITED_DATE);
            int visitsIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITS);
            int bookmarkIndex = c.getColumnIndex(BookmarksProvider.Columns.BOOKMARK);
            int folderIndex = c.getColumnIndex(BookmarksProvider.Columns.IS_FOLDER);
            int parentfolderIdIndex = c.getColumnIndex(BookmarksProvider.Columns.PARENT_FOLDER_ID);

            while (!c.isAfterLast()) {

                publishProgress(1, current, total);

                boolean isFolder = c.getInt(folderIndex) > 0 ? true : false;

                if (isFolder) {
                    String title = c.getString(titleIndex);
                    title = title != null ? URLEncoder.encode(title, "UTF-8") : "";

                    foldersArray.add(title, c.getLong(idIndex), c.getLong(parentfolderIdIndex));

                } else {
                    boolean isBookmark = c.getInt(bookmarkIndex) > 0 ? true : false;

                    String title = c.getString(titleIndex);
                    title = title != null ? URLEncoder.encode(title, "UTF-8") : "";

                    String url = c.getString(urlIndex);
                    url = url != null ? URLEncoder.encode(url, "UTF-8") : "";

                    if (isBookmark) {
                        bookmarksArray.add(c.getLong(parentfolderIdIndex), title, url,
                                c.getLong(creationDateIndex), c.getLong(visitedDateIndex),
                                c.getInt(visitsIndex));
                    } else {
                        historyArray.add(title, url, c.getLong(visitedDateIndex), c.getInt(visitsIndex));
                    }
                }

                current++;
                c.moveToNext();
            }
        }

        JSONObject output = new JSONObject();
        output.put("folders", foldersArray);
        output.put("bookmarks", bookmarksArray);
        output.put("history", historyArray);

        writer.write(output.toString(1));

        writer.flush();
        writer.close();

    } catch (JSONException e) {
        e.printStackTrace();
        return e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return e.getMessage();
    }

    return null;
}

From source file:com.seunghyo.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 w  ww . j  a  va  2  s .  com*/
 */
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
        }

        // 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;
}