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:com.hichinaschool.flashcards.libanki.Sched.java

/**
 * Returns [deckname, did, rev, lrn, new]
 *///from   www.ja  v  a 2  s.c o m
public ArrayList<Object[]> deckDueList() {
    _checkDay();
    mCol.getDecks().recoverOrphans();
    ArrayList<JSONObject> decks = mCol.getDecks().all();
    Collections.sort(decks, new DeckDueListComparator());
    HashMap<String, Integer[]> lims = new HashMap<String, Integer[]>();
    ArrayList<Object[]> data = new ArrayList<Object[]>();
    try {
        for (JSONObject deck : decks) {
            // if we've already seen the exact same deck name, remove the
            // invalid duplicate and reload
            if (lims.containsKey(deck.getString("name"))) {
                mCol.getDecks().rem(deck.getLong("id"), false, true);
                return deckDueList();
            }
            String p;
            List<String> parts = Arrays.asList(deck.getString("name").split("::"));
            if (parts.size() < 2) {
                p = null;
            } else {
                parts = parts.subList(0, parts.size() - 1);
                p = TextUtils.join("::", parts);
            }
            // new
            int nlim = _deckNewLimitSingle(deck);
            if (!TextUtils.isEmpty(p)) {
                if (!lims.containsKey(p)) {
                    // if parent was missing, this deck is invalid, and we need to reload the deck list
                    mCol.getDecks().rem(deck.getLong("id"), false, true);
                    return deckDueList();
                }
                nlim = Math.min(nlim, lims.get(p)[0]);
            }
            int newC = _newForDeck(deck.getLong("id"), nlim);
            // learning
            int lrn = _lrnForDeck(deck.getLong("id"));
            // reviews
            int rlim = _deckRevLimitSingle(deck);
            if (!TextUtils.isEmpty(p)) {
                rlim = Math.min(rlim, lims.get(p)[1]);
            }
            int rev = _revForDeck(deck.getLong("id"), rlim);
            // save to list
            // LIBANKI: order differs from libanki (here: new, lrn, rev)  // TODO: why?
            data.add(new Object[] { deck.getString("name"), deck.getLong("id"), newC, lrn, rev });
            // add deck as a parent
            lims.put(deck.getString("name"), new Integer[] { nlim, rlim });
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return data;
}

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

public int _deckNewLimitSingle(JSONObject g) {
    try {/*from   w  w  w  .  j a  va2  s.  c o  m*/
        if (g.getInt("dyn") != 0) {
            return mReportLimit;
        }
        JSONObject c = mCol.getDecks().confForDid(g.getLong("id"));
        return Math.max(0, c.getJSONObject("new").getInt("perDay") - g.getJSONArray("newToday").getInt(1));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

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

private int _deckRevLimitSingle(JSONObject d) {
    try {/* w  w  w .  j  a  va2  s  .c om*/
        if (d.getInt("dyn") != 0) {
            return mReportLimit;
        }
        JSONObject c = mCol.getDecks().confForDid(d.getLong("id"));
        return Math.max(0, c.getJSONObject("rev").getInt("perDay") - d.getJSONArray("revToday").getInt(1));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

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

private List<Long> _fillDyn(JSONObject deck) {
    JSONArray terms;//from ww  w  .java2s  .  c om
    List<Long> ids;
    try {
        terms = deck.getJSONArray("terms").getJSONArray(0);
        String search = terms.getString(0);
        int limit = terms.getInt(1);
        int order = terms.getInt(2);
        String orderlimit = _dynOrder(order, limit);
        search += " -is:suspended -is:buried -deck:filtered";
        ids = mCol.findCards(search, orderlimit);
        if (ids.isEmpty()) {
            return ids;
        }
        // move the cards over
        _moveToDyn(deck.getLong("id"), ids);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return ids;
}

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

/** returns today's progress
 *
 * @param counts (if empty, cached version will be used if any)
 * @param card/*from w ww . j  av a 2s. c  om*/
 * @return [progressCurrentDeck, progressAllDecks, leftCards, eta]
 */
public float[] progressToday(TreeSet<Object[]> counts, Card card, boolean eta) {
    try {
        int doneCurrent = 0;
        int[] leftCurrent = new int[] { 0, 0, 0 };
        String[] cs = new String[] { "new", "lrn", "rev" };
        long currentDid = 0;

        // current selected deck
        if (counts == null) {
            JSONObject deck = mCol.getDecks().current();
            currentDid = deck.getLong("id");
            for (String s : cs) {
                doneCurrent += deck.getJSONArray(s + "Today").getInt(1);
            }
            if (card != null) {
                int idx = countIdx(card);
                leftCurrent[idx] += idx == 1 ? card.getLeft() / 1000 : 1;
            } else {
                reset();
            }
            leftCurrent[0] += mNewCount;
            leftCurrent[1] += mLrnCount;
            leftCurrent[2] += mRevCount;
        }

        // refresh deck progresses with fresh counts if necessary
        if (counts != null || mCachedDeckCounts == null) {
            if (mCachedDeckCounts == null) {
                mCachedDeckCounts = new HashMap<Long, Pair<String[], long[]>>();
            }
            mCachedDeckCounts.clear();
            if (counts == null) {
                // reload counts
                counts = (TreeSet<Object[]>) deckCounts()[0];
            }
            for (Object[] d : counts) {
                int done = 0;
                JSONObject deck = mCol.getDecks().get((Long) d[1]);
                for (String s : cs) {
                    done += deck.getJSONArray(s + "Today").getInt(1);
                }
                mCachedDeckCounts.put((Long) d[1], new Pair<String[], long[]>((String[]) d[0],
                        new long[] { done, (Integer) d[2], (Integer) d[3], (Integer) d[4] }));
            }
        }

        int doneAll = 0;
        int[] leftAll = new int[] { 0, 0, 0 };
        for (Map.Entry<Long, Pair<String[], long[]>> d : mCachedDeckCounts.entrySet()) {
            boolean exclude = d.getKey() == currentDid; // || mCol.getDecks().isDyn(d.getKey());
            if (d.getValue().first.length == 1) {
                if (exclude) {
                    // don't count cached version of current deck
                    continue;
                }
                long[] c = d.getValue().second;
                doneAll += c[0];
                leftAll[0] += c[1];
                leftAll[1] += c[2];
                leftAll[2] += c[3];
            } else if (exclude) {
                // exclude cached values for current deck in order to avoid double count
                long[] c = d.getValue().second;
                doneAll -= c[0];
                leftAll[0] -= c[1];
                leftAll[1] -= c[2];
                leftAll[2] -= c[3];
            }
        }
        doneAll += doneCurrent;
        leftAll[0] += leftCurrent[0];
        leftAll[1] += leftCurrent[1];
        leftAll[2] += leftCurrent[2];
        int totalAll = doneAll + leftAll[0] + leftAll[1] + leftAll[2];
        int totalCurrent = doneCurrent + leftCurrent[0] + leftCurrent[1] + leftCurrent[2];

        float progressCurrent = -1;
        if (totalCurrent != 0) {
            progressCurrent = (float) doneCurrent / (float) totalCurrent;
        }
        float progressTotal = -1;
        if (totalAll != 0) {
            progressTotal = (float) doneAll / (float) totalAll;
        }
        return new float[] { progressCurrent, progressTotal, totalAll - doneAll,
                eta ? eta(leftAll, false) : -1 };
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitTagTest.java

@Test
public void testListOrionServerTags() throws Exception {
    File orionServer = new File("").getAbsoluteFile().getParentFile(/*org.eclipse.orion.server.tests*/)
            .getParentFile(/*tests*/);
    Assume.assumeTrue(new File(orionServer, Constants.DOT_GIT).exists());

    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(),
            orionServer.toURI().toString());
    String location = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get project/folder metadata
    WebRequest request = getGetRequest(location);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject folder = new JSONObject(response.getText());

    JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
    String gitTagUri = gitSection.getString(GitConstants.KEY_TAG);

    JSONArray tags = listTags(gitTagUri);
    assertTrue(tags.length() > 0);/*from  w w w  . j a  va 2  s  . c  o m*/
    long lastTime = Long.MAX_VALUE;
    for (int i = 0; i < tags.length(); i++) {
        JSONObject tag = tags.getJSONObject(i);

        // assert properly sorted, new first
        long t = tag.getLong(ProtocolConstants.KEY_LOCAL_TIMESTAMP);
        assertTrue(t <= lastTime);
        lastTime = t;

        // get 'tag' metadata
        request = getGetGitTagRequest(tag.getString(ProtocolConstants.KEY_LOCATION).toString());
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    }
}

From source file:JMeterProcessing.JMeterPropertiesGenerator.java

private static void doCurl(String url, String[] idNames, Map<String, Long> idValuesMap)
        throws JSONException, IOException {
    String[] command = { "curl", "-H", "Accept:application/json", "-X", "GET", "-u",
            _USERNAME + ":" + _PASSWORD, url };

    ProcessBuilder process = new ProcessBuilder(command);

    Process p = process.start();/*  w  ww .  ja v  a 2  s.c om*/

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    StringBuilder sb = new StringBuilder();

    String line = reader.readLine();

    while (line != null) {
        sb.append(line);

        line = reader.readLine();
    }

    String result = sb.toString();

    if (result != null) {
        JSONObject curlResult = new JSONObject(result);

        JSONObject jsonObject;

        try {
            JSONArray data = curlResult.getJSONArray("data");

            jsonObject = data.getJSONObject(0);
        } catch (JSONException e) {
            jsonObject = curlResult.getJSONObject("data");
        }

        for (String idName : idNames) {
            Long idValue = jsonObject.getLong(idName);

            idValuesMap.put(idName, idValue);
        }
    }
}

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

@Override
protected Long handleInternally(JSONObject content) {
    ChannelType type = ChannelType.fromId(content.getInt("type"));
    if (type == ChannelType.GROUP) {
        handleGroup(content);//from  w ww .j a  va 2 s.c o m
        return null;
    }

    List<IPermissionHolder> changed = new ArrayList<>();
    List<IPermissionHolder> contained = new ArrayList<>();

    final long channelId = content.getLong("id");
    final int position = content.getInt("position");
    final String name = content.getString("name");
    final boolean nsfw = !content.isNull("nsfw") && content.getBoolean("nsfw");
    JSONArray permOverwrites = content.getJSONArray("permission_overwrites");
    switch (type) {
    case TEXT: {
        String topic = content.isNull("topic") ? null : content.getString("topic");
        TextChannelImpl textChannel = (TextChannelImpl) api.getTextChannelMap().get(channelId);
        if (textChannel == null) {
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "CHANNEL_UPDATE attempted to update a TextChannel that does not exist. JSON: " + content);
            return null;
        }

        //If any properties changed, update the values and fire the proper events.
        final String oldName = textChannel.getName();
        final String oldTopic = textChannel.getTopic();
        final int oldPosition = textChannel.getPositionRaw();
        final boolean oldNsfw = textChannel.isNSFW();
        if (!Objects.equals(oldName, name)) {
            textChannel.setName(name);
            api.getEventManager()
                    .handle(new TextChannelUpdateNameEvent(api, responseNumber, textChannel, oldName));
        }
        if (!Objects.equals(oldTopic, topic)) {
            textChannel.setTopic(topic);
            api.getEventManager()
                    .handle(new TextChannelUpdateTopicEvent(api, responseNumber, textChannel, oldTopic));
        }
        if (oldPosition != position) {
            textChannel.setRawPosition(position);
            api.getEventManager()
                    .handle(new TextChannelUpdatePositionEvent(api, responseNumber, textChannel, oldPosition));
        }

        if (oldNsfw != nsfw) {
            textChannel.setNSFW(nsfw);
            api.getEventManager()
                    .handle(new TextChannelUpdateNSFWEvent(api, responseNumber, textChannel, nsfw));
        }

        applyPermissions(textChannel, content, permOverwrites, contained, changed);

        //If this update modified permissions in any way.
        if (!changed.isEmpty()) {
            api.getEventManager()
                    .handle(new TextChannelUpdatePermissionsEvent(api, responseNumber, textChannel, changed));
        }
        break; //Finish the TextChannelUpdate case
    }
    case VOICE: {
        VoiceChannelImpl voiceChannel = (VoiceChannelImpl) api.getVoiceChannelMap().get(channelId);
        int userLimit = content.getInt("user_limit");
        int bitrate = content.getInt("bitrate");
        if (voiceChannel == null) {
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "CHANNEL_UPDATE attempted to update a VoiceChannel that does not exist. JSON: " + content);
            return null;
        }
        //If any properties changed, update the values and fire the proper events.
        final String oldName = voiceChannel.getName();
        final int oldPosition = voiceChannel.getPositionRaw();
        final int oldLimit = voiceChannel.getUserLimit();
        final int oldBitrate = voiceChannel.getBitrate();
        if (!Objects.equals(oldName, name)) {
            voiceChannel.setName(name);
            api.getEventManager()
                    .handle(new VoiceChannelUpdateNameEvent(api, responseNumber, voiceChannel, oldName));
        }
        if (oldPosition != position) {
            voiceChannel.setRawPosition(position);
            api.getEventManager().handle(
                    new VoiceChannelUpdatePositionEvent(api, responseNumber, voiceChannel, oldPosition));
        }
        if (oldLimit != userLimit) {
            voiceChannel.setUserLimit(userLimit);
            api.getEventManager()
                    .handle(new VoiceChannelUpdateUserLimitEvent(api, responseNumber, voiceChannel, oldLimit));
        }
        if (oldBitrate != bitrate) {
            voiceChannel.setBitrate(bitrate);
            api.getEventManager()
                    .handle(new VoiceChannelUpdateBitrateEvent(api, responseNumber, voiceChannel, oldBitrate));
        }

        applyPermissions(voiceChannel, content, permOverwrites, contained, changed);

        //If this update modified permissions in any way.
        if (!changed.isEmpty()) {
            api.getEventManager()
                    .handle(new VoiceChannelUpdatePermissionsEvent(api, responseNumber, voiceChannel, changed));
        }
        break; //Finish the VoiceChannelUpdate case
    }
    default:
        throw new IllegalArgumentException(
                "CHANNEL_UPDATE provided an unrecognized channel type JSON: " + content);
    }
    return null;
}

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

private void handlePermissionOverride(JSONObject override, AbstractChannelImpl<?> channel, JSONObject content,
        List<IPermissionHolder> changedPermHolders, List<IPermissionHolder> containedPermHolders) {
    final long id = override.getLong("id");
    final long allow = override.getLong("allow");
    final long deny = override.getLong("deny");
    final IPermissionHolder permHolder;

    switch (override.getString("type")) {
    case "role": {
        permHolder = channel.getGuild().getRoleById(id);

        if (permHolder == null) {
            api.getEventCache().cache(EventCache.Type.ROLE, id, () -> handlePermissionOverride(override,
                    channel, content, changedPermHolders, containedPermHolders));
            EventCache.LOG.debug(/*www .j av  a2s.c om*/
                    "CHANNEL_UPDATE attempted to create or update a PermissionOverride for a Role that doesn't exist! RoleId: "
                            + id + " JSON: " + content);
            return;
        }
        break;
    }
    case "member": {
        permHolder = channel.getGuild().getMemberById(id);
        if (permHolder == null) {
            api.getEventCache().cache(EventCache.Type.USER, id, () -> handlePermissionOverride(override,
                    channel, content, changedPermHolders, containedPermHolders));
            EventCache.LOG.debug(
                    "CHANNEL_UPDATE attempted to create or update a PermissionOverride for Member that doesn't exist in this Guild! MemberId: "
                            + id + " JSON: " + content);
            return;
        }
        break;
    }
    default:
        throw new IllegalArgumentException(
                "CHANNEL_UPDATE provided an unrecognized PermissionOverride type. JSON: " + content);
    }

    PermissionOverrideImpl permOverride = (PermissionOverrideImpl) channel.getOverrideMap().get(id);

    if (permOverride == null) //Created
    {
        api.getEntityBuilder().createPermissionOverride(override, channel);
        changedPermHolders.add(permHolder);
    } else if (permOverride.getAllowedRaw() != allow || permOverride.getDeniedRaw() != deny) //Updated
    {
        permOverride.setAllow(allow);
        permOverride.setDeny(deny);
        changedPermHolders.add(permHolder);
    }
    containedPermHolders.add(permHolder);
}

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

private void handleGroup(JSONObject content) {
    final long groupId = content.getLong("id");
    final long ownerId = content.getLong("owner_id");
    final String name = content.isNull("name") ? null : content.getString("name");
    final String iconId = content.isNull("icon") ? null : content.getString("icon");

    GroupImpl group = (GroupImpl) api.asClient().getGroupById(groupId);
    if (group == null) {
        api.getEventCache().cache(EventCache.Type.CHANNEL, groupId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug("Received CHANNEL_UPDATE for a group that was not yet cached. JSON: " + content);
        return;/*ww w.ja  va  2s. c o m*/
    }

    final User owner = group.getUserMap().get(ownerId);
    final User oldOwner = group.getOwner();
    final String oldName = group.getName();
    final String oldIconId = group.getIconId();

    if (owner == null) {
        EventCache.LOG.warn(
                "Received CHANNEL_UPDATE for a group with an owner_id for a user that is not cached. owner_id: "
                        + ownerId);
    } else {
        if (!Objects.equals(owner, oldOwner)) {
            group.setOwner(owner);
            api.getEventManager().handle(new GroupUpdateOwnerEvent(api, responseNumber, group, oldOwner));
        }
    }

    if (!Objects.equals(name, oldName)) {
        group.setName(name);
        api.getEventManager().handle(new GroupUpdateNameEvent(api, responseNumber, group, oldName));
    }
    if (!Objects.equals(iconId, oldIconId)) {
        group.setIconId(iconId);
        api.getEventManager().handle(new GroupUpdateIconEvent(api, responseNumber, group, oldIconId));
    }
}