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:org.b3log.latke.cache.PageCaches.java

/**
 * Gets a cached page with the specified page cache key and update 
 * stat. flag. /* w ww  . j a  v a2 s.  c  o m*/
 * 
 * <p>
 * Invoking this method may change statistic, such as to update the 
 * cache hit count. But if the specified request made from a search engine 
 * bot, will NOT change statistic field.
 * </p>
 * 
 * <p>
 * The {@link #get(java.lang.String)} method will return a cached page 
 * without update statistic.
 * </p>
 * 
 * <p>
 *   <b>Note</b>: Do NOT modify properties of the returned json object,
 * </p>
 *
 * @param pageCacheKey the specified page cache key
 * @param request the specified request
 * @param response the specified response
 * @return for example,
 * <pre>
 * {
 *     "cachedContent: "",
 *     "cachedOid": "",
 *     "cachedTitle": "",
 *     "cachedType": "",
 *     "cachedBytesLength": int,
 *     "cachedHitCount": long,
 *     "cachedTime": long
 * }
 * </pre>
 * @see Requests#searchEngineBotRequest(javax.servlet.http.HttpServletRequest) 
 * @see Requests#hasBeenServed(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 
 * @see #get(java.lang.String) 
 */
public static JSONObject get(final String pageCacheKey, final HttpServletRequest request,
        final HttpServletResponse response) {
    final JSONObject ret = (JSONObject) CACHE.get(pageCacheKey);

    if (null == ret) {
        return null;
    }

    try {
        if (!Requests.searchEngineBotRequest(request) && !Requests.hasBeenServed(request, response)) {
            final long hitCount = ret.getLong(CACHED_HIT_COUNT);

            ret.put(CACHED_HIT_COUNT, hitCount + 1);
        }

        CACHE.put(pageCacheKey, ret);
        KEYS.add(pageCacheKey);
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Set stat. of cached page[pageCacheKey=" + pageCacheKey + "] failed", e);
    }

    return ret;
}

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

@Override
protected Long handleInternally(JSONObject content) {
    final long guildId = content.getLong("guild_id");
    api.getClient().getQueuedAudioConnectionMap().remove(guildId);

    if (api.getGuildLock().isLocked(guildId))
        return guildId;

    if (content.isNull("endpoint")) {
        //Discord did not provide an endpoint yet, we are to wait until discord has resources to provide
        // an endpoint, which will result in them sending another VOICE_SERVER_UPDATE which we will handle
        // to actually connect to the audio server.
        return null;
    }//from w w w  .  ja v  a2 s. co m

    String endpoint = content.getString("endpoint");
    String token = content.getString("token");
    Guild guild = api.getGuildMap().get(guildId);
    if (guild == null)
        throw new IllegalArgumentException(
                "Attempted to start audio connection with Guild that doesn't exist! JSON: " + content);
    String sessionId = guild.getSelfMember().getVoiceState().getSessionId();
    if (sessionId == null)
        throw new IllegalArgumentException(
                "Attempted to create audio connection without having a session ID. Did VOICE_STATE_UPDATED fail?");

    //Strip the port from the endpoint.
    endpoint = endpoint.replace(":80", "");

    AudioManagerImpl audioManager = (AudioManagerImpl) guild.getAudioManager();
    synchronized (audioManager.CONNECTION_LOCK) //Synchronized to prevent attempts to close while setting up initial objects.
    {
        if (audioManager.isConnected())
            audioManager.prepareForRegionChange();
        if (!audioManager.isAttemptingToConnect()) {
            WebSocketClient.LOG.debug(
                    "Received a VOICE_SERVER_UPDATE but JDA is not currently connected nor attempted to connect "
                            + "to a VoiceChannel. Assuming that this is caused by another client running on this account. Ignoring the event.");
            return null;
        }

        AudioWebSocket socket = new AudioWebSocket(audioManager.getListenerProxy(), endpoint, api, guild,
                sessionId, token, audioManager.isAutoReconnect());
        AudioConnection connection = new AudioConnection(socket, audioManager.getQueuedAudioConnection());
        audioManager.setAudioConnection(connection);
        socket.startConnection();

        return null;
    }
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

/**
 * TODO: unused because we now use {@link LargeCheckpointer}.
 * /*from  w w w.j  av  a 2 s  . c o  m*/
 * Sends request for and receives remote checkpoint file if correctly
 * formatted URL. If so, it returns a local filename. If not, it returns the
 * url back as-is.
 */
@SuppressWarnings("unused")
private String getRemoteCheckpoint(String rcGroup, String url) {
    if (url == null)
        return url;
    String filename = url;
    JSONObject jsonUrl;
    try {
        jsonUrl = new JSONObject(url);
        if (jsonUrl.has(Keys.INET_SOCKET_ADDRESS.toString()) && jsonUrl.has(Keys.FILENAME.toString())) {
            filename = jsonUrl.getString(Keys.FILENAME.toString());
            File file = new File(filename);
            if (!file.exists()) { // fetch from remote
                InetSocketAddress sockAddr = Util
                        .getInetSocketAddressFromString(jsonUrl.getString(Keys.INET_SOCKET_ADDRESS.toString()));
                assert (sockAddr != null);
                filename = this.getRemoteCheckpoint(rcGroup, sockAddr, filename,
                        jsonUrl.getLong(Keys.FILESIZE.toString()));
            }
        }
    } catch (JSONException e) {
        // do nothing, will return filename
    }
    return filename;
}

From source file:com.soomla.levelup.LevelUp.java

private static boolean resetWorldsStateFromJSON(JSONObject state) {
    boolean worldsApplyState = resetStateFromJSON(state, "worlds", new IItemStateApplier() {
        @Override/*w ww  .  ja va 2  s.c om*/
        public boolean applyState(String itemId, JSONObject itemValuesJSON) {
            try {
                if (itemValuesJSON.has("completed")) {
                    boolean completedState = itemValuesJSON.getBoolean("completed");
                    WorldStorage.setCompleted(itemId, completedState, false);
                }

                if (itemValuesJSON.has("assignedReward")) {
                    String assignedRewardId = itemValuesJSON.getString("assignedReward");
                    WorldStorage.setReward(itemId, assignedRewardId, false);
                }
            } catch (JSONException e) {
                SoomlaUtils.LogError(TAG,
                        "Unable to set state for world " + itemId + ". error: " + e.getLocalizedMessage());
                return false;
            }

            return true;
        }
    });

    boolean levelsApplyState = resetStateFromJSON(state, "levels", new IItemStateApplier() {
        @Override
        public boolean applyState(String itemId, JSONObject itemValuesJSON) {
            try {
                if (itemValuesJSON.has("started")) {
                    int timesStarted = itemValuesJSON.getInt("started");
                    LevelStorage.setTimesStarted(itemId, timesStarted);
                }

                if (itemValuesJSON.has("played")) {
                    int timesPlayed = itemValuesJSON.getInt("played");
                    LevelStorage.setTimesPlayed(itemId, timesPlayed);
                }

                if (itemValuesJSON.has("timesCompleted")) {
                    int timesCompleted = itemValuesJSON.getInt("timesCompleted");
                    LevelStorage.setTimesCompleted(itemId, timesCompleted);
                }

                if (itemValuesJSON.has("slowest")) {
                    long slowest = itemValuesJSON.getLong("slowest");
                    LevelStorage.setSlowestDurationMillis(itemId, slowest);
                }

                if (itemValuesJSON.has("fastest")) {
                    long fastest = itemValuesJSON.getLong("fastest");
                    LevelStorage.setFastestDurationMillis(itemId, fastest);
                }
            } catch (JSONException e) {
                SoomlaUtils.LogError(TAG,
                        "Unable to set state for level " + itemId + ". error: " + e.getLocalizedMessage());
                return false;
            }

            return true;
        }
    });

    return worldsApplyState && levelsApplyState;
}

From source file:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP050401DataImpl.java

public static EEP050401DataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP050401DataImpl(null, null);

    try {//from  ww w . ja  v  a 2  s .c  o  m
        KeyCardState keyCardState = KeyCardState.valueOf(lastKnownData.getString("keyCardState"));
        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP050401DataImpl(keyCardState, date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEP050401DataImpl(null, null);
    }
}

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

private void NewMove(final JSONObject json) {
    try {/*from w  w w.jav a2s.c  om*/
        final JSONArray ids = json.getJSONArray("gameids");

        for (int i = 0, len = ids.length(); i < len; i++) {
            if (error)
                return;
            net.game_status(ids.getString(i));
            net.run();

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

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

private void NewMsgs(final JSONObject json) {
    try {//from   w w  w  .  j a v a 2 s .  c o m
        final JSONArray msgs = json.getJSONArray("msglist");
        final long time = json.getLong("time");

        for (int i = 0, len = msgs.length(); i < len; i++) {
            final JSONObject item = msgs.getJSONObject(i);
            db.insertMsg(item);
        }

        // Save sync time
        final PrefEdit pref = new PrefEdit(this);
        pref.putLong(R.array.pf_lastmsgsync, time);
        pref.commit();
    } catch (final JSONException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:edu.umass.cs.gigapaxos.paxospackets.PrepareReplyPacket.java

public PrepareReplyPacket(JSONObject json) throws JSONException {
    super(json);/*from  www.  j  ava 2  s .c o  m*/
    assert (PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.PREPARE_REPLY);
    this.packetType = PaxosPacket.getPaxosPacketType(json);
    this.acceptor = json.getInt(PaxosPacket.NodeIDKeys.ACCPTR.toString());
    this.ballot = new Ballot(json.getString(PaxosPacket.NodeIDKeys.B.toString()));
    this.accepted = parseJsonForAccepted(json);
    this.firstSlot = json.getInt(PaxosPacket.Keys.PREPLY_MIN.toString());
    this.maxSlot = json.getInt(PaxosPacket.Keys.MAX_S.toString());
    this.minSlot = json.getInt(PaxosPacket.Keys.MIN_S.toString());
    this.createTime = json.getLong(RequestPacket.Keys.CT.toString());
}

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

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

    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, id, () -> {
            handle(responseNumber, allContent);
        });//from  ww  w  . j  ava2 s  .  com
        return null;
    }

    Member member = api.getEntityBuilder().createMember(guild, content);
    api.getEventManager().handle(new GuildMemberJoinEvent(api, responseNumber, guild, member));
    api.getEventCache().playbackCache(EventCache.Type.USER, member.getUser().getIdLong());
    return null;
}

From source file:com.nextgis.firereporter.GetFiresService.java

protected void FillScanexData(int nType, String sJSON) {
    GetDataStoped();/* w w  w .j  ava  2  s .  com*/
    try {
        String sSubData = removeJsonT(sJSON);
        JSONObject rootobj = new JSONObject(sSubData);
        String sStatus = rootobj.getString("Status");
        if (sStatus.equals("OK")) {
            //6. store data to db and in map
            List<Long> naIDs = new ArrayList<Long>();
            JSONArray oResults = rootobj.getJSONArray("Result");
            for (int i = 0; i < oResults.length(); i++) {
                JSONObject jsonObject = oResults.getJSONObject(i);
                long nID = jsonObject.getLong("ID");
                naIDs.add(nID);

                // Add new items

                if (!mmoSubscriptions.containsKey(nID)) {
                    String sTitle = jsonObject.getString("Title");
                    String sLayerName = jsonObject.getString("LayerName");
                    String sWKT = jsonObject.getString("wkt");
                    boolean bSMSEnable = jsonObject.getBoolean("SMSEnable");

                    ScanexSubscriptionItem Item = new ScanexSubscriptionItem(this, nID, sTitle, sLayerName,
                            sWKT, bSMSEnable);
                    mmoSubscriptions.put(nID, Item);
                    SendScanexItem(Item);

                    mbHasChanges = true;
                }

                mmoSubscriptions.get(nID).UpdateFromRemote(msScanexLoginCookie);

            }

            // Remove deleted items
            for (Long id : mmoSubscriptions.keySet()) {
                if (!naIDs.contains(id)) {
                    mmoSubscriptions.remove(id);
                }
            }
            StoreScanexData();
        } else {
            SendError(rootobj.getString("ErrorInfo"));
        }
    } catch (JSONException e) {
        SendError(e.getLocalizedMessage());
        e.printStackTrace();
    }
}