Example usage for org.json JSONException printStackTrace

List of usage examples for org.json JSONException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:fi.elfcloud.sci.container.Cluster.java

/**
 * Returns child {@link DataItem}s//from   w ww.j a v a  2s .co m
 * @param    keynames array of {@link DataItem} names. Can be empty Array to list all.
 * @return {@link DataItem}s filtered by <code>keynames</code> or all direct {@link DataItem}s if
 *       array is empty
 * @throws ECException
 * @throws IOException
 */
public DataItem[] getDataItems(String[] keynames) throws ECException, IOException {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("parent_id", this.id);
    params.put("names", keynames);
    Object response;
    try {
        response = (JSONArray) this.client.getConnection().sendRequest("list_dataitems", params);
        JSONArray dataItems = (JSONArray) response;
        DataItem result[] = new DataItem[dataItems.length()];
        for (int i = 0; i < dataItems.length(); i++) {
            result[i] = new DataItem(this.client, dataItems.getJSONObject(i), this.id);
        }
        this.dataItemCount = result.length;
        return result;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.jitix.nbastatstream.util.IabHelper.java

/**
 * Handles an activity result that's part of the purchase flow in in-app billing. If you
 * are calling {@link #launchPurchaseFlow}, then you must call this method from your
 * Activity's {@link android.app.Activity@onActivityResult} method. This method
 * MUST be called from the UI thread of the Activity.
 *
 * @param requestCode The requestCode as you received it.
 * @param resultCode The resultCode as you received it.
 * @param data The data (Intent) as you received it.
 * @return Returns true if the result was related to a purchase flow and was handled;
 *     false if the result was not related to a purchase, in which case you should
 *     handle it normally.//from  ww  w . j a  v a 2 s  .c  om
 */
public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
    IabResult result;
    if (requestCode != mRequestCode)
        return false;

    checkNotDisposed();
    checkSetupDone("handleActivityResult");

    // end of async purchase operation that started on launchPurchaseFlow
    flagEndAsync();

    if (data == null) {
        logError("Null data in IAB activity result.");
        result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result");
        if (mPurchaseListener != null)
            mPurchaseListener.onIabPurchaseFinished(result, null);
        return true;
    }

    int responseCode = getResponseCodeFromIntent(data);
    String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA);
    String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE);

    if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) {
        logDebug("Successful resultcode from purchase activity.");
        logDebug("Purchase data: " + purchaseData);
        logDebug("Data signature: " + dataSignature);
        logDebug("Extras: " + data.getExtras());
        logDebug("Expected item type: " + mPurchasingItemType);

        if (purchaseData == null || dataSignature == null) {
            logError("BUG: either purchaseData or dataSignature is null.");
            logDebug("Extras: " + data.getExtras().toString());
            result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature");
            if (mPurchaseListener != null)
                mPurchaseListener.onIabPurchaseFinished(result, null);
            return true;
        }

        Purchase purchase = null;
        try {
            purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature);
            String sku = purchase.getSku();

            // Verify signature
            if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) {
                logError("Purchase signature verification FAILED for sku " + sku);
                result = new IabResult(IABHELPER_VERIFICATION_FAILED,
                        "Signature verification failed for sku " + sku);
                if (mPurchaseListener != null)
                    mPurchaseListener.onIabPurchaseFinished(result, purchase);
                return true;
            }
            logDebug("Purchase signature successfully verified.");
        } catch (JSONException e) {
            logError("Failed to parse purchase data.");
            e.printStackTrace();
            result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
            if (mPurchaseListener != null)
                mPurchaseListener.onIabPurchaseFinished(result, null);
            return true;
        }

        if (mPurchaseListener != null) {
            mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"),
                    purchase);
        }
    } else if (resultCode == Activity.RESULT_OK) {
        // result code was OK, but in-app billing response was not OK.
        logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode));
        if (mPurchaseListener != null) {
            result = new IabResult(responseCode, "Problem purchashing item.");
            mPurchaseListener.onIabPurchaseFinished(result, null);
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode));
        result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled.");
        if (mPurchaseListener != null)
            mPurchaseListener.onIabPurchaseFinished(result, null);
    } else {
        logError("Purchase failed. Result code: " + Integer.toString(resultCode) + ". Response: "
                + getResponseDesc(responseCode));
        result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response.");
        if (mPurchaseListener != null)
            mPurchaseListener.onIabPurchaseFinished(result, null);
    }
    return true;
}

From source file:org.digitalcampus.oppia.application.Tracker.java

