Example usage for org.json JSONException getLocalizedMessage

List of usage examples for org.json JSONException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 */// www .  j  ava  2s  .com
public String getRemoteLoyaltyCards() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                LoyaltyCard.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE,
                                "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        LoyaltyCard loyaltyCard = LoyaltyCard
                                .getByRemoteId(loyaltyCardJson.get("_id").toString());
                        if (loyaltyCard == null) {
                            loyaltyCard = new LoyaltyCard(loyaltyCardJson);
                        } else {
                            loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id"));
                            loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue"));
                            loyaltyCard.setCode(loyaltyCardJson.getInt("code"));
                            loyaltyCard.setLabel(loyaltyCardJson.getString("label"));
                            loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate"));
                        }

                        loyaltyCard.save();
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Fetch user details//from   www . j  a v a  2  s.  c  o  m
 * @param args
 * @param callbackContext
 */
protected void fetchUserDetails(JSONArray args, final CallbackContext callbackContext) {
    Log.d(TAG, "FETCHUSERDETAILS");
    Notificare.shared().fetchUserDetails(new NotificareCallback<NotificareUser>() {

        @Override
        public void onSuccess(NotificareUser result) {
            if (callbackContext == null) {
                return;
            }
            try {
                callbackContext.success(result.toJSONObject());
            } catch (JSONException error) {
                callbackContext.error(error.getLocalizedMessage());
            }
        }

        @Override
        public void onError(NotificareError error) {
            if (callbackContext == null) {
                return;
            }
            callbackContext.error(error.getLocalizedMessage());
        }
    });
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Generate access token//from   ww w . j  a  v  a2  s  . c o m
 * @param args
 * @param callbackContext
 */
protected void generateAccessToken(JSONArray args, final CallbackContext callbackContext) {
    Log.d(TAG, "GENERATEACCESSTOKEN");
    Notificare.shared().generateAccessToken(new NotificareCallback<NotificareUser>() {

        @Override
        public void onSuccess(NotificareUser result) {
            if (callbackContext == null) {
                return;
            }
            try {
                callbackContext.success(result.toJSONObject());
            } catch (JSONException error) {
                callbackContext.error(error.getLocalizedMessage());
            }
        }

        @Override
        public void onError(NotificareError error) {
            if (callbackContext == null) {
                return;
            }
            callbackContext.error(error.getLocalizedMessage());
        }
    });
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

private void postHistoryItemToServer(HistoryData hd, HistoryData from, Context context) {
    if (PreferenceManager.getDefaultSharedPreferences(context).contains("auth_token")) {
        String authToken = PreferenceManager.getDefaultSharedPreferences(context).getString("auth_token", "");
        final JSONObject postObject = new JSONObject();
        try {/*ww  w  .  ja  v a2  s . c o m*/
            postObject.put("auth_token", authToken);
            JSONObject routeObject = new JSONObject();
            if (from.getName() == null || from.getName().trim().equals("")) {
                from.setName(IbikeApplication.getString("current_position"));
            }
            routeObject.put("from_name", from.getName());
            routeObject.put("from_lattitude", from.getLatitude());
            routeObject.put("from_longitude", from.getLongitude());
            routeObject.put("to_name", hd.getName());
            routeObject.put("to_lattitude", hd.getLatitude());
            routeObject.put("to_longitude", hd.getLongitude());
            routeObject.put("start_date",
                    DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
            postObject.put("route", routeObject);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    LOG.d("Server request: " + Config.serverUrl + "/routes");
                    HttpUtils.postToServer(Config.serverUrl + "/routes", postObject);
                }
            });
            thread.start();
        } catch (JSONException e) {
            LOG.e(e.getLocalizedMessage());
        }
    }

}

From source file:com.spoiledmilk.ibikecph.util.DB.java

