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.nit.vicky.multimediacard.activity.MultimediaCardEditorActivity.java

/**
 * Change current model for the Note. Changes both MultimediaNote and the mEditorNote (Note Object) and copies
 * existing values to both./*from ww  w.  j a v a2 s  .c  om*/
 * 
 * @param newId
 */
protected void changeCurrentModel(long newId) {
    try {
        JSONObject currentModel = mCol.getModels().get(newId);
        mCol.getModels().setCurrent(currentModel);
        JSONObject cdeck = mCol.getDecks().current();

        cdeck.put("mid", newId);

        mCol.getDecks().save(cdeck);
        int size = mNote.getNumberOfFields();
        String[] oldValues = new String[size];
        for (int i = 0; i < size; i++) {
            oldValues[i] = mNote.getField(i).getFormattedValue();
        }
        mEditorNote = new Note(mCol, currentModel);
        mEditorNote.model().put("did", mCurrentDid);

        MultimediaEditableNote newNote = NoteService.createEmptyNote(currentModel);
        for (int i = 0; i < newNote.getNumberOfFields(); i++) {
            if (i < mNote.getNumberOfFields()) {
                newNote.setField(i, mNote.getField(i));
            }
        }
        mNote = newNote;

    } catch (JSONException e) {
        Log.e("Multimedia Editor", e.getMessage());
    }

}

From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override/*from   w  w w . j  a v  a2  s  .  co  m*/
        public void run() {
            final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL);
            url.append("unspent-outputs");
            url.append("?per_page=MAX");
            for (final Address address : addresses)
                url.append("&address[]=").append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IllegalStateException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        if (jsonOutput.getInt("is_spent") != 0)
                            throw new IllegalStateException("UXTO not spent");

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script_pub_key"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

                if (connection != null)
                    connection.disconnect();
            }
        }
    });
}

From source file:tv.ouya.sample.game.OptionsActivity.java

private void requestPurchase(final Options.Level level)
        throws GeneralSecurityException, JSONException, UnsupportedEncodingException {
    final String productId = getProductIdForLevel(level);

    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", productId);
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);//from   ww w  .  ja  v a 2s  .c o m
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    mOuyaFacade.requestPurchase(purchasable, new OuyaResponseListener<String>() {
        @Override
        public void onSuccess(String result) {
            String responseProductId;
            try {
                OuyaEncryptionHelper helper = new OuyaEncryptionHelper();

                JSONObject response = new JSONObject(result);
                String responseUUID = helper.decryptPurchaseResponse(response, mPublicKey);
                synchronized (mOutstandingPurchaseRequests) {
                    responseProductId = mOutstandingPurchaseRequests.remove(responseUUID);
                }
                if (responseProductId == null || !responseProductId.equals(productId)) {
                    onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS,
                            "Purchased product is not the same as purchase request product", Bundle.EMPTY);
                    return;
                }
            } catch (JSONException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (ParseException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (IOException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (GeneralSecurityException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            }

            if (responseProductId.equals(getProductIdForLevel(level))) {
                setNeedsPurchaseText(levelToRadioButton.get(level), false);
                Toast.makeText(OptionsActivity.this, "Level purchased!", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(int errorCode, String errorMessage, Bundle optionalData) {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this,
                    "Error making purchase!\n\nError " + errorCode + "\n" + errorMessage + ")",
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancel() {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this, "You cancelled the purchase!", Toast.LENGTH_LONG).show();
        }
    });
}

From source file:org.jabsorb.serializer.AccessibleObjectResolver.java

/**
 * Creates a signature for an array of arguments
 *
 * @param arguments The argumnts/*  w  w w.jav  a 2  s  .  co  m*/
 * @return A comma seperated string listing the arguments
 */
private static String argSignature(JSONArray arguments) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < arguments.length(); i += 1) {
        if (i > 0) {
            buf.append(",");
        }
        Object jso;

        try {
            jso = arguments.get(i);
        } catch (JSONException e) {
            throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e);
        }

        if (jso == null) {
            buf.append("java.lang.Object");
        } else if (jso instanceof String) {
            buf.append("java.lang.String");
        } else if (jso instanceof Number) {
            buf.append("java.lang.Number");
        } else if (jso instanceof JSONArray) {
            buf.append("java.lang.Object[]");
        } else {
            buf.append("java.lang.Object");
        }
    }
    return buf.toString();
}

From source file:org.jabsorb.serializer.AccessibleObjectResolver.java

/**
 * Tries to unmarshall the arguments to a method
 *
 * @param accessibleObject The method/constructor to unmarshall the arguments
 *          for./*from   w  ww  . ja va2 s. co  m*/
 * @param arguments The arguments to unmarshall
 * @param parameterTypes The parameters of the method/construcot
 * @param serializer The main json serialiser.
 * @return The MethodCandidate that should suit the arguements and method.
 * @throws UnmarshallException If one of the arguments cannot be unmarshalled
 */
private static AccessibleObjectCandidate tryUnmarshallArgs(AccessibleObject accessibleObject,
        JSONArray arguments, Class[] parameterTypes, JSONSerializer serializer) throws UnmarshallException {
    int i = 0;
    ObjectMatch[] matches = new ObjectMatch[parameterTypes.length];
    try {
        int nonLocalArgIndex = 0;
        for (; i < parameterTypes.length; i++) {
            SerializerState serialiserState = new SerializerState();
            if (LocalArgController.isLocalArg(parameterTypes[i])) {
                // TODO: do this on the actual candidate?
                matches[i] = ObjectMatch.OKAY;
            } else {
                matches[i] = serializer.tryUnmarshall(serialiserState, parameterTypes[i],
                        arguments.get(nonLocalArgIndex++));
            }
        }
    } catch (JSONException e) {
        throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e);
    } catch (UnmarshallException e) {
        throw new UnmarshallException("arg " + (i + 1) + " " + e.getMessage(), e);
    }
    AccessibleObjectCandidate candidate = new AccessibleObjectCandidate(accessibleObject, parameterTypes,
            matches);

    return candidate;
}

