Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

In this page you can find the example usage for org.json JSONObject getInt.

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

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

/**
 * get Int from jsonObject//from w w w. j  av  a 2 s . c om
 *
 * @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#getInt(String)} exception, return defaultValue</li>
 * <li>return {@link JSONObject#getInt(String)}</li>
 * </ul>
 */
public static Integer getInt(JSONObject jsonObject, String key, Integer defaultValue) {
    if (jsonObject == null || StringUtils.isEmpty(key)) {
        return defaultValue;
    }

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

From source file:org.openmidaas.library.authentication.AuthCallbackForAccessToken.java

private void obtainAccessToken(SubjectToken subjectToken, String deviceToken) throws JSONException {
    AVSServer.getAuthToken(subjectToken, deviceToken, new AsyncHttpResponseHandler() {
        @Override//w  ww. j a va2s  . c om
        public void onSuccess(String response) {
            if (response == null || response.isEmpty()) {
                MIDaaS.logError(TAG, "Server response is empty.");
                mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
            } else {
                try {
                    JSONObject accessToken = new JSONObject(response);
                    if ((accessToken.has(Constants.AccessTokenKeys.ACCESS_TOKEN)
                            && !(accessToken.isNull(Constants.AccessTokenKeys.ACCESS_TOKEN)))
                            && (accessToken.has(Constants.AccessTokenKeys.EXPIRES_IN)
                                    && !(accessToken.isNull(Constants.AccessTokenKeys.EXPIRES_IN)))) {
                        AccessToken token = AccessToken.createAccessToken(
                                accessToken.getString(Constants.AccessTokenKeys.ACCESS_TOKEN),
                                accessToken.getInt(Constants.AccessTokenKeys.EXPIRES_IN));
                        if (token != null) {
                            MIDaaS.logDebug(TAG, "got access token: ");
                            mCallback.onSuccess(token);
                        } else {
                            MIDaaS.logError(TAG, "Error could not create access token");
                            mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                        }
                    } else {
                        MIDaaS.logError(TAG, "Server response is not what is expected");
                        mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                    }

                } catch (JSONException e) {
                    MIDaaS.logError(TAG, "Internal error while parsing server JSON response");
                    mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                }

            }

        }

        @Override
        public void onFailure(Throwable e, String response) {
            MIDaaS.logError(TAG, "Server responded with error " + response);
            mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
        }
    });
}

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

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *///  ww  w  .  j  a v a2s  .co  m
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:com.norman0406.slimgress.API.Knobs.ScannerKnobs.java

public ScannerKnobs(JSONObject json) throws JSONException {
    super(json);/*from w w  w  . j a  va  2 s  .  c  o m*/

    mRangeM = json.getInt("rangeM");
    mUpdateDistanceM = json.getInt("updateDistanceM");
    mUpdateIntervalMS = json.getInt("updateIntervalMs");
}

From source file:org.openmidaas.library.authentication.AuthCallbackForRegistration.java

@Override
public void onSuccess(String deviceToken) {
    try {/*  w  w w  .  j  av  a2s . com*/
        AVSServer.registerDevice(deviceToken, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                if (response == null || response.isEmpty()) {
                    mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                } else {
                    try {
                        MIDaaS.logDebug(TAG, "device successfully registered. persisting registration.");
                        JSONObject responseObject = new JSONObject(response);
                        if (responseObject.has("subjectToken") && !(responseObject.isNull("subjectToken"))) {
                            SubjectToken subjectToken = SubjectTokenFactory.createAttribute();
                            subjectToken.setValue(Build.MODEL);
                            subjectToken.setSignedToken(responseObject.getString("subjectToken"));
                            subjectToken.save();
                            // if we didn't get the access token, we can get it on-demand at a later time. 
                            if ((responseObject.has(Constants.AccessTokenKeys.ACCESS_TOKEN)
                                    && !(responseObject.isNull(Constants.AccessTokenKeys.ACCESS_TOKEN)))
                                    && (responseObject.has(Constants.AccessTokenKeys.EXPIRES_IN)
                                            && !(responseObject
                                                    .isNull(Constants.AccessTokenKeys.EXPIRES_IN)))) {
                                MIDaaS.logDebug(TAG, "Registration response has an access token.");
                                AccessToken token = AccessToken.createAccessToken(
                                        responseObject.getString(Constants.AccessTokenKeys.ACCESS_TOKEN),
                                        responseObject.getInt(Constants.AccessTokenKeys.EXPIRES_IN));
                                if (token != null) {
                                    MIDaaS.logDebug(TAG, "Access token is ok.");
                                    AuthenticationManager.getInstance().setAccessToken(token);
                                } else {
                                    MIDaaS.logError(TAG, "Access token is null.");
                                    mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                                }
                            } else {
                                MIDaaS.logDebug(TAG,
                                        "No access token object in server response. Access token will be created on-demand.");
                            }
                        } else {
                            MIDaaS.logError(TAG, "Server response doesn't match expected response");
                            mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                        }
                        mInitCallback.onSuccess();
                    } catch (InvalidAttributeValueException e) {
                        // should never get here b/c we're returning true. 
                        MIDaaS.logError(TAG, "logic error. should never have thrown exception");
                    } catch (MIDaaSException e) {
                        MIDaaS.logError(TAG, e.getError().getErrorMessage());
                        mInitCallback.onError(e);

                    } catch (JSONException e) {
                        MIDaaS.logError(TAG, e.getMessage());
                        mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                    }
                }
            }

            @Override
            public void onFailure(Throwable e, String response) {
                MIDaaS.logError(TAG, response);
                mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
            }
        });
    } catch (JSONException e) {
        MIDaaS.logError(TAG, "Internal error");
        MIDaaS.logError(TAG, e.getMessage());
        mInitCallback.onError(null);
    }

}

