Example usage for org.json JSONException toString

List of usage examples for org.json JSONException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.vufind.MaterialsRequest.java

/**
 * If a title has been added to the catalog, add 
 *//*from w  w w.  j  av a2 s . c o  m*/
private void generateHolds() {
    processLog.addNote("Generating holds for materials requests that have arrived");
    //Get a list of requests to generate holds for
    try {
        PreparedStatement requestsToEmailStmt = vufindConn.prepareStatement(
                "SELECT materials_request.*, cat_username, cat_password FROM materials_request inner join user on user.id = materials_request.createdBy WHERE placeHoldWhenAvailable = 1 and holdsCreated = 0 and status IN ('owned', 'purchased')");
        PreparedStatement setHoldsCreatedStmt = vufindConn
                .prepareStatement("UPDATE materials_request SET holdsCreated=1 where id =?");
        ResultSet requestsToCreateHolds = requestsToEmailStmt.executeQuery();
        //For each request, 
        while (requestsToCreateHolds.next()) {
            boolean holdCreated = false;
            //Check to see if the title has been received based on the ISBN or OCLC Number
            String requestId = requestsToCreateHolds.getString("id");
            String requestIsbn = requestsToCreateHolds.getString("isbn");
            String requestIssn = requestsToCreateHolds.getString("issn");
            String requestUpc = requestsToCreateHolds.getString("upc");
            String requestOclcNumber = requestsToCreateHolds.getString("oclcNumber");
            String holdPickupLocation = requestsToCreateHolds.getString("holdPickupLocation");
            String cat_username = requestsToCreateHolds.getString("cat_username");
            String cat_password = requestsToCreateHolds.getString("cat_password");

            String recordId = null;
            //Search for the isbn 
            if ((requestIsbn != null && requestIsbn.length() > 0)
                    || (requestIssn != null && requestIssn.length() > 0)
                    || (requestUpc != null && requestUpc.length() > 0)
                    || (requestOclcNumber != null && requestOclcNumber.length() > 0)) {
                URL searchUrl;
                if (requestIsbn != null && requestIsbn.length() > 0) {
                    searchUrl = new URL(
                            vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestIsbn + "&type=isn");
                } else if (requestIssn != null && requestIssn.length() > 0) {
                    searchUrl = new URL(
                            vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestIssn + "&type=isn");
                } else if (requestUpc != null && requestUpc.length() > 0) {
                    searchUrl = new URL(
                            vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestUpc + "&type=isn");
                } else {
                    searchUrl = new URL(vufindUrl + "/API/SearchAPI?method=search&lookfor=oclc"
                            + requestOclcNumber + "&type=allfields");
                }
                Object searchDataRaw = searchUrl.getContent();
                if (searchDataRaw instanceof InputStream) {
                    String searchDataJson = Util.convertStreamToString((InputStream) searchDataRaw);
                    try {
                        JSONObject searchData = new JSONObject(searchDataJson);
                        JSONObject result = searchData.getJSONObject("result");
                        if (result.getInt("recordCount") > 0) {
                            //Found a record
                            JSONArray recordSet = result.getJSONArray("recordSet");
                            JSONObject firstRecord = recordSet.getJSONObject(0);
                            recordId = firstRecord.getString("id");
                        }
                    } catch (JSONException e) {
                        logger.error("Unable to load search result", e);
                        processLog.incErrors();
                        processLog.addNote("Unable to load search result " + e.toString());
                    }
                } else {
                    logger.error("Error searching for isbn " + requestIsbn);
                    processLog.incErrors();
                    processLog.addNote("Error searching for isbn " + requestIsbn);
                }
            }

            if (recordId != null) {
                //Place a hold on the title for the user
                URL placeHoldUrl;
                if (recordId.matches("econtentRecord\\d+")) {
                    placeHoldUrl = new URL(vufindUrl + "/API/UserAPI?method=placeEContentHold&username="
                            + cat_username + "&password=" + cat_password + "&recordId=" + recordId);
                } else {
                    placeHoldUrl = new URL(
                            vufindUrl + "/API/UserAPI?method=placeHold&username=" + cat_username + "&password="
                                    + cat_password + "&bibId=" + recordId + "&campus=" + holdPickupLocation);
                }
                logger.info("Place Hold URL: " + placeHoldUrl);
                Object placeHoldDataRaw = placeHoldUrl.getContent();
                if (placeHoldDataRaw instanceof InputStream) {
                    String placeHoldDataJson = Util.convertStreamToString((InputStream) placeHoldDataRaw);
                    try {
                        JSONObject placeHoldData = new JSONObject(placeHoldDataJson);
                        JSONObject result = placeHoldData.getJSONObject("result");
                        holdCreated = result.getBoolean("success");
                        if (holdCreated) {
                            logger.info("hold was created successfully.");
                            processLog.incUpdated();
                        } else {
                            logger.info("hold could not be created " + result.getString("holdMessage"));
                            processLog.incErrors();
                            processLog.addNote("hold could not be created " + result.getString("holdMessage"));
                        }
                    } catch (JSONException e) {
                        logger.error("Unable to load results of placing the hold", e);
                        processLog.incErrors();
                        processLog.addNote("Unable to load results of placing the hold " + e.toString());
                    }
                }
            }

            if (holdCreated) {
                //Mark that the hold was created
                setHoldsCreatedStmt.setString(1, requestId);
                setHoldsCreatedStmt.executeUpdate();
            }
        }

    } catch (Exception e) {
        logger.error("Error generating holds for purchased requests ", e);
        processLog.incErrors();
        processLog.addNote("Error generating holds for purchased requests " + e.toString());
    }
}