From source file:org.jabsorb.serializer.AccessibleObjectResolver.java

/**
 * Convert the arguments to a method call from json into java objects to be
 * used for invoking the method, later.//  w  w  w  .  j  ava  2 s  .co  m
 *
 * @param context the context of the caller. This will be the servlet request
 *          and response objects in an http servlet call environment. These
 *          are used to insert local arguments (e.g. the request, response or
 *          session,etc.) when found in the java method call argument
 *          signature.
 * @param param the classes of the arguments to the function.
 * @param arguments the arguments from the caller, in json format.
 * @param serializer The main json serializer.
 * @return the java arguments as unmarshalled from json.
 * @throws UnmarshallException if there is a problem unmarshalling the
 *           arguments.
 */
private static Object[] unmarshallArgs(Object context[], Class[] param, JSONArray arguments,
        JSONSerializer serializer) throws UnmarshallException {
    Object javaArgs[] = new Object[param.length];
    int i = 0, j = 0;
    try {
        for (; i < param.length; i++) {
            SerializerState serializerState = new SerializerState();
            if (LocalArgController.isLocalArg(param[i])) {
                javaArgs[i] = LocalArgController.resolveLocalArg(context, param[i]);
            } else {
                javaArgs[i] = serializer.unmarshall(serializerState, param[i], arguments.get(j++));
            }
        }
    } catch (JSONException e) {
        throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e);
    } catch (UnmarshallException e) {
        throw new UnmarshallException("arg " + (i + 1) + " could not unmarshall", e);
    }

    return javaArgs;
}

From source file:com.msrproduction.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  w w w  . j  a  v a 2  s .  co 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) {
            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.hichinaschool.flashcards.libanki.Utils.java

/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(JSONArray ids) {
    StringBuilder str = new StringBuilder(512);
    str.append("(");
    if (ids != null) {
        int len = ids.length();
        for (int i = 0; i < len; i++) {
            try {
                if (i == (len - 1)) {
                    str.append(ids.get(i));
                } else {
                    str.append(ids.get(i)).append(",");
                }/*from  w ww.  j a  v a 2  s .  c  o  m*/
            } catch (JSONException e) {
                Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
            }
        }
    }
    str.append(")");
    return str.toString();
}

From source file:com.hichinaschool.flashcards.libanki.Utils.java

private static void printJSONObject(JSONObject jsonObject, String indentation, BufferedWriter buff) {
    try {/*from   w  ww  . j  av a2 s.co  m*/
        @SuppressWarnings("unchecked")
        Iterator<String> keys = (Iterator<String>) jsonObject.keys();
        TreeSet<String> orderedKeysSet = new TreeSet<String>();
        while (keys.hasNext()) {
            orderedKeysSet.add(keys.next());
        }

        Iterator<String> orderedKeys = orderedKeysSet.iterator();
        while (orderedKeys.hasNext()) {
            String key = orderedKeys.next();

            try {
                Object value = jsonObject.get(key);
                if (value instanceof JSONObject) {
                    if (buff != null) {
                        buff.write(indentation + " " + key + " : ");
                        buff.newLine();
                    }
                    // Log.i(AnkiDroidApp.TAG, "   " + indentation + key + " : ");
                    printJSONObject((JSONObject) value, indentation + "-", buff);
                } else {
                    if (buff != null) {
                        buff.write(indentation + " " + key + " = " + jsonObject.get(key).toString());
                        buff.newLine();
                    }
                    // Log.i(AnkiDroidApp.TAG, "   " + indentation + key + " = " + jsonObject.get(key).toString());
                }
            } catch (JSONException e) {
                Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
            }
        }
    } catch (IOException e1) {
        Log.e(AnkiDroidApp.TAG, "IOException = " + e1.getMessage());
    }
}

From source file:org.jbpm.designer.web.server.menu.connector.commands.AbstractCommand.java

public JSONObject listContent(IDiagramProfile profile, String target, String current, boolean tree)
        throws Exception {
    try {//from   w  ww .j a  v  a2s .  c o m
        if (target == null || target.length() < 1) {
            target = "/";
        } else if (!target.startsWith("/")) {
            target = "/" + target;
        }
        JSONObject retObj = new JSONObject();
        retObj.put("cwd", getCwd(profile, target, tree));
        retObj.put("cdc", getCdc(profile, target, tree));
        if (target == "/") {
            retObj.put("tree", getTree(profile, target, tree));
        }
        addParams(retObj);
        return retObj;
    } catch (JSONException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return new JSONObject();
    }
}