private void updateFavoriteToServer(final FavoritesData fd, Context context, final APIListener listener) {

    if (IbikeApplication.isUserLogedIn()) {
        String authToken = IbikeApplication.getAuthToken();
        final JSONObject postObject = new JSONObject();
        try {//from w  ww  .  j  a  v  a2 s  .  c o  m
            JSONObject favouriteObject = new JSONObject();
            favouriteObject.put("name", fd.getName());
            favouriteObject.put("address", fd.getAdress());
            favouriteObject.put("lattitude", fd.getLatitude());
            favouriteObject.put("longitude", fd.getLongitude());
            favouriteObject.put("source", fd.getSource());
            favouriteObject.put("sub_source", fd.getSubSource());
            postObject.put("favourite", favouriteObject);
            postObject.put("auth_token", authToken);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    JsonNode node = HttpUtils.putToServer(Config.serverUrl + "/favourites/" + fd.getApiId(),
                            postObject);
                    if (listener != null) {
                        boolean success = false;
                        if (node != null && node.has("success") && node.get("success").asBoolean()) {
                            success = true;
                        }
                        listener.onRequestCompleted(success);
                    }
                }
            });
            thread.start();
        } catch (JSONException e) {
            LOG.e(e.getLocalizedMessage());
        }
    }
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

public void deleteFavoriteFromServer(final FavoritesData fd, Context context) {
    if (IbikeApplication.isUserLogedIn()) {
        String authToken = IbikeApplication.getAuthToken();
        final JSONObject postObject = new JSONObject();
        try {//from  ww w  .  j a v  a  2 s.co  m
            postObject.put("auth_token", authToken);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpUtils.deleteFromServer(Config.serverUrl + "/favourites/" + fd.getApiId(), postObject);
                }
            });
            thread.start();
        } catch (JSONException e) {
            LOG.e(e.getLocalizedMessage());
        }
    }
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

public void saveFinishedRoute(Location startLocation, Location endLocation, String startName, String endName,
        String startDate, String endDate, String visitedLocations) {
    if (IbikeApplication.isUserLogedIn()) {
        String authToken = IbikeApplication.getAuthToken();
        final JSONObject postObject = new JSONObject();
        try {/*from   ww w . j a  v a2 s .  com*/
            postObject.put("auth_token", authToken);
            JSONObject routeObject = new JSONObject();
            routeObject.put("from_name", startName);
            routeObject.put("from_lattitude", startLocation.getLatitude());
            routeObject.put("from_longitude", startLocation.getLongitude());
            routeObject.put("to_name", endName);
            routeObject.put("to_lattitude", endLocation.getLatitude());
            routeObject.put("to_longitude", endLocation.getLongitude());
            routeObject.put("start_date", startDate);
            routeObject.put("end_date", endDate);
            routeObject.put("route_visited_locations", visitedLocations);
            routeObject.put("is_finished", true);
            postObject.put("route", routeObject);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpUtils.postToServer(Config.serverUrl + "/routes", postObject);
                }
            }).start();

        } catch (JSONException e) {
            LOG.e(e.getLocalizedMessage());
        }
    }

}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *///from   w w w . ja va2s  .  c  om
public String getRemoteExpenses() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored."));
                Expense.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE,
                                "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString());
                        if (expense == null) {
                            expense = new Expense(expenseJson);
                        } else {
                            expense.setRemoteId(expenseJson.getString("_id"));
                            expense.setAmount(expenseJson.getDouble("amount"));
                            expense.setCategory(expenseJson.getString("category"));
                            expense.setDate(expenseJson.getString("date"));

                            if (expenseJson.has("deviceId")) {
                                expense.setDeviceId(expenseJson.getString("deviceId"));
                            } else {
                                expense.setDeviceId(Device.registeredDevice().getLogin());
                            }
                        }
                        expense.save();

                        if (expenseJson.has("receipts")) {
                            JSONArray receiptsArray = expenseJson.getJSONArray("receipts");

                            for (int j = 0; j < receiptsArray.length(); j++) {
                                JSONObject recJsonObject = receiptsArray.getJSONObject(i);
                                Receipt receipt = new Receipt();
                                receipt.setBase64(recJsonObject.getString("base64"));
                                receipt.setExpense(expense);
                                receipt.setName("");
                                receipt.save();
                            }
                        }
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:com.facebook.share.ShareApi.java

