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:se.su.dsv.scipro.android.tasks.GetProjectsAsyncTask.java

@Override
protected ProjectsResult doInBackground(Void... params) {
    String response = SciProJSON.getInstance().getProjects();

    boolean authenticated = true;
    List<Project> projects = new ArrayList<Project>();

    try {/*w ww  .j  ava  2  s . co m*/
        JSONObject jsonObject = new JSONObject(response);
        if (!jsonObject.getString("apikey").equals("success")) {
            authenticated = false;
        } else {
            JSONArray projectsArray = jsonObject.getJSONArray("projectArray");
            for (int i = 0; i < projectsArray.length(); i++) {
                JSONObject currentObject = projectsArray.getJSONObject(i);

                String title = currentObject.getString("title");

                Project.STATUS status = Enum.valueOf(Project.STATUS.class, currentObject.getString("status"));

                String statusMessage = currentObject.getString("statusMessage");

                String level = currentObject.getString("level");

                List<User> projectMembers = new ArrayList<User>();
                JSONArray memberArray = currentObject.getJSONArray("projectMembers");
                for (int j = 0; j < memberArray.length(); j++) {
                    JSONObject member = memberArray.getJSONObject(j);
                    projectMembers.add(new User(member.getLong("id"), member.getString("name")));
                }
                DaoUtils.addUsersToApplication(projectMembers);

                List<User> projectReviewers = new ArrayList<User>();
                JSONArray reviewerArray = currentObject.getJSONArray("projectReviewers");
                for (int j = 0; j < reviewerArray.length(); j++) {
                    JSONObject reviewer = reviewerArray.getJSONObject(j);
                    projectReviewers.add(new User(reviewer.getLong("id"), reviewer.getString("name")));
                }
                DaoUtils.addUsersToApplication(projectReviewers);

                List<User> projectCoSupervisors = new ArrayList<User>();
                JSONArray coSuperVisorArray = currentObject.getJSONArray("projectCosupervisors");
                for (int j = 0; j < coSuperVisorArray.length(); j++) {
                    JSONObject coSupervisor = coSuperVisorArray.getJSONObject(j);
                    projectCoSupervisors
                            .add(new User(coSupervisor.getLong("id"), coSupervisor.getString("name")));
                }
                DaoUtils.addUsersToApplication(projectCoSupervisors);

                int projectProgress = currentObject.getInt("projectProgress");

                List<FinalSeminar> finalSeminars = new ArrayList<FinalSeminar>();
                JSONArray finalSeminarArray = currentObject.getJSONArray("finalSeminars");
                for (int j = 0; j < finalSeminarArray.length(); j++) {
                    JSONObject finalSeminar = finalSeminarArray.getJSONObject(j);
                    String room = finalSeminar.getString("room");
                    String date = finalSeminar.getString("date");

                    List<User> activeListeners = new ArrayList<User>();
                    JSONArray activeListenerArray = finalSeminar.getJSONArray("active");
                    for (int k = 0; k < activeListenerArray.length(); k++) {
                        JSONObject listener = activeListenerArray.getJSONObject(k);
                        activeListeners.add(new User(listener.getLong("id"), listener.getString("name")));
                    }
                    DaoUtils.addUsersToApplication(activeListeners);

                    List<User> opponents = new ArrayList<User>();
                    JSONArray opponentArray = finalSeminar.getJSONArray("opponents");
                    for (int k = 0; k < opponentArray.length(); k++) {
                        JSONObject opponent = opponentArray.getJSONObject(k);
                        opponents.add((new User(opponent.getLong("id"), opponent.getString("name"))));
                    }
                    DaoUtils.addUsersToApplication(opponents);

                    finalSeminars.add(new FinalSeminar(room, date, activeListeners, opponents));
                }

                Project project = new Project(title);
                project.status = status;
                project.statusMessage = statusMessage;
                project.level = level;
                project.projectMembers = projectMembers;
                project.projectCoSupervisors = projectCoSupervisors;
                project.projectReviewers = projectReviewers;
                project.projectProgress = projectProgress;
                project.finalSeminars = finalSeminars;

                projects.add(project);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException: ", e);
    }

    return new ProjectsResult(authenticated, projects);
}

From source file:net.dv8tion.jda.core.handle.GuildUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long id = content.getLong("id");
    if (api.getGuildLock().isLocked(id))
        return id;

    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);
    Member owner = guild.getMembersMap().get(content.getLong("owner_id"));
    String name = content.getString("name");
    String iconId = !content.isNull("icon") ? content.getString("icon") : null;
    String splashId = !content.isNull("splash") ? content.getString("splash") : null;
    Region region = Region.fromKey(content.getString("region"));
    Guild.VerificationLevel verificationLevel = Guild.VerificationLevel
            .fromKey(content.getInt("verification_level"));
    Guild.NotificationLevel notificationLevel = Guild.NotificationLevel
            .fromKey(content.getInt("default_message_notifications"));
    Guild.MFALevel mfaLevel = Guild.MFALevel.fromKey(content.getInt("mfa_level"));
    Guild.ExplicitContentLevel explicitContentLevel = Guild.ExplicitContentLevel
            .fromKey(content.getInt("explicit_content_filter"));
    Guild.Timeout afkTimeout = Guild.Timeout.fromKey(content.getInt("afk_timeout"));
    VoiceChannel afkChannel = !content.isNull("afk_channel_id")
            ? guild.getVoiceChannelMap().get(content.getLong("afk_channel_id"))
            : null;//  w  ww .  j  av  a2 s  .  c  o  m

    if (!Objects.equals(owner, guild.getOwner())) {
        Member oldOwner = guild.getOwner();
        guild.setOwner(owner);
        api.getEventManager().handle(new GuildUpdateOwnerEvent(api, responseNumber, guild, oldOwner));
    }
    if (!Objects.equals(name, guild.getName())) {
        String oldName = guild.getName();
        guild.setName(name);
        api.getEventManager().handle(new GuildUpdateNameEvent(api, responseNumber, guild, oldName));
    }
    if (!Objects.equals(iconId, guild.getIconId())) {
        String oldIconId = guild.getIconId();
        guild.setIconId(iconId);
        api.getEventManager().handle(new GuildUpdateIconEvent(api, responseNumber, guild, oldIconId));
    }
    if (!Objects.equals(splashId, guild.getSplashId())) {
        String oldSplashId = guild.getSplashId();
        guild.setSplashId(splashId);
        api.getEventManager().handle(new GuildUpdateSplashEvent(api, responseNumber, guild, oldSplashId));
    }
    if (!Objects.equals(region, guild.getRegion())) {
        Region oldRegion = guild.getRegion();
        guild.setRegion(region);
        api.getEventManager().handle(new GuildUpdateRegionEvent(api, responseNumber, guild, oldRegion));
    }
    if (!Objects.equals(verificationLevel, guild.getVerificationLevel())) {
        Guild.VerificationLevel oldVerificationLevel = guild.getVerificationLevel();
        guild.setVerificationLevel(verificationLevel);
        api.getEventManager().handle(
                new GuildUpdateVerificationLevelEvent(api, responseNumber, guild, oldVerificationLevel));
    }
    if (!Objects.equals(notificationLevel, guild.getDefaultNotificationLevel())) {
        Guild.NotificationLevel oldNotificationLevel = guild.getDefaultNotificationLevel();
        guild.setDefaultNotificationLevel(notificationLevel);
        api.getEventManager().handle(
                new GuildUpdateNotificationLevelEvent(api, responseNumber, guild, oldNotificationLevel));
    }
    if (!Objects.equals(mfaLevel, guild.getRequiredMFALevel())) {
        Guild.MFALevel oldMfaLevel = guild.getRequiredMFALevel();
        guild.setRequiredMFALevel(mfaLevel);
        api.getEventManager().handle(new GuildUpdateMFALevelEvent(api, responseNumber, guild, oldMfaLevel));
    }
    if (!Objects.equals(explicitContentLevel, guild.getExplicitContentLevel())) {
        Guild.ExplicitContentLevel oldExplicitContentLevel = guild.getExplicitContentLevel();
        guild.setExplicitContentLevel(explicitContentLevel);
        api.getEventManager().handle(
                new GuildUpdateExplicitContentLevelEvent(api, responseNumber, guild, oldExplicitContentLevel));
    }
    if (!Objects.equals(afkTimeout, guild.getAfkTimeout())) {
        Guild.Timeout oldAfkTimeout = guild.getAfkTimeout();
        guild.setAfkTimeout(afkTimeout);
        api.getEventManager().handle(new GuildUpdateAfkTimeoutEvent(api, responseNumber, guild, oldAfkTimeout));
    }
    if (!Objects.equals(afkChannel, guild.getAfkChannel())) {
        VoiceChannel oldAfkChannel = guild.getAfkChannel();
        guild.setAfkChannel(afkChannel);
        api.getEventManager().handle(new GuildUpdateAfkChannelEvent(api, responseNumber, guild, oldAfkChannel));
    }
    return null;
}