From source file:com.projectgoth.mywebrtcdemo.RoomParametersFetcher.java

private void roomHttpResponseParse(String response) {
    Log.d(TAG, "Room response: " + response);
    try {//from  w ww. jav a2  s  .c  om
        LinkedList<IceCandidate> iceCandidates = null;
        SessionDescription offerSdp = null;
        JSONObject roomJson = new JSONObject(response);

        String result = roomJson.getString("result");
        if (!result.equals("SUCCESS")) {
            events.onSignalingParametersError("Room response error: " + result);
            return;
        }
        response = roomJson.getString("params");
        roomJson = new JSONObject(response);
        String roomId = roomJson.getString("room_id");
        String clientId = roomJson.getString("client_id");
        String wssUrl = roomJson.getString("wss_url");
        String wssPostUrl = roomJson.getString("wss_post_url");
        boolean initiator = (roomJson.getBoolean("is_initiator"));
        if (!initiator) {
            iceCandidates = new LinkedList<IceCandidate>();
            String messagesString = roomJson.getString("messages");
            JSONArray messages = new JSONArray(messagesString);
            for (int i = 0; i < messages.length(); ++i) {
                String messageString = messages.getString(i);
                JSONObject message = new JSONObject(messageString);
                String messageType = message.getString("type");
                Log.d(TAG, "GAE->C #" + i + " : " + messageString);
                if (messageType.equals("offer")) {
                    offerSdp = new SessionDescription(SessionDescription.Type.fromCanonicalForm(messageType),
                            message.getString("sdp"));
                } else if (messageType.equals("candidate")) {
                    IceCandidate candidate = new IceCandidate(message.getString("id"), message.getInt("label"),
                            message.getString("candidate"));
                    iceCandidates.add(candidate);
                } else {
                    Log.e(TAG, "Unknown message: " + messageString);
                }
            }
        }
        Log.d(TAG, "RoomId: " + roomId + ". ClientId: " + clientId);
        Log.d(TAG, "Initiator: " + initiator);
        Log.d(TAG, "WSS url: " + wssUrl);
        Log.d(TAG, "WSS POST url: " + wssPostUrl);

        LinkedList<PeerConnection.IceServer> iceServers = iceServersFromPCConfigJSON(
                roomJson.getString("pc_config"));
        boolean isTurnPresent = false;
        for (PeerConnection.IceServer server : iceServers) {
            Log.d(TAG, "IceServer: " + server);
            if (server.uri.startsWith("turn:")) {
                isTurnPresent = true;
                break;
            }
        }
        // Request TURN servers.
        if (!isTurnPresent) {
            LinkedList<PeerConnection.IceServer> turnServers = requestTurnServers(
                    roomJson.getString("turn_url"));
            for (PeerConnection.IceServer turnServer : turnServers) {
                Log.d(TAG, "TurnServer: " + turnServer);
                iceServers.add(turnServer);
            }
        }

        SignalingParameters params = new SignalingParameters(iceServers, initiator, clientId, wssUrl,
                wssPostUrl, offerSdp, iceCandidates);
        events.onSignalingParametersReady(params);
    } catch (JSONException e) {
        events.onSignalingParametersError("Room JSON parsing error: " + e.toString());
    } catch (IOException e) {
        events.onSignalingParametersError("Room IO error: " + e.toString());
    }
}