private void stageArrayList(final ArrayList arrayList,
        final CollectionMapper.OnMapValueCompleteListener onArrayListStagedListener) {
    final JSONArray stagedObject = new JSONArray();
    final CollectionMapper.Collection<Integer> collection = new CollectionMapper.Collection<Integer>() {
        @Override//from  ww  w  .ja  v a  2s . c o m
        public Iterator<Integer> keyIterator() {
            final int size = arrayList.size();
            final Mutable<Integer> current = new Mutable<Integer>(0);
            return new Iterator<Integer>() {
                @Override
                public boolean hasNext() {
                    return current.value < size;
                }

                @Override
                public Integer next() {
                    return current.value++;
                }

                @Override
                public void remove() {
                }
            };
        }

        @Override
        public Object get(Integer key) {
            return arrayList.get(key);
        }

        @Override
        public void set(Integer key, Object value, CollectionMapper.OnErrorListener onErrorListener) {
            try {
                stagedObject.put(key, value);
            } catch (final JSONException ex) {
                String message = ex.getLocalizedMessage();
                if (message == null) {
                    message = "Error staging object.";
                }
                onErrorListener.onError(new FacebookException(message));
            }
        }
    };
    final CollectionMapper.OnMapperCompleteListener onStagedArrayMapperCompleteListener = new CollectionMapper.OnMapperCompleteListener() {
        @Override
        public void onComplete() {
            onArrayListStagedListener.onComplete(stagedObject);
        }

        @Override
        public void onError(FacebookException exception) {
            onArrayListStagedListener.onError(exception);
        }
    };
    stageCollectionValues(collection, onStagedArrayMapperCompleteListener);
}

From source file:com.facebook.share.ShareApi.java

private void stageOpenGraphObject(final ShareOpenGraphObject object,
        final CollectionMapper.OnMapValueCompleteListener onOpenGraphObjectStagedListener) {
    String type = object.getString("type");
    if (type == null) {
        type = object.getString("og:type");
    }// w  ww. j ava  2s  . c  o m

    if (type == null) {
        onOpenGraphObjectStagedListener
                .onError(new FacebookException("Open Graph objects must contain a type value."));
        return;
    }
    final JSONObject stagedObject = new JSONObject();
    final CollectionMapper.Collection<String> collection = new CollectionMapper.Collection<String>() {
        @Override
        public Iterator<String> keyIterator() {
            return object.keySet().iterator();
        }

        @Override
        public Object get(String key) {
            return object.get(key);
        }

        @Override
        public void set(String key, Object value, CollectionMapper.OnErrorListener onErrorListener) {
            try {
                stagedObject.put(key, value);
            } catch (final JSONException ex) {
                String message = ex.getLocalizedMessage();
                if (message == null) {
                    message = "Error staging object.";
                }
                onErrorListener.onError(new FacebookException(message));
            }
        }
    };
    final GraphRequest.Callback requestCallback = new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            final FacebookRequestError error = response.getError();
            if (error != null) {
                String message = error.getErrorMessage();
                if (message == null) {
                    message = "Error staging Open Graph object.";
                }
                onOpenGraphObjectStagedListener.onError(new FacebookGraphResponseException(response, message));
                return;
            }
            final JSONObject data = response.getJSONObject();
            if (data == null) {
                onOpenGraphObjectStagedListener.onError(
                        new FacebookGraphResponseException(response, "Error staging Open Graph object."));
                return;
            }
            final String stagedObjectId = data.optString("id");
            if (stagedObjectId == null) {
                onOpenGraphObjectStagedListener.onError(
                        new FacebookGraphResponseException(response, "Error staging Open Graph object."));
                return;
            }
            onOpenGraphObjectStagedListener.onComplete(stagedObjectId);
        }
    };
    final String ogType = type;
    final CollectionMapper.OnMapperCompleteListener onMapperCompleteListener = new CollectionMapper.OnMapperCompleteListener() {
        @Override
        public void onComplete() {
            final String objectString = stagedObject.toString();
            final Bundle parameters = new Bundle();
            parameters.putString("object", objectString);
            try {
                new GraphRequest(AccessToken.getCurrentAccessToken(),
                        getGraphPath("objects/" + URLEncoder.encode(ogType, DEFAULT_CHARSET)), parameters,
                        HttpMethod.POST, requestCallback).executeAsync();
            } catch (final UnsupportedEncodingException ex) {
                String message = ex.getLocalizedMessage();
                if (message == null) {
                    message = "Error staging Open Graph object.";
                }
                onOpenGraphObjectStagedListener.onError(new FacebookException(message));
            }
        }

        @Override
        public void onError(FacebookException exception) {
            onOpenGraphObjectStagedListener.onError(exception);
        }
    };
    stageCollectionValues(collection, onMapperCompleteListener);
}