From source file:net.jmhertlein.mcanalytics.console.gui.HostEntry.java

public static HostEntry fromJSON(JSONObject host) {
    return new HostEntry(host.getString("nick"), host.getString("url"), host.getInt("port"));
}

From source file:io.sponges.dubtrack4j.internal.subscription.callback.PlaylistUpdateCall.java

@Override
public void run(JSONObject json) throws IOException {
    int startTime = json.getInt("startTime");
    if (startTime != -1)
        return; // prevent double call

    JSONObject song = json.getJSONObject("song");
    JSONObject songInfo = json.getJSONObject("songInfo");

    String playlistId = song.getString("_id");
    String userId = song.getString("userid");
    String roomId = song.getString("roomid");
    long time = song.getLong("created");
    String songId = song.getString("songid");

    String songName = songInfo.getString("name");
    long songLength = songInfo.getLong("songLength");

    String sourceTypeId = songInfo.getString("type");
    SongInfo.SourceType sourceType = SongInfo.SourceType.valueOf(sourceTypeId.toUpperCase());
    String sourceId = songInfo.getString("fkid");

    RoomImpl room = dubtrack.loadRoom(roomId);
    User user = room.getOrLoadUser(userId);

    SongInfo sInfo = new SongInfo(songName, songLength, sourceType);
    if (sourceType == SongInfo.SourceType.YOUTUBE) {
        sInfo.setYoutubeId(sourceId);//from   w  w  w  .j av a  2 s  .  co  m
    } else {
        sInfo.setSoundcloudId(sourceId);
    }

    Song s = new SongImpl(dubtrack, songId, user, room, sInfo);

    Song previous = room.getCurrentSong();
    room.setCurrent(s);
    room.setPlaylistId(playlistId);
    room.getInternalRoomQueue().remove(previous);
    room.loadRoomQueue(); // updating the queue

    dubtrack.getEventBus().post(new SongChangeEvent(previous, s, room));
}