From source file:org.uiautomation.ios.mobileSafari.events.inserted.ChildIframeInserted.java

public ChildIframeInserted(JSONObject message) throws JSONException {
    super(message);

    JSONObject params = message.optJSONObject("params").getJSONObject("node");

    JSONObject json = params.getJSONObject("contentDocument");
    contentDocument = new NodeId(json.getInt("nodeId"));
}

From source file:de.jaetzold.philips.hue.HueBridge.java

/**
 * Attempt to verify the given username is allowed to access the bridge instance.
 * If the username is not allowed (or not given, meaning <code>null</code>) and <code>waitForGrant</code> is <code>true</code>,
 * the method then waits for up to 30 seconds to be granted access to the bridge. This would be done by pressing the bridges button.
 * If authentication succeeds, the username for which it succeeded is then saved and the method returns <code>true</code>.
 *
 * <p>See <a href="http://developers.meethue.com/4_configurationapi.html#41_create_user">Philips hue API, Section 4.1</a> for further reference.</p>
 *
 * @see #authenticate(boolean)/*from  ww w .  j a  v  a  2  s .c o m*/
 *
 * @param usernameToTry a username to authenticate with or null if a new one should be generated by the bridge if access is granted through pressing the hardware button.
 * @param waitForGrant if true, this method blocks for up to 30 seconds or until access to the bridge is allowed, whichever comes first.
 *
 * @return true, if this bridge API instance has now a username that is verified to be allowed to access the bridge device.
 */