public void saveTracker(int courseId, String digest, JSONObject data, boolean completed) {
    // add tracker UUID
    UUID guid = java.util.UUID.randomUUID();
    try {/*from  w  ww.j ava2  s . c  o  m*/
        data.put("uuid", guid.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    DbHelper db = new DbHelper(this.ctx);
    db.insertTracker(courseId, digest, data.toString(), completed);
    DatabaseManager.getInstance().closeDatabase();

}

From source file:edu.msu.walajahi.sunshine.app.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  www  .j  av a2 s  .  c o  m*/
 */
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) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            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:ru.neverdark.phototools.utils.Geocoder.java

/**
 * Gets coordinate from location name/*  ww w.j av a2 s . c  om*/
 * 
 * @param searchString
 *            user specify location name
 * @return coordinates for founded location or null if not found
 */
public LatLng getFromLocation(String searchString) {
    LatLng coords = null;
    String locationInfo = getLocationInfo(searchString);

    if (locationInfo.length() > 0) {
        try {
            JSONObject jsonObject = new JSONObject(locationInfo);
            JSONArray jsonArray = (JSONArray) jsonObject.get("results");
            JSONObject jsonLocation = jsonArray.getJSONObject(0).getJSONObject("geometry")
                    .getJSONObject("location");
            Double longitude = jsonLocation.getDouble("lng");
            Double latitude = jsonLocation.getDouble("lat");

            coords = new LatLng(latitude, longitude);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return coords;
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFlipperFragment.java

private void swipe(final int direction) {
    mHandler.post(new Runnable() {
        @Override/*from  ww  w. j a v  a2  s.co m*/
        public void run() {
            JSONObject jsonObj = new JSONObject();
            try {
                jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeEvent);
                if (direction == GESTURE_SWIPE_LEFT) {
                    jsonObj.put(Cobalt.kJSEvent, JSEventSwipeLeft);
                    if (Cobalt.DEBUG)
                        Log.i(Cobalt.TAG, TAG + " - swipe: next");
                } else if (direction == GESTURE_SWIPE_RIGHT) {
                    jsonObj.put(Cobalt.kJSEvent, JSEventSwipeRight);
                    if (Cobalt.DEBUG)
                        Log.i(Cobalt.TAG, TAG + " - swipe: previous");
                }
                sendMessage(jsonObj);
            } catch (JSONException exception) {
                exception.printStackTrace();
            }
        }
    });
}

From source file:com.orange.oidc.secproxy_service.Token.java

void setField(String name, Object object) {
    if (name == null || name.length() == 0)
        return;//from   w w w  .  java  2s .c  o m

    if (name.compareTo("iss") == 0) {
        iss = (String) object;
    } else if (name.compareTo("sub") == 0) {
        sub = (String) object;
    } else if (name.compareTo("aud") == 0) {
        JSONArray jArray = (JSONArray) object;
        aud = "";
        for (int i = 0; i < jArray.length(); i++) {
            try {
                aud += jArray.getString(i) + " ";
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else if (name.compareTo("jti") == 0) {
        jti = (String) object;
    } else if (name.compareTo("exp") == 0) {
        exp = getIntAsString(object);
    } else if (name.compareTo("iat") == 0) {
        iat = getIntAsString(object);
    } else if (name.compareTo("auth_time") == 0) {
        auth_time = getIntAsString(object);
    } else if (name.compareTo("nonce") == 0) {
        nonce = (String) object;
    } else if (name.compareTo("at_hash") == 0) {
        at_hash = (String) object;
    } else if (name.compareTo("acr") == 0) {
        acr = (String) object;
    } else if (name.compareTo("amr") == 0) {
        amr = (String) object;
    } else if (name.compareTo("azp") == 0) {
        azp = (String) object;
    } else if (name.compareTo("tim_app_key") == 0) {
        tak = (String) object;
    }
}

From source file:cz.muni.fi.japanesedictionary.entity.JapaneseCharacter.java

/**
 * Universal privatemethod for parsing JSON array.
 * //w  w  w  .  ja  v  a2s . c o  m
 * @param sense - JSONArray to be parsed
 */
private List<String> parseOneJSONArray(JSONArray sense) {
    if (sense == null) {
        return null;
    }
    List<String> temp = new ArrayList<>();
    for (int k = 0; k < sense.length(); k++) {
        String value;
        try {
            value = sense.getString(k);
            temp.add(value);
        } catch (JSONException e) {
            Log.w(LOG_TAG, "getting parseOneSense() expression failed: " + e.toString());
            e.printStackTrace();
        }
    }
    return temp;
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get Long from jsonObject/* ww  w  .  j  av a 2  s  .c  o m*/
 *
 * @param jsonObject
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if key is null or empty, return defaultValue</li>
 * <li>if {@link JSONObject#getLong(String)} exception, return defaultValue</li>
 * <li>return {@link JSONObject#getLong(String)}</li>
 * </ul>
 */
public static Long getLong(JSONObject jsonObject, String key, Long defaultValue) {
    if (jsonObject == null || StringUtils.isEmpty(key)) {
        return defaultValue;
    }

    try {
        return jsonObject.getLong(key);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get Long from jsonData//from w  w  w .  j av a  2 s  .  c  o  m
 *
 * @param jsonData
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li>
 * <li>return {@link JSONUtils#getLong(JSONObject, String, Long)}</li>
 * </ul>
 */
public static Long getLong(String jsonData, String key, Long defaultValue) {
    if (StringUtils.isEmpty(jsonData)) {
        return defaultValue;
    }

    try {
        JSONObject jsonObject = new JSONObject(jsonData);
        return getLong(jsonObject, key, defaultValue);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}