From source file:edu.cwru.apo.Home.java

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.phone) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    SharedPreferences.Editor editor = getSharedPreferences(APO.PREF_FILE_NAME, MODE_PRIVATE)
                            .edit();//from w w  w. j  av a 2  s.c o  m
                    editor.putLong("updateTime", result.getLong("updateTime"));
                    editor.commit();
                    int numbros = result.getInt("numBros");
                    JSONArray caseID = result.getJSONArray("caseID");
                    JSONArray first = result.getJSONArray("first");
                    JSONArray last = result.getJSONArray("last");
                    JSONArray phone = result.getJSONArray("phone");
                    JSONArray family = result.getJSONArray("family");
                    ContentValues values;
                    for (int i = 0; i < numbros; i++) {
                        values = new ContentValues();
                        values.put("_id", caseID.getString(i));
                        values.put("first", first.getString(i));
                        values.put("last", last.getString(i));
                        values.put("phone", phone.getString(i));
                        values.put("family", family.getString(i));
                        database.replace("phoneDB", null, values);
                    }
                } else if (requestStatus.compareTo("timestamp invalid") == 0) {
                    Toast msg = Toast.makeText(this, "Invalid timestamp.  Please try again.",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("HMAC invalid") == 0) {
                    Auth.loggedIn = false;
                    Toast msg = Toast.makeText(this,
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                    finish();
                } else {
                    Toast msg = Toast.makeText(this, "Invalid requestStatus", Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else if (method == Methods.checkAppVersion) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    String appVersion = result.getString("version");
                    String appDate = result.getString("date");
                    final String appUrl = result.getString("url");
                    PackageInfo pinfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
                    ;
                    if (appVersion.compareTo(pinfo.versionName) != 0) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("Upgrade");
                        builder.setMessage("Update available, ready to upgrade?");
                        builder.setIcon(R.drawable.icon);
                        builder.setCancelable(false);
                        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent promptInstall = new Intent("android.intent.action.VIEW",
                                        Uri.parse("https://apo.case.edu:8090/app/" + appUrl));
                                startActivity(promptInstall);
                            }
                        });
                        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    } else {
                        Toast msg = Toast.makeText(this, "No updates found", Toast.LENGTH_LONG);
                        msg.show();
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NameNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private void handleFeedResponse(JSONObject jsonResponse, FeedListener listener) {
    FbSimplePost post;/*w ww .ja  va  2  s .  c o  m*/
    ArrayList<FbSimplePost> posts = new ArrayList<FbSimplePost>();

    try {
        JSONArray objs = jsonResponse.getJSONArray("data");

        for (int i = 0; i < objs.length(); i++) {
            JSONObject obj = objs.getJSONObject(i);

            post = new FbSimplePost();
            post.setId(obj.getString("id"));

            JSONObject fromJson = obj.optJSONObject("from");
            if (fromJson != null) {
                FbSimpleUser from = new FbSimpleUser();
                from.setId(fromJson.getString("id"));
                from.setName(fromJson.getString("name"));

                post.setFrom(from);
            }

            post.setMessage(obj.optString("message"));
            post.setPicture(obj.optString("picture"));
            post.setLink(obj.optString("link"));
            post.setName(obj.optString("name"));
            post.setCaption(obj.optString("caption"));
            post.setDescription(obj.optString("description"));
            post.setSource(obj.optString("source"));
            post.setType(obj.optString("type"));

            post.setCreatedTime(new Date(obj.getLong("created_time")));
            post.setUpdatedTime(new Date(obj.getLong("updated_time")));

            JSONObject comments = obj.optJSONObject("comments");
            if (comments != null) {
                post.setNumberOfComments(comments.getInt("count"));
            }

            JSONObject likes = obj.optJSONObject("likes");
            if (likes != null) {
                post.setNumberOfLikes(likes.getInt("count"));
            }

            posts.add(post);
        }

        String nextPage = null;
        JSONObject paging = jsonResponse.optJSONObject("paging");
        if (paging != null) {
            nextPage = paging.optString("next");
        }

        listener.onComplete(posts, nextPage);

    } catch (JSONException e) {
        Util.logd(TAG, "Could not parse Json response", e);
        listener.onFail(e);
    }
}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private U2FContext parseU2FContextSign(JSONObject json) {
    try {//from w w w.  j  a v a2s.  c om
        String appId = json.getString(TAG_JSON_APPID);
        byte[] challenge = Base64.decode(json.getString(TAG_JSON_CHALLENGE), Base64.URL_SAFE);
        int requestId = json.getInt(TAG_JSON_REQUESTID);
        JSONArray array = json.getJSONArray(TAG_JSON_REGISTERED_KEYS);
        Vector<byte[]> keyHandles = new Vector<byte[]>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject keyHandleItem = array.getJSONObject(i);
            if (!keyHandleItem.getString(TAG_JSON_VERSION).equals(VERSION_U2F_V2)) {
                Log.e(TAG, "Invalid handle version");
                return null;
            }
            byte[] keyHandle = Base64.decode(keyHandleItem.getString(TAG_JSON_KEYHANDLE), Base64.URL_SAFE);
            keyHandles.add(keyHandle);
        }
        return new U2FContext(appId, challenge, keyHandles, requestId, true);
    } catch (JSONException e) {
        Log.e(TAG, "Error decoding request");
        return null;
    }
}