Example usage for org.json JSONObject getLong

List of usage examples for org.json JSONObject getLong

Introduction

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

Prototype

public long getLong(String key) throws JSONException 

Source Link

Document

Get the long value associated with a key.

Usage

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

@Override
protected Long handleInternally(JSONObject content) {
    //Do a pre-check to see if this is for a Guild, and if it is, if the guild is currently locked.
    if (content.has("guild_id")) {
        final long guildId = content.getLong("guild_id");
        if (api.getGuildLock().isLocked(guildId))
            return guildId;
    }/*  w w  w .jav a  2 s .co  m*/

    JSONObject jsonUser = content.getJSONObject("user");
    final long userId = jsonUser.getLong("id");
    UserImpl user = (UserImpl) api.getUserMap().get(userId);

    //If we do know about the user, lets update the user's specific info.
    // Afterwards, we will see if we already have them cached in the specific guild
    // or Relation. If not, we'll cache the OnlineStatus and Game for later handling
    // unless OnlineStatus is OFFLINE, in which case we probably received this event
    // due to a User leaving a guild or no longer being a relation.
    if (user != null) {
        if (jsonUser.has("username")) {
            String name = jsonUser.getString("username");
            String discriminator = jsonUser.get("discriminator").toString();
            String avatarId = jsonUser.isNull("avatar") ? null : jsonUser.getString("avatar");

            if (!user.getName().equals(name)) {
                String oldUsername = user.getName();
                String oldDiscriminator = user.getDiscriminator();
                user.setName(name);
                user.setDiscriminator(discriminator);
                api.getEventManager().handle(
                        new UserNameUpdateEvent(api, responseNumber, user, oldUsername, oldDiscriminator));
            }
            String oldAvatar = user.getAvatarId();
            if (!(avatarId == null && oldAvatar == null) && !Objects.equals(avatarId, oldAvatar)) {
                String oldAvatarId = user.getAvatarId();
                user.setAvatarId(avatarId);
                api.getEventManager().handle(new UserAvatarUpdateEvent(api, responseNumber, user, oldAvatarId));
            }
        }

        //Now that we've update the User's info, lets see if we need to set the specific Presence information.
        // This is stored in the Member or Relation objects.
        String gameName = null;
        String gameUrl = null;
        Game.GameType type = null;
        if (!content.isNull("game") && !content.getJSONObject("game").isNull("name")) {
            gameName = content.getJSONObject("game").get("name").toString();
            gameUrl = (content.getJSONObject("game").isNull("url") ? null
                    : content.getJSONObject("game").get("url").toString());
            try {
                type = content.getJSONObject("game").isNull("type") ? Game.GameType.DEFAULT
                        : Game.GameType.fromKey(
                                Integer.parseInt(content.getJSONObject("game").get("type").toString()));
            } catch (NumberFormatException ex) {
                type = Game.GameType.DEFAULT;
            }
        }
        Game nextGame = (gameName == null ? null : new GameImpl(gameName, gameUrl, type));
        OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));

        //If we are in a Guild, then we will use Member.
        // If we aren't we'll be dealing with the Relation system.
        if (content.has("guild_id")) {
            GuildImpl guild = (GuildImpl) api.getGuildById(content.getLong("guild_id"));
            MemberImpl member = (MemberImpl) guild.getMember(user);

            //If the Member is null, then User isn't in the Guild.
            //This is either because this PRESENCE_UPDATE was received before the GUILD_MEMBER_ADD event
            // or because a Member recently left and this PRESENCE_UPDATE came after the GUILD_MEMBER_REMOVE event.
            //If it is because a Member recently left, then the status should be OFFLINE. As such, we will ignore
            // the event if this is the case. If the status isn't OFFLINE, we will cache and use it when the
            // Member object is setup during GUILD_MEMBER_ADD
            if (member == null) {
                //Cache the presence and return to finish up.
                if (status != OnlineStatus.OFFLINE) {
                    guild.getCachedPresenceMap().put(userId, content);
                    return null;
                }
            } else {
                //The member is already cached, so modify the presence values and fire events as needed.
                if (!member.getOnlineStatus().equals(status)) {
                    OnlineStatus oldStatus = member.getOnlineStatus();
                    member.setOnlineStatus(status);
                    api.getEventManager().handle(
                            new UserOnlineStatusUpdateEvent(api, responseNumber, user, guild, oldStatus));
                }
                if (member.getGame() == null ? nextGame != null : !member.getGame().equals(nextGame)) {
                    Game oldGame = member.getGame();
                    member.setGame(nextGame);
                    api.getEventManager()
                            .handle(new UserGameUpdateEvent(api, responseNumber, user, guild, oldGame));
                }
            }
        } else {
            //In this case, this PRESENCE_UPDATE is for a Relation.

        }
    } else {
        //In this case, we don't have the User cached, which means that we can't update the User's information.
        // This is most likely because this PRESENCE_UPDATE came before the GUILD_MEMBER_ADD that would have added
        // this User to our User cache. Or, it could have come after a GUILD_MEMBER_REMOVE that caused the User
        // to be removed from JDA's central User cache because there were no more connected Guilds. If this is
        // the case, then the OnlineStatus will be OFFLINE and we can ignore this event.
        //Either way, we don't have the User cached so we need to cache the Presence information if
        // the OnlineStatus is not OFFLINE.

        //If the OnlineStatus is OFFLINE, ignore the event and return.
        OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));
        if (status == OnlineStatus.OFFLINE)
            return null;

        //If this was for a Guild, cache it in the Guild for later use in GUILD_MEMBER_ADD
        if (content.has("guild_id")) {
            GuildImpl guild = (GuildImpl) api.getGuildById(content.getLong("guild_id"));
            guild.getCachedPresenceMap().put(userId, content);
        } else {
            //cache in relationship stuff
        }
    }
    return null;
}