public boolean authenticate(String usernameToTry, boolean waitForGrant) {
    if (usernameToTry != null && !usernameToTry.matches("\\s*[-\\w]{10,40}\\s*")) {
        throw new IllegalArgumentException(
                "A username must be 10-40 characters long and may only contain the characters -,_,a-b,A-B,0-9");
    }

    if (!isAuthenticated() || !equalEnough(username, usernameToTry)) {
        // if we have an usernameToTry then check that first whether it already exists
        // I just don't get why a "create new user" request for an existing user results in the same 101 error as when the user does not exist.
        // But for this reason this additional preliminary request is necessary.
        if (!equalEnough(null, usernameToTry)) {
            try {
                completeSync(usernameToTry);
                authenticated = true;
            } catch (HueCommException e) {
                e.printStackTrace();
            }
        }

        if (!isAuthenticated()) {
            long start = System.currentTimeMillis();
            int waitSeconds = 30;
            do {
                JSONObject response = new JSONObject();
                try {
                    final JSONWriter jsonWriter = new JSONStringer().object().key("devicetype")
                            .value(deviceType);
                    if (usernameToTry != null && usernameToTry.trim().length() >= 10) {
                        jsonWriter.key("username").value(usernameToTry.trim());
                    }
                    // use comm directly here because the user is not currently set
                    response = comm.request(POST, "api", jsonWriter.endObject().toString()).get(0);
                } catch (IOException e) {
                    log.log(Level.WARNING, "IOException on create user request", e);
                }
                final JSONObject success = response.optJSONObject("success");
                if (success != null && success.has("username")) {
                    username = success.getString("username");
                    authenticated = true;
                    waitForGrant = false;
                } else {
                    final JSONObject error = response.optJSONObject("error");
                    if (error != null && error.has("type")) {
                        if (error.getInt("type") != 101) {
                            log.warning("Got unexpected error on create user: " + error);
                            waitForGrant = false;
                        }
                    }
                }
                if (waitForGrant) {
                    if (System.currentTimeMillis() - start > waitSeconds * 1000) {
                        waitForGrant = false;
                    } else {
                        try {
                            Thread.sleep(900 + Math.round(Math.random() * 100));
                        } catch (InterruptedException e) {
                        }
                    }
                }
            } while (waitForGrant);
        }
    }

    if (isAuthenticated() && !initialSyncDone) {
        completeSync(username);
    }

    return isAuthenticated();
}

From source file:com.heliosapm.opentsdb.client.opentsdb.OpenTsdbPutResponseHandler.java

/**
 * Processes the summary stats from the http put response
 * @param content The response content/*from  ww  w.j  ava2 s  .  c o m*/
 * @param log The logger to log any errors with
 * @return an array of result counts (failed:0, success:1)
 */
public static int[] doSummaryStats(final ChannelBuffer content, final Logger log) {
    final int[] results = new int[] { 0, 0 };
    try {
        final JSONObject j = new JSONObject(content.toString(Constants.UTF8));
        results[0] = j.getInt(FAILED_KEY);
        results[1] = j.getInt(SUCCESS_KEY);
    } catch (Exception ex) {
        log.error("Failed to process response", ex);
    }
    return results;
}

From source file:com.heliosapm.opentsdb.client.opentsdb.OpenTsdbPutResponseHandler.java

/**
 * Extracts the failiure and success counts and the error json from the passed details response and increments the counters
 * @param responseCode The HTTP response code
 * @param content The response buffer /*w  w w . j a v a2 s  .c  om*/
 * @param log The logger to log with
 * @return the counts of failed submissions ([0]) and successful submissions ([1]).
 */
public static int[] doDetailedStats(final int responseCode, final ChannelBuffer content, final Logger log) {
    final int[] results = new int[] { 0, 0 };
    String contentStr = null;
    try {
        contentStr = content.toString(Constants.UTF8);
        if (responseCode == 400) {
            if (couldBeGzipIssue(responseCode, contentStr)) {
                log.error("Auto disabled http post gzip");
                HttpMetricsPoster.getInstance().autoDisableGZip();
            }
        }
        final JSONObject j = new JSONObject(contentStr);
        results[0] = j.getInt(FAILED_KEY);
        results[1] = j.getInt(SUCCESS_KEY);
        processErrors(j.optJSONArray(ERRORS_KEY), log);
    } catch (Exception ex) {
        log.warn("Failed to process response {}", contentStr, ex);
    }
    return results;
}

From source file:com.norman0406.slimgress.API.Item.ItemPowerCube.java

public ItemPowerCube(JSONArray json) throws JSONException {
    super(ItemType.PowerCube, json);

    JSONObject item = json.getJSONObject(2);
    JSONObject powerCube = item.getJSONObject("powerCube");

    mEnergy = powerCube.getInt("energy");
}

From source file:net.dv8tion.jda.core.handle.MessageCreateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    MessageType type = MessageType.fromId(content.getInt("type"));

    switch (type) {
    case DEFAULT:
        return handleDefaultMessage(content);
    default://from ww w.j  ava  2  s.  com
        WebSocketClient.LOG
                .debug("JDA received a message of unknown type. Type: " + type + "  JSON: " + content);
    }
    return null;
}

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

public JSONObject template() {
    JSONObject m = model();
    try {/*  www .j  a  va2 s .  c  o m*/
        if (m.getInt("type") == Sched.MODEL_STD) {
            return m.getJSONArray("tmpls").getJSONObject(mOrd);
        } else {
            return model().getJSONArray("tmpls").getJSONObject(0);
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:fr.pasteque.pos.customers.DiscountProfile.java

public DiscountProfile(JSONObject o) {
    if (!o.isNull("id")) {
        this.id = o.getInt("id");
    }//from w w  w  . j a  v a2 s. c  om
    this.name = o.getString("label");
    this.rate = o.getDouble("rate");
}