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:uk.ac.imperial.presage2.web.SimulationsTreeServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logRequest(req);/*from   w ww  .  ja  va 2s .  co m*/
    String path = req.getPathInfo();
    Matcher matcher = ID_REGEX.matcher(path);
    if (matcher.matches()) {
        long simId = Integer.parseInt(matcher.group(1));
        try {
            // get data sent to us
            JSONObject input = new JSONObject(new JSONTokener(req.getReader()));
            if (simId > 0 && (input.getString("parentId").equalsIgnoreCase("root")
                    || input.getLong("parentId") > 0)) {
                PersistentSimulation sim = sto.getSimulationById(simId);
                PersistentSimulation parent = null;
                if (input.getString("parentId").equalsIgnoreCase("root")) {
                    parent = null;
                } else if (input.getLong("parentId") > 0 && input.getLong("parentId") != simId) {
                    parent = sto.getSimulationById(input.getLong("parentId"));
                } else {
                    resp.setStatus(400);
                    return;
                }
                if (sim != null) {
                    sim.setParentSimulation(parent);
                    resp.setStatus(200);
                    return;
                }
            }
            resp.setStatus(400);
        } catch (JSONException e) {
            resp.setStatus(400);
        }
    } else {
        resp.setStatus(400);
    }
}

From source file:com.github.koraktor.steamcondenser.community.SteamId.java

/**
 * Fetches the friends of this user/* w  ww .  j  a  v  a  2 s. co m*/
 * <p>
 * This creates a new <code>SteamId</code> instance for each of the friends
 * without fetching their data.
 *
 * @see #getFriends
 * @see SteamId#SteamId
 * @throws SteamCondenserException if an error occurs while parsing the
 *         data
 */
private void fetchFriends() throws SteamCondenserException {
    try {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("relationship", "friend");
        params.put("steamid", this.steamId64);

        JSONObject jsonData = new JSONObject(WebApi.getJSON("ISteamUser", "GetFriendList", 1, params));
        JSONArray friendsData = jsonData.getJSONObject("friendslist").getJSONArray("friends");
        this.friends = new ArrayList<SteamId>();
        for (int i = 0; i < friendsData.length(); i++) {
            JSONObject friend = friendsData.getJSONObject(i);
            this.friends.add(new SteamId(friend.getLong("steamid"), false));
        }
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }
}

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

@Override
protected Long handleInternally(JSONObject content) {
    final Long guildId = content.has("guild_id") ? content.getLong("guild_id") : null;
    if (guildId != null && api.getGuildLock().isLocked(guildId))
        return guildId;

    if (guildId != null)
        handleGuildVoiceState(content);/*w w w . ja va  2s .c o  m*/
    else
        handleCallVoiceState(content);
    return null;
}

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

private void handleGuildVoiceState(JSONObject content) {
    final long userId = content.getLong("user_id");
    final long guildId = content.getLong("guild_id");
    final Long channelId = !content.isNull("channel_id") ? content.getLong("channel_id") : null;
    final String sessionId = !content.isNull("session_id") ? content.getString("session_id") : null;
    boolean selfMuted = content.getBoolean("self_mute");
    boolean selfDeafened = content.getBoolean("self_deaf");
    boolean guildMuted = content.getBoolean("mute");
    boolean guildDeafened = content.getBoolean("deaf");
    boolean suppressed = content.getBoolean("suppress");

    Guild guild = api.getGuildById(guildId);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent));
        EventCache.LOG/*  w  ww .j  a va 2 s . c  om*/
                .debug("Received a VOICE_STATE_UPDATE for a Guild that has yet to be cached. JSON: " + content);
        return;
    }

    VoiceChannelImpl channel = channelId != null ? (VoiceChannelImpl) guild.getVoiceChannelById(channelId)
            : null;
    if (channel == null && channelId != null) {
        api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug(
                "Received VOICE_STATE_UPDATE for a VoiceChannel that has yet to be cached. JSON: " + content);
        return;
    }

    MemberImpl member = (MemberImpl) guild.getMemberById(userId);
    if (member == null) {
        //Caching of this might not be valid. It is possible that we received this
        // update due to this Member leaving the guild while still connected to a voice channel.
        // In that case, we should not cache this because it could cause problems if they rejoined.
        //However, we can't just ignore it completely because it could be a user that joined off of
        // an invite to a VoiceChannel, so the GUILD_MEMBER_ADD and the VOICE_STATE_UPDATE may have
        // come out of order. Not quite sure what to do. Going to cache for now however.
        //At the worst, this will just cause a few events to fire with bad data if the member rejoins the guild if
        // in fact the issue was that the VOICE_STATE_UPDATE was sent after they had left, however, by caching
        // it we will preserve the integrity of the cache in the event that it was actually a mis-ordering of
        // GUILD_MEMBER_ADD and VOICE_STATE_UPDATE. I'll take some bad-data events over an invalid cache.
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent));
        EventCache.LOG
                .debug("Received VOICE_STATE_UPDATE for a Member that has yet to be cached. JSON: " + content);
        return;
    }

    GuildVoiceStateImpl vState = (GuildVoiceStateImpl) member.getVoiceState();
    vState.setSessionId(sessionId); //Cant really see a reason for an event for this

    if (!Objects.equals(channel, vState.getChannel())) {
        VoiceChannelImpl oldChannel = (VoiceChannelImpl) vState.getChannel();
        vState.setConnectedChannel(channel);

        if (oldChannel == null) {
            channel.getConnectedMembersMap().put(userId, member);
            api.getEventManager().handle(new GuildVoiceJoinEvent(api, responseNumber, member));
        } else if (channel == null) {
            oldChannel.getConnectedMembersMap().remove(userId);
            api.getEventManager().handle(new GuildVoiceLeaveEvent(api, responseNumber, member, oldChannel));
        } else {
            //If the connect account is the one that is being moved, and this instance of JDA
            // is connected or attempting to connect, them change the channel we expect to be connected to.
            if (guild.getSelfMember().equals(member)) {
                AudioManagerImpl mng = api.getAudioManagerMap().get(guildId);
                if (mng != null && (mng.isConnected() || mng.isAttemptingToConnect()))
                    mng.setConnectedChannel(channel);
            }

            channel.getConnectedMembersMap().put(userId, member);
            oldChannel.getConnectedMembersMap().remove(userId);
            api.getEventManager().handle(new GuildVoiceMoveEvent(api, responseNumber, member, oldChannel));
        }
    }

    boolean wasMute = vState.isMuted();
    boolean wasDeaf = vState.isDeafened();

    if (selfMuted != vState.isSelfMuted()) {
        vState.setSelfMuted(selfMuted);
        api.getEventManager().handle(new GuildVoiceSelfMuteEvent(api, responseNumber, member));
    }
    if (selfDeafened != vState.isSelfDeafened()) {
        vState.setSelfDeafened(selfDeafened);
        api.getEventManager().handle(new GuildVoiceSelfDeafenEvent(api, responseNumber, member));
    }
    if (guildMuted != vState.isGuildMuted()) {
        vState.setGuildMuted(guildMuted);
        api.getEventManager().handle(new GuildVoiceGuildMuteEvent(api, responseNumber, member));
    }
    if (guildDeafened != vState.isGuildDeafened()) {
        vState.setGuildDeafened(guildDeafened);
        api.getEventManager().handle(new GuildVoiceGuildDeafenEvent(api, responseNumber, member));
    }
    if (suppressed != vState.isSuppressed()) {
        vState.setSuppressed(suppressed);
        api.getEventManager().handle(new GuildVoiceSuppressEvent(api, responseNumber, member));
    }
    if (wasMute != vState.isMuted())
        api.getEventManager().handle(new GuildVoiceMuteEvent(api, responseNumber, member));
    if (wasDeaf != vState.isDeafened())
        api.getEventManager().handle(new GuildVoiceDeafenEvent(api, responseNumber, member));
}

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

private void handleCallVoiceState(JSONObject content) {
    final long userId = content.getLong("user_id");
    final Long channelId = !content.isNull("channel_id") ? content.getLong("channel_id") : null;
    String sessionId = !content.isNull("session_id") ? content.getString("session_id") : null;
    boolean selfMuted = content.getBoolean("self_mute");
    boolean selfDeafened = content.getBoolean("self_deaf");

    //Joining a call
    CallableChannel channel;/*  w  ww .  j a  v  a 2s  .  c  o  m*/
    CallVoiceStateImpl vState;
    if (channelId != null) {
        channel = api.asClient().getGroupById(channelId);
        if (channel == null)
            channel = api.getPrivateChannelMap().get(channelId);

        if (channel == null) {
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "Received a VOICE_STATE_UPDATE for a Group/PrivateChannel that was not yet cached! JSON: "
                            + content);
            return;
        }

        CallImpl call = (CallImpl) channel.getCurrentCall();
        if (call == null) {
            api.getEventCache().cache(EventCache.Type.CALL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG
                    .debug("Received a VOICE_STATE_UPDATE for a Call that is not yet cached. JSON: " + content);
            return;
        }

        CallUser cUser = ((JDAClientImpl) api.asClient()).getCallUserMap().get(userId);
        if (cUser != null && channelId != cUser.getCall().getCallableChannel().getIdLong()) {
            WebSocketClient.LOG.fatal(
                    "Received a VOICE_STATE_UPDATE for a user joining a call, but the user was already in a different call! Big error! JSON: "
                            + content);
            ((CallVoiceStateImpl) cUser.getVoiceState()).setInCall(false);
        }

        cUser = call.getCallUserMap().get(userId);
        if (cUser == null) {
            api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "Received a VOICE_STATE_UPDATE for a user that is not yet a a cached CallUser for the call. (groups only). JSON: "
                            + content);
            return;
        }

        ((JDAClientImpl) api.asClient()).getCallUserMap().put(userId, cUser);
        vState = (CallVoiceStateImpl) cUser.getVoiceState();
        vState.setSessionId(sessionId);
        vState.setInCall(true);

        api.getEventManager().handle(new CallVoiceJoinEvent(api, responseNumber, cUser));
    } else //Leaving a call
    {
        CallUser cUser = ((JDAClientImpl) api.asClient()).getCallUserMap().remove(userId);
        if (cUser == null) {
            api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "Received a VOICE_STATE_UPDATE for a User leaving a Call, but the Call was not yet cached! JSON: "
                            + content);
            return;
        }

        Call call = cUser.getCall();
        channel = call.getCallableChannel();
        vState = (CallVoiceStateImpl) cUser.getVoiceState();
        vState.setSessionId(sessionId);
        vState.setInCall(false);

        api.getEventManager().handle(new CallVoiceLeaveEvent(api, responseNumber, cUser));
    }

    //Now that we're done dealing with the joins and leaves, we can deal with the mute/deaf changes.
    if (selfMuted != vState.isSelfMuted()) {
        vState.setSelfMuted(selfMuted);
        api.getEventManager().handle(new CallVoiceSelfMuteEvent(api, responseNumber, vState.getCallUser()));
    }
    if (selfDeafened != vState.isSelfDeafened()) {
        vState.setSelfDeafened(selfDeafened);
        api.getEventManager().handle(new CallVoiceSelfDeafenEvent(api, responseNumber, vState.getCallUser()));
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

long addObjectByJson(long contactId, JSONObject json, long hash, byte[] raw, Integer intKey) {
    try {/*w w  w . jav  a 2  s .c o  m*/
        long objId = getNextId();
        long seqId = json.optLong(DbObjects.SEQUENCE_ID);
        long timestamp = json.getLong(DbObjects.TIMESTAMP);
        String feedName = json.getString(DbObjects.FEED_NAME);
        String type = json.getString(DbObjects.TYPE);
        String appId = json.getString(DbObjects.APP_ID);
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, objId);
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, contactId);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, seqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.HASH, hash);
        cv.put(DbObject.SENT, 1);

        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());
        if (raw != null) {
            cv.put(DbObject.RAW, raw);
        }
        if (intKey != null) {
            cv.put(DbObject.KEY_INT, intKey);
        }

        // TODO: Deprecated!!
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        long newObjId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        String notifyName = feedName;
        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            notifyName = feedName + ":" + hashA;
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, newObjId, relation);
            }
        }

        ContentResolver resolver = mContext.getContentResolver();
        DungBeetleContentProvider.notifyDependencies(this, resolver, notifyName);
        updateObjModification(App.instance().getMusubi().objForId(newObjId));
        return objId;
    } catch (Exception e) {
        if (DBG)
            Log.e(TAG, "Error adding object by json.", e);
        return -1;
    }
}

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

public static EEP070905DataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP070905DataImpl(VOC.VOCT, -1, null);

    try {//from   w w  w  .j  a v  a 2 s .c  o m
        VOC VOCname = VOC.valueOf(lastKnownData.getString("VOCname"));
        int VOCppb = lastKnownData.getInt("VOCppb");
        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP070905DataImpl(VOCname, VOCppb, 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 EEP070905DataImpl(VOC.VOCT, -1, null);
    }
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private List<String> getPoshFingerprintsFromCache(String domain) {
    File file = getPoshCacheFile(domain);
    try {// ww w.j  a  v a  2 s .  com
        InputStream is = new FileInputStream(file);
        BufferedReader buf = new BufferedReader(new InputStreamReader(is));

        String line = buf.readLine();
        StringBuilder sb = new StringBuilder();

        while (line != null) {
            sb.append(line).append("\n");
            line = buf.readLine();
        }
        JSONObject jsonObject = new JSONObject(sb.toString());
        is.close();
        long expires = jsonObject.getLong("expires");
        long expiresIn = expires - System.currentTimeMillis();
        if (expiresIn < 0) {
            file.delete();
            return null;
        } else {
            Log.d("mtm", "posh fingerprints expire in " + (expiresIn / 1000) + "s");
        }
        List<String> result = new ArrayList<>();
        JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
        for (int i = 0; i < jsonArray.length(); ++i) {
            result.add(jsonArray.getString(i));
        }
        return result;
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        return null;
    } catch (JSONException e) {
        file.delete();
        return null;
    }
}

From source file:com.nextgis.maplib.datasource.ngw.LayerWithStyles.java

public void fillStyles() {
    mStyles = new ArrayList<>();
    try {/*from w  w w .j av a  2s.  c  o  m*/
        String sURL = mConnection.getURL() + "/resource/" + mRemoteId + "/child/";
        HttpGet get = new HttpGet(sURL);
        get.setHeader("Cookie", mConnection.getCookie());
        get.setHeader("Accept", "*/*");
        HttpResponse response = mConnection.getHttpClient().execute(get);
        HttpEntity entity = response.getEntity();
        JSONArray children = new JSONArray(EntityUtils.toString(entity));
        for (int i = 0; i < children.length(); i++) {
            //Only store style id
            //To get more style properties need to create style class extended from Resource
            //Style extends Resource
            //mStyles.add(new Style(styleObject, mConnection);
            JSONObject styleObject = children.getJSONObject(i);
            JSONObject JSONResource = styleObject.getJSONObject("resource");
            long remoteId = JSONResource.getLong("id");
            mStyles.add(remoteId);
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.kevinquan.android.utils.JSONUtils.java

/**
 * Retrieve a long stored at the provided key from the provided JSON object
 * @param obj The JSON object to retrieve from
 * @param key The key to retrieve/*from  ww w . j  a v a 2 s  .c om*/
 * @return the long stored in the key, or the default value if the key doesn't exist
 */
public static long safeGetLong(JSONObject obj, String key, long defaultValue) {
    if (obj == null || TextUtils.isEmpty(key))
        return defaultValue;
    if (obj.has(key)) {
        try {
            return obj.getLong(key);
        } catch (JSONException e) {
            Log.w(TAG, "Could not get long from key " + key, e);
        }
    }
    return defaultValue;
}