From source file:app.com.example.android.sunshine.ForecastFragment.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.// ww  w.j  av a 2  s  . c  om
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException {

    // These are the names of the JSON objects that need to be extracted.
    final String OWM_LIST = "list";
    final String OWM_WEATHER = "weather";
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";
    final String OWM_DATETIME = "dt";
    final String OWM_DESCRIPTION = "main";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    String[] resultStrs = new String[numDays];
    for (int i = 0; i < weatherArray.length(); i++) {
        // For now, using the format "Day, description, hi/low"
        String day;
        String description;
        String highAndLow;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        long dateTime = dayForecast.getLong(OWM_DATETIME);
        day = getReadableDateString(dateTime);

        // description is in a child array called "weather", which is 1 element long.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);

        // 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);
        double high = temperatureObject.getDouble(OWM_MAX);
        double low = temperatureObject.getDouble(OWM_MIN);

        highAndLow = formatHighLows(high, low);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    return resultStrs;
}

From source file:com.aliyun.openservices.odps.console.commands.logview.GetTaskDetailsAction.java

private FuxiInstance getFuxiInstanceFromJson(JSONObject instJson) throws JSONException {
    FuxiInstance inst = new FuxiInstance();
    inst.id = instJson.getString("id");
    inst.logid = instJson.getString("logId");
    inst.status = instJson.getString("status");
    inst.startTime = instJson.getLong("startTime");
    long endTime = instJson.getLong("endTime");
    inst.duration = (int) (endTime - inst.startTime);
    return inst;/*  ww w  .jav  a  2s  .  com*/
}

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 {//from  w w w .ja v a2  s .c  om
        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;//from   w  w w. j  a v  a  2s .com

    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:com.dahl.brendan.wordsearch.model.HighScore.java

public HighScore(JSONObject json) throws JSONException {
    this.name = json.getString(Constants.KEY_HIGH_SCORE_NAME);
    this.score = json.getLong(Constants.KEY_HIGH_SCORE);
    this.time = json.getLong(Constants.KEY_HIGH_SCORE_TIME);
}

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

private Long handleDefaultMessage(JSONObject content) {
    Message message;//from w  w  w. j  a  v a 2  s  .  c om
    try {
        message = api.getEntityBuilder().createMessage(content, true);
    } catch (IllegalArgumentException e) {
        switch (e.getMessage()) {
        case EntityBuilder.MISSING_CHANNEL: {
            final long channelId = content.getLong("channel_id");
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug("Received a message for a channel that JDA does not currently have cached");
            return null;
        }
        case EntityBuilder.MISSING_USER: {
            final long authorId = content.getJSONObject("author").getLong("id");
            api.getEventCache().cache(EventCache.Type.USER, authorId, () -> handle(responseNumber, allContent));
            EventCache.LOG.debug("Received a message for a user that JDA does not currently have cached");
            return null;
        }
        default:
            throw e;
        }
    }

    switch (message.getChannelType()) {
    case TEXT: {
        TextChannelImpl channel = (TextChannelImpl) message.getTextChannel();
        if (api.getGuildLock().isLocked(channel.getGuild().getIdLong())) {
            return channel.getGuild().getIdLong();
        }
        channel.setLastMessageId(message.getIdLong());
        api.getEventManager().handle(new GuildMessageReceivedEvent(api, responseNumber, message));
        break;
    }
    case PRIVATE: {
        PrivateChannelImpl channel = (PrivateChannelImpl) message.getPrivateChannel();
        channel.setLastMessageId(message.getIdLong());
        api.getEventManager().handle(new PrivateMessageReceivedEvent(api, responseNumber, message));
        break;
    }
    case GROUP: {
        GroupImpl channel = (GroupImpl) message.getGroup();
        channel.setLastMessageId(message.getIdLong());
        api.getEventManager().handle(new GroupMessageReceivedEvent(api, responseNumber, message));
        break;
    }
    default:
        WebSocketClient.LOG
                .warn("Received a MESSAGE_CREATE with a unknown MessageChannel ChannelType. JSON: " + content);
        return null;
    }

    //Combo event
    api.getEventManager().handle(new MessageReceivedEvent(api, responseNumber, message));

    //        //searching for invites
    //        Matcher matcher = invitePattern.matcher(message.getContent());
    //        while (matcher.find())
    //        {
    //            InviteUtil.Invite invite = InviteUtil.resolve(matcher.group(1));
    //            if (invite != null)
    //            {
    //                api.getEventManager().handle(
    //                        new InviteReceivedEvent(
    //                                api, responseNumber,
    //                                message,invite));
    //            }
    //        }
    return null;
}

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

public HashMap<String, String> _getQA(boolean reload, boolean browser) {
    if (mQA == null || reload) {
        mQA = new HashMap<String, String>();
        Note n = note(reload);//from   ww  w.j  a v a  2  s  .co  m
        JSONObject m = model();
        JSONObject t = template();
        Object[] data;
        try {
            data = new Object[] { mId, n.getId(), m.getLong("id"), mODid != 0l ? mODid : mDid, mOrd,
                    n.stringTags(), n.joinedFields() };
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        List<String> args = new ArrayList<String>();
        if (browser) {
            try {
                args.add(t.getString("bqfmt"));
                args.add(t.getString("bafmt"));
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
        mQA = mCol._renderQA(data, args);
    }
    return mQA;
}

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

/**
 * Time taken to answer card, in integer MS.
 *//*w w w .  j a  v a  2s  . c om*/
public long timeLimit() {
    JSONObject conf = mCol.getDecks().confForDid(mODid == 0 ? mDid : mODid);
    try {
        return conf.getLong("maxTaken") * 1000;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.chess.genesis.net.SyncClient.java

private void sync_recent(final JSONObject json) {
    try {//from   w w  w .  j a  va 2  s  . co  m
        final JSONArray ids = json.getJSONArray("gameids");
        final ExecutorService pool = Executors.newCachedThreadPool();

        for (int i = 0, len = ids.length(); i < len; i++) {
            if (error)
                return;
            final NetworkClient nc = new NetworkClient(context, handle);
            nc.game_status(ids.getString(i));
            pool.submit(nc);

            lock++;
        }
        // Save sync time
        final PrefEdit pref = new PrefEdit(context);
        pref.putLong(R.array.pf_lastgamesync, json.getLong("time"));
        pref.commit();
    } catch (final JSONException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}