From source file:com.intellisol.plugin.Wallpaper.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {/*from  w  ww . j av  a 2s . com*/
        // get path from argument
        String path = args.getString(0);

        // get context (Android)
        Context ctxt = cordova.getActivity().getBaseContext();
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(ctxt);

        // get image file
        InputStream bitmapIn = cordova.getActivity().getAssets().open(path);
        Bitmap bitmap = BitmapFactory.decodeStream(bitmapIn);

        // set wallpaper
        wallpaperManager.setBitmap(bitmap);

    } catch (JSONException e) {
        // log error
        Log.d("Wallpaper", e.toString());
        return false;
    } catch (Exception e) {
        // log error
        Log.d("Wallpaper", e.toString());
        return false;
    }
    return true;
}

From source file:com.facebook.stetho.inspector.ChromeDiscoveryHandler.java

@Override
protected void handleSecured(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    Uri uri = Uri.parse(request.getRequestLine().getUri());
    String path = uri.getPath();//from   w w w.ja va2  s.  co  m
    try {
        if (PATH_VERSION.equals(path)) {
            handleVersion(response);
        } else if (PATH_PAGE_LIST.equals(path)) {
            handlePageList(response);
        } else if (PATH_ACTIVATE.equals(path)) {
            handleActivate(response);
        } else {
            response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
            response.setReasonPhrase("Not Implemented");
            response.setEntity(new StringEntity("No support for " + uri.getPath()));
        }
    } catch (JSONException e) {
        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        response.setReasonPhrase("Internal Server Error");
        response.setEntity(new StringEntity(e.toString(), Utf8Charset.NAME));
    }
}

From source file:com.pinplanet.pintact.GcmIntentService.java

private void sendNotification(String msg, String customData) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    String type = null;//from www .j  a v  a  2s.  c o  m
    if (customData != null) {

        customData = customData.replace("\"{", "{");
        customData = customData.replaceFirst(Pattern.quote("}\""), "}");
        Log.d(TAG, "CustomData2: " + customData);
    }
    try {
        JSONObject jsonObject = new JSONObject(customData);
        Log.d(TAG, "jsonObject: " + jsonObject.toString());
        type = jsonObject.getString("type");
        switch (type) {
        case "NEW_CHAT_MESSAGE":
            if (customData != null) {
                sendChatNotification(customData);
            }
            break;
        default:
            sendDefaultNotification();
            break;
        }
    } catch (JSONException e) {
        Log.d(TAG, "JSONException in GcmIntentService: " + e.toString());
        e.printStackTrace();
    }

    //        Intent it = new Intent(this, GroupContactsActivity.class);
    //        //it.putExtra(LeftDeckActivity.SELECTED_OPTIONS, LeftDeckActivity.OPTION_NOTIFY);
    //        // add the following line would show Pintact to the preview page.
    //        // it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    //        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_CANCEL_CURRENT);
    //
    //        NotificationCompat.Builder mBuilder =
    //                new NotificationCompat.Builder(this)
    //                        .setSmallIcon(R.drawable.ic_launcher)
    //                        .setContentTitle("Pintact Update")
    //                        .setStyle(new NotificationCompat.BigTextStyle()
    //                                .bigText(msg))
    //                        .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
    //                        .setContentText(msg);
    //
    //        mBuilder.setContentIntent(contentIntent);
    //        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    //        SingletonLoginData.getInstance().mNotificationManager = mNotificationManager;
}

From source file:com.pinplanet.pintact.GcmIntentService.java

private void sendChatNotification(String customData) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    JSONObject jsonObject = null;/*from w  ww  .  ja  v a2  s .co m*/
    JSONObject chatObject = null;
    GroupDTO groupDTO = new GroupDTO();
    String chatMessage = "New Chat Message";
    String groupId = "";
    try {
        jsonObject = new JSONObject(customData);
        Log.d(TAG, "groupId: " + jsonObject.getString("groupId"));
        groupId = jsonObject.getString("groupId");
        groupDTO.setId(jsonObject.getString("groupId"));
        SingletonLoginData.getInstance().setCurGroup(groupDTO);
        Log.d(TAG, "message: " + jsonObject.getString("message"));
        chatObject = jsonObject.getJSONObject("message");
        chatMessage = chatObject.getString("content");
    } catch (JSONException e) {
        Log.d(TAG, "sendChatNotification error: " + e.toString());
        e.printStackTrace();
    }
    //Intent it = new Intent(this, PushNotificationActivity.class);
    Intent it = new Intent(this, GroupContactsActivity.class);

    it.putExtra("groupId", groupId);
    it.putExtra("OpenThreads", true);
    //it.putExtra(LeftDeckActivity.SELECTED_OPTIONS, LeftDeckActivity.OPTION_NOTIFY);
    // add the following line would show Pintact to the preview page.
    // it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("New Message")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(chatMessage))
            .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }).setAutoCancel(true)
            .setContentText(chatMessage);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    SingletonLoginData.getInstance().mNotificationManager = mNotificationManager;
}

From source file:com.piusvelte.sonet.core.SonetCreatePost.java

private void setLocation(final long accountId) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {

        int serviceId;

        @Override/*from w ww. j  a  va2 s  .co m*/
        protected String doInBackground(Void... none) {
            Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET },
                    Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
            if (account.moveToFirst()) {
                SonetOAuth sonetOAuth;
                serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE));
                switch (serviceId) {
                case TWITTER:
                    // anonymous requests are rate limited to 150 per hour
                    // authenticated requests are rate limited to 350 per hour, so authenticate this!
                    sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
                    return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong))));
                case FACEBOOK:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH,
                            FACEBOOK_BASE_URL, mLat, mLong, Saccess_token,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                case FOURSQUARE:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(
                            FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                }
            }
            account.close();
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (response != null) {
                switch (serviceId) {
                case TWITTER:
                    try {
                        JSONArray places = new JSONObject(response).getJSONObject(Sresult)
                                .getJSONArray(Splaces);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sfull_name);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FACEBOOK:
                    try {
                        JSONArray places = new JSONObject(response).getJSONArray(Sdata);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sname);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FOURSQUARE:
                    try {
                        JSONArray groups = new JSONObject(response).getJSONObject(Sresponse)
                                .getJSONArray(Sgroups);
                        for (int g = 0, g2 = groups.length(); g < g2; g++) {
                            JSONObject group = groups.getJSONObject(g);
                            if (group.getString(Sname).equals(SNearby)) {
                                JSONArray places = group.getJSONArray(Sitems);
                                final String placesNames[] = new String[places.length()];
                                final String placesIds[] = new String[places.length()];
                                for (int i = 0, i2 = places.length(); i < i2; i++) {
                                    JSONObject place = places.getJSONObject(i);
                                    placesNames[i] = place.getString(Sname);
                                    placesIds[i] = place.getString(Sid);
                                }
                                mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                        .setSingleChoiceItems(placesNames, -1,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        mAccountsLocation.put(accountId, placesIds[which]);
                                                        dialog.dismiss();
                                                    }
                                                })
                                        .setNegativeButton(android.R.string.cancel,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .create();
                                mDialog.show();
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                }
            } else {
                (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show();
            }
        }

    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute();
}

From source file:run.ace.OutgoingMessages.java

static void send(Object[] data) {
    PluginResult r = null;/*  w  ww  . ja  va  2 s.  co m*/
    try {
        r = new PluginResult(PluginResult.Status.OK, new JSONArray(data));
    } catch (JSONException ex) {
        r = new PluginResult(PluginResult.Status.ERROR,
                "Could not send back native data " + data + ": " + ex.toString());
    }
    r.setKeepCallback(true);
    _callbackContext.sendPluginResult(r);
}

From source file:com.evothings.BLE.java

public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
    if (mScanCallbackContext == null) {
        return;//from ww  w  . j  ava 2s .  co m
    }
    try {
        //System.out.println("onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
        JSONObject o = new JSONObject();
        o.put("address", device.getAddress());
        o.put("rssi", rssi);
        o.put("name", device.getName());
        o.put("scanRecord", Base64.encodeToString(scanRecord, Base64.NO_WRAP));
        keepCallback(mScanCallbackContext, o);
    } catch (JSONException e) {
        mScanCallbackContext.error(e.toString());
    }
}

From source file:com.evothings.BLE.java

private void close(final CordovaArgs args, final CallbackContext callbackContext) {
    try {//from  w ww . j ava 2s.c  o  m
        GattHandler gh = mGatt.get(args.getInt(0));
        gh.mGatt.close();
        mGatt.remove(args.getInt(0));
    } catch (JSONException e) {
        e.printStackTrace();
        callbackContext.error(e.toString());
    }
}