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.co.petertribble.jproc.parse.JSONParser.java

private static JProcStatus getStatus(JSONObject jo) {
    JProcStatus jps = new JProcStatus();
    try {/*from  ww w  .java 2s.  c o  m*/
        jps.insert(jo.getInt("lwpid"), jo.getLong("utime"), jo.getLong("nutime"), jo.getLong("stime"),
                jo.getLong("nstime"), jo.getLong("cutime"), jo.getLong("ncutime"), jo.getLong("cstime"),
                jo.getLong("ncstime"));
    } catch (JSONException jse) {
        return null;
    }
    return jps;
}

From source file:uk.co.petertribble.jproc.parse.JSONParser.java

private static JProcUsage getUsage(JSONObject jo) {
    JProcUsage jpu = new JProcUsage();
    try {/*from  w  w  w . ja  v a 2 s .  c  o m*/
        jpu.insert(jo.getInt("lwpid"), jo.getInt("count"), jo.getLong("rtime"), jo.getLong("nrtime"),
                jo.getLong("utime"), jo.getLong("nutime"), jo.getLong("stime"), jo.getLong("nstime"),
                jo.getLong("minf"), jo.getLong("majf"), jo.getLong("nswap"), jo.getLong("inblk"),
                jo.getLong("oublk"), jo.getLong("msnd"), jo.getLong("mrcv"), jo.getLong("sigs"),
                jo.getLong("vctx"), jo.getLong("ictx"), jo.getLong("sysc"), jo.getLong("ioch"));
    } catch (JSONException jse) {
        return null;
    }
    return jpu;
}

From source file:uk.co.petertribble.jproc.parse.JSONParser.java

private static JProcInfo getInfo(JSONObject jo) {
    JProcInfo jpi = new JProcInfo();
    try {/* ww w  .j  a  v  a2  s. c o m*/
        jpi.insert(jo.getInt("pid"), jo.getInt("ppid"), jo.getInt("uid"), jo.getInt("euid"), jo.getInt("gid"),
                jo.getInt("egid"), jo.getInt("nlwp"), jo.getLong("size"), jo.getLong("rssize"),
                jo.getLong("stime"), jo.getLong("etime"), jo.getLong("ntime"), jo.getLong("ectime"),
                jo.getLong("nctime"), jo.getInt("taskid"), jo.getInt("projid"), jo.getInt("zoneid"),
                jo.getInt("contract"), jo.getString("fname"));
    } catch (JSONException jse) {
        return null;
    }
    return jpi;
}

From source file:uk.co.petertribble.jproc.parse.JSONParser.java

private static JProcLwpStatus getLwpStatus(JSONObject jo) {
    JProcLwpStatus jpls = new JProcLwpStatus();
    try {/*  www.  j a  va2s.  c  o m*/
        jpls.insert(jo.getInt("pid"), jo.getInt("lwpid"), jo.getLong("utime"), jo.getLong("nutime"),
                jo.getLong("stime"), jo.getLong("nstime"));
    } catch (JSONException jse) {
        return null;
    }
    return jpls;
}

From source file:uk.co.petertribble.jproc.parse.JSONParser.java

private static JProcLwpInfo getLwpInfo(JSONObject jo) {
    JProcLwpInfo jpli = new JProcLwpInfo();
    try {/*from w  w  w .  j a  v a  2 s  .c om*/
        jpli.insert(jo.getInt("pid"), jo.getInt("lwpid"), jo.getLong("stime"), jo.getLong("etime"),
                jo.getLong("ntime"));
    } catch (JSONException jse) {
        return null;
    }
    return jpli;
}

From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java

@Override
public DaemonTaskResult executeTask(Log log, DaemonTask task) {

    try {//from  w ww  .ja v a  2s .  c  om

        // Get the server version
        if (rpcVersion <= -1) {
            // Get server session statistics
            JSONObject response = makeRequest(log, buildRequestObject("session-get", new JSONObject()));
            rpcVersion = response.getJSONObject("arguments").getInt("rpc-version");
        }

        JSONObject request = new JSONObject();
        switch (task.getMethod()) {
        case Retrieve:

            // Request all torrents from server
            JSONArray fields = new JSONArray();
            final String[] fieldsArray = new String[] { RPC_ID, RPC_NAME, RPC_ERROR, RPC_ERRORSTRING,
                    RPC_STATUS, RPC_DOWNLOADDIR, RPC_RATEDOWNLOAD, RPC_RATEUPLOAD, RPC_PEERSGETTING,
                    RPC_PEERSSENDING, RPC_PEERSCONNECTED, RPC_ETA, RPC_DOWNLOADSIZE1, RPC_DOWNLOADSIZE2,
                    RPC_UPLOADEDEVER, RPC_TOTALSIZE, RPC_DATEADDED, RPC_DATEDONE, RPC_AVAILABLE, RPC_COMMENT };
            for (String field : fieldsArray) {
                fields.put(field);
            }
            request.put("fields", fields);

            JSONObject result = makeRequest(log, buildRequestObject("torrent-get", request));
            return new RetrieveTaskSuccessResult((RetrieveTask) task,
                    parseJsonRetrieveTorrents(result.getJSONObject("arguments")), null);

        case GetStats:

            // Request the current server statistics
            JSONObject stats = makeRequest(log, buildRequestObject("session-get", new JSONObject()))
                    .getJSONObject("arguments");
            return new GetStatsTaskSuccessResult((GetStatsTask) task, stats.getBoolean("alt-speed-enabled"),
                    rpcVersion >= 12 ? stats.getLong("download-dir-free-space") : -1);

        case GetTorrentDetails:

            // Request fine details of a specific torrent
            JSONArray dfields = new JSONArray();
            dfields.put("trackers");
            dfields.put("trackerStats");

            JSONObject buildDGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null,
                    false);
            buildDGet.put("fields", dfields);
            JSONObject getDResult = makeRequest(log, buildRequestObject("torrent-get", buildDGet));
            return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
                    parseJsonTorrentDetails(getDResult.getJSONObject("arguments")));

        case GetFileList:

            // Request all details for a specific torrent
            JSONArray ffields = new JSONArray();
            ffields.put("files");
            ffields.put("fileStats");

            JSONObject buildGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false);
            buildGet.put("fields", ffields);
            JSONObject getResult = makeRequest(log, buildRequestObject("torrent-get", buildGet));
            return new GetFileListTaskSuccessResult((GetFileListTask) task,
                    parseJsonFileList(getResult.getJSONObject("arguments"), task.getTargetTorrent()));

        case AddByFile:

            // Add a torrent to the server by sending the contents of a local .torrent file
            String file = ((AddByFileTask) task).getFile();

            // Encode the .torrent file's data
            InputStream in = new Base64.InputStream(new FileInputStream(new File(URI.create(file))),
                    Base64.ENCODE);
            StringWriter writer = new StringWriter();
            int c;
            while ((c = in.read()) != -1) {
                writer.write(c);
            }
            in.close();

            // Request to add a torrent by Base64-encoded meta data
            request.put("metainfo", writer.toString());

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case AddByUrl:

            // Request to add a torrent by URL
            String url = ((AddByUrlTask) task).getUrl();
            request.put("filename", url);

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case AddByMagnetUrl:

            // Request to add a magnet link by URL
            String magnet = ((AddByMagnetUrlTask) task).getUrl();
            request.put("filename", magnet);

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case Remove:

            // Remove a torrent
            RemoveTask removeTask = (RemoveTask) task;
            makeRequest(log,
                    buildRequestObject("torrent-remove",
                            buildTorrentRequestObject(removeTask.getTargetTorrent().getUniqueID(),
                                    "delete-local-data", removeTask.includingData())));
            return new DaemonTaskSuccessResult(task);

        case Pause:

            // Pause a torrent
            PauseTask pauseTask = (PauseTask) task;
            makeRequest(log, buildRequestObject("torrent-stop",
                    buildTorrentRequestObject(pauseTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        case PauseAll:

            // Resume all torrents
            makeRequest(log,
                    buildRequestObject("torrent-stop", buildTorrentRequestObject(FOR_ALL, null, false)));
            return new DaemonTaskSuccessResult(task);

        case Resume:

            // Resume a torrent
            ResumeTask resumeTask = (ResumeTask) task;
            makeRequest(log, buildRequestObject("torrent-start",
                    buildTorrentRequestObject(resumeTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        case ResumeAll:

            // Resume all torrents
            makeRequest(log,
                    buildRequestObject("torrent-start", buildTorrentRequestObject(FOR_ALL, null, false)));
            return new DaemonTaskSuccessResult(task);

        case SetDownloadLocation:

            // Change the download location
            SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task;
            // Build request
            JSONObject sdlrequest = new JSONObject();
            JSONArray sdlids = new JSONArray();
            sdlids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
            sdlrequest.put("ids", sdlids);
            sdlrequest.put("location", sdlTask.getNewLocation());
            sdlrequest.put("move", true);
            makeRequest(log, buildRequestObject("torrent-set-location", sdlrequest));
            return new DaemonTaskSuccessResult(task);

        case SetFilePriorities:

            // Set priorities of the files of some torrent
            SetFilePriorityTask prioTask = (SetFilePriorityTask) task;

            // Build request
            JSONObject prequest = new JSONObject();
            JSONArray ids = new JSONArray();
            ids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
            prequest.put("ids", ids);
            JSONArray fileids = new JSONArray();
            for (TorrentFile forfile : prioTask.getForFiles()) {
                fileids.put(Integer.parseInt(forfile.getKey())); // The keys are the indices of the files, so always numeric
            }
            switch (prioTask.getNewPriority()) {
            case Off:
                prequest.put("files-unwanted", fileids);
                break;
            case Low:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-low", fileids);
                break;
            case Normal:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-normal", fileids);
                break;
            case High:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-high", fileids);
                break;
            }

            makeRequest(log, buildRequestObject("torrent-set", prequest));
            return new DaemonTaskSuccessResult(task);

        case SetTransferRates:

            // Request to set the maximum transfer rates
            SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
            if (ratesTask.getUploadRate() == null) {
                request.put("speed-limit-up-enabled", false);
            } else {
                request.put("speed-limit-up-enabled", true);
                request.put("speed-limit-up", ratesTask.getUploadRate().intValue());
            }
            if (ratesTask.getDownloadRate() == null) {
                request.put("speed-limit-down-enabled", false);
            } else {
                request.put("speed-limit-down-enabled", true);
                request.put("speed-limit-down", ratesTask.getDownloadRate().intValue());
            }

            makeRequest(log, buildRequestObject("session-set", request));
            return new DaemonTaskSuccessResult(task);

        case SetAlternativeMode:

            // Request to set the alternative speed mode (Tutle Mode)
            SetAlternativeModeTask altModeTask = (SetAlternativeModeTask) task;
            request.put("alt-speed-enabled", altModeTask.isAlternativeModeEnabled());
            makeRequest(log, buildRequestObject("session-set", request));
            return new DaemonTaskSuccessResult(task);

        case ForceRecheck:

            // Verify torrent data integrity
            ForceRecheckTask verifyTask = (ForceRecheckTask) task;
            makeRequest(log, buildRequestObject("torrent-verify",
                    buildTorrentRequestObject(verifyTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        default:
            return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
                    task.getMethod() + " is not supported by " + getType()));
        }
    } catch (JSONException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.ParsingFailed, e.toString()));
    } catch (DaemonException e) {
        return new DaemonTaskFailureResult(task, e);
    } catch (FileNotFoundException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.FileAccessError, e.toString()));
    } catch (IOException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.FileAccessError, e.toString()));
    }
}

From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java

private ArrayList<Torrent> parseJsonRetrieveTorrents(JSONObject response) throws JSONException {

    // Parse response
    ArrayList<Torrent> torrents = new ArrayList<Torrent>();
    JSONArray rarray = response.getJSONArray("torrents");
    for (int i = 0; i < rarray.length(); i++) {
        JSONObject tor = rarray.getJSONObject(i);
        // Add the parsed torrent to the list
        float have = (float) (tor.getLong(RPC_DOWNLOADSIZE1) + tor.getLong(RPC_DOWNLOADSIZE2));
        long total = tor.getLong(RPC_TOTALSIZE);
        // Error is a number, see https://trac.transmissionbt.com/browser/trunk/libtransmission/transmission.h#L1747
        // We only consider it a real error if it is local (blocking), which is error code 3
        boolean hasError = tor.getInt(RPC_ERROR) == 3;
        String errorString = tor.getString(RPC_ERRORSTRING).trim();
        String commentString = tor.getString(RPC_COMMENT).trim();
        if (!commentString.equals("")) {
            errorString = errorString.equals("") ? commentString : errorString + "\n" + commentString;
        }//from  w  ww .  j ava2 s . c  o  m
        String locationDir = tor.getString(RPC_DOWNLOADDIR);
        if (!locationDir.endsWith(settings.getOS().getPathSeperator())) {
            locationDir += settings.getOS().getPathSeperator();
        }
        // @formatter:off
        torrents.add(new Torrent(tor.getInt(RPC_ID), null, tor.getString(RPC_NAME),
                hasError ? TorrentStatus.Error : getStatus(tor.getInt(RPC_STATUS)), locationDir,
                tor.getInt(RPC_RATEDOWNLOAD), tor.getInt(RPC_RATEUPLOAD), tor.getInt(RPC_PEERSSENDING),
                tor.getInt(RPC_PEERSCONNECTED), tor.getInt(RPC_PEERSGETTING), tor.getInt(RPC_PEERSCONNECTED),
                tor.getInt(RPC_ETA), tor.getLong(RPC_DOWNLOADSIZE1) + tor.getLong(RPC_DOWNLOADSIZE2),
                tor.getLong(RPC_UPLOADEDEVER), tor.getLong(RPC_TOTALSIZE),
                //(float) tor.getDouble(RPC_PERCENTDONE),
                (total == 0 ? 0 : have / (float) total),
                (total == 0 ? 0 : (have + (float) tor.getLong(RPC_AVAILABLE)) / (float) total),
                // No label/category/group support in the RPC API for now
                null, new Date(tor.getLong(RPC_DATEADDED) * 1000L), new Date(tor.getLong(RPC_DATEDONE) * 1000L),
                errorString, settings.getType()));
        // @formatter:on
    }

    // Return the list
    return torrents;

}

From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java

private ArrayList<TorrentFile> parseJsonFileList(JSONObject response, Torrent torrent) throws JSONException {

    // Parse response
    ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>();
    JSONArray rarray = response.getJSONArray("torrents");
    if (rarray.length() > 0) {
        JSONArray files = rarray.getJSONObject(0).getJSONArray("files");
        JSONArray fileStats = rarray.getJSONObject(0).getJSONArray("fileStats");
        for (int i = 0; i < files.length(); i++) {
            JSONObject file = files.getJSONObject(i);
            JSONObject stat = fileStats.getJSONObject(i);
            // @formatter:off
            torrentfiles.add(new TorrentFile(String.valueOf(i), file.getString(RPC_FILE_NAME),
                    file.getString(RPC_FILE_NAME), torrent.getLocationDir() + file.getString(RPC_FILE_NAME),
                    file.getLong(RPC_FILE_LENGTH), file.getLong(RPC_FILE_COMPLETED),
                    convertTransmissionPriority(stat.getBoolean(RPC_FILESTAT_WANTED),
                            stat.getInt(RPC_FILESTAT_PRIORITY))));
            // @formatter:on
        }/*from   www  .jav a  2 s  . c  o m*/
    }

    // Return the list
    return torrentfiles;

}

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

@Override
protected Long handleInternally(JSONObject content) {
    EntityBuilder builder = api.getEntityBuilder();

    //Core/*from  w  w  w .  ja  v  a2s  .c o  m*/
    JSONArray guilds = content.getJSONArray("guilds");
    JSONObject selfJson = content.getJSONObject("user");

    builder.createSelfUser(selfJson);

    if (api.getAccountType() == AccountType.CLIENT && !content.isNull("user_settings")) {
        // handle user settings
        JSONObject userSettingsJson = content.getJSONObject("user_settings");
        UserSettingsImpl userSettingsObj = (UserSettingsImpl) api.asClient().getSettings();
        userSettingsObj
                // TODO: set all information and handle updates
                .setStatus(userSettingsJson.isNull("status") ? OnlineStatus.ONLINE
                        : OnlineStatus.fromKey(userSettingsJson.getString("status")));
        // update presence information unless the status is ONLINE
        if (userSettingsObj.getStatus() != OnlineStatus.ONLINE)
            ((PresenceImpl) api.getPresence()).setCacheStatus(userSettingsObj.getStatus());
    }

    //Keep a list of all guilds in incompleteGuilds that need to be setup (GuildMemberChunk / GuildSync)
    //Send all guilds to the EntityBuilder's first pass to setup caching for when GUILD_CREATE comes
    // or, for Client accounts, to start the setup process (since we already have guild info)
    //Callback points to guildSetupComplete so that when MemberChunking and GuildSync processes are done, we can
    // "check off" the completed guild from the set of guilds in incompleteGuilds.

    for (int i = 0; i < guilds.length(); i++) {
        JSONObject guild = guilds.getJSONObject(i);
        incompleteGuilds.add(guild.getLong("id"));
    }

    //We use two different for-loops here so that we cache all of the ids before sending them off to the EntityBuilder
    //  due to the checks in checkIfReadyToSendRequests and guildSetupComplete triggering too soon otherwise.
    // Specifically: incompleteGuilds.size() == acknowledgedGuilds.size() and
    //  incompleteGuilds.size() == unavailableGuilds.size() respectively.

    for (int i = 0; i < guilds.length(); i++) {
        JSONObject guild = guilds.getJSONObject(i);

        //If a Guild isn't unavailable, then it is possible that we were given all information
        // needed to fully load the guild. In this case, we provide the method `guildSetupComplete`
        // as the secondPassCallback so it can immediately be called to signify that the provided guild
        // is loaded and ready to go.
        //If a Guild is unavailable it won't have the information needed, so we pass null as the secondPassCallback
        // for now and wait for the GUILD_CREATE event to give us the required information.
        if (guild.has("unavailable") && guild.getBoolean("unavailable"))
            builder.createGuildFirstPass(guild, null);
        else
            builder.createGuildFirstPass(guild, this::guildSetupComplete);
    }

    if (guilds.length() == 0)
        guildLoadComplete(content);

    return null;
}

From source file:com.appdynamics.monitors.nginx.statsExtractor.CachesStatsExtractor.java

private Map<String, String> getCachesStats(JSONObject caches) {
    Map<String, String> cachesStats = new HashMap<String, String>();
    Set<String> cacheNames = caches.keySet();

    for (String cacheName : cacheNames) {
        JSONObject cache = caches.getJSONObject(cacheName);

        long size = cache.getLong("size");
        cachesStats.put("caches|" + cacheName + "|size", String.valueOf(size));

        long max_size = cache.getLong("max_size");
        cachesStats.put("caches|" + cacheName + "|max_size", String.valueOf(max_size));

        boolean cold = cache.getBoolean("cold");
        cachesStats.put("caches|" + cacheName + "|cold", String.valueOf(cold ? 0 : 1));

        for (String s : new String[] { "hit", "stale", "updating", "revalidated" }) {
            JSONObject jsonObject = cache.getJSONObject(s);
            long responses = jsonObject.getLong("responses");
            cachesStats.put("caches|" + cacheName + "|" + s + "|responses", String.valueOf(responses));

            long bytes = jsonObject.getLong("bytes");
            cachesStats.put("caches|" + cacheName + "|" + s + "|bytes", String.valueOf(bytes));
        }//  w w w .  j  av a  2  s.  c o m

        for (String s : new String[] { "miss", "expired", "bypass" }) {
            JSONObject jsonObject = cache.getJSONObject(s);
            long responses = jsonObject.getLong("responses");
            cachesStats.put("caches|" + cacheName + "|" + s + "|responses", String.valueOf(responses));

            long bytes = jsonObject.getLong("bytes");
            cachesStats.put("caches|" + cacheName + "|" + s + "|bytes", String.valueOf(bytes));

            long responses_written = jsonObject.getLong("responses_written");
            cachesStats.put("caches|" + cacheName + "|" + s + "|responses_written",
                    String.valueOf(responses_written));

            long bytes_written = jsonObject.getLong("bytes_written");
            cachesStats.put("caches|" + cacheName + "|" + s + "|bytes_written", String.valueOf(bytes_written));
        }
    }
    return cachesStats;
}