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.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get Long from jsonObject/* w  ww .  j  ava 2s.c  o m*/
 *
 * @param jsonObject
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if key is null or empty, return defaultValue</li>
 * <li>if {@link JSONObject#getLong(String)} exception, return defaultValue</li>
 * <li>return {@link JSONObject#getLong(String)}</li>
 * </ul>
 */
public static Long getLong(JSONObject jsonObject, String key, Long defaultValue) {
    if (jsonObject == null || StringUtils.isEmpty(key)) {
        return defaultValue;
    }

    try {
        return jsonObject.getLong(key);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

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

@Override
protected Long handleInternally(JSONObject content) {
    Guild g = api.getGuildById(content.getLong("id"));
    Boolean wasAvail = (g == null || g.getName() == null) ? null : g.isAvailable();
    api.getEntityBuilder().createGuildFirstPass(content, guild -> {
        if (guild.isAvailable()) {
            if (!api.getClient().isReady()) {
                api.getClient().<ReadyHandler>getHandler("READY").guildSetupComplete(guild);
            } else {
                if (wasAvail == null) //didn't exist
                {/*from  www.java 2 s .  c  o m*/
                    api.getEventManager().handle(new GuildJoinEvent(api, responseNumber, guild));
                    api.getEventCache().playbackCache(EventCache.Type.GUILD, guild.getIdLong());
                } else if (!wasAvail) //was previously unavailable
                {
                    api.getEventManager().handle(new GuildAvailableEvent(api, responseNumber, guild));
                } else {
                    throw new RuntimeException("Got a GuildCreateEvent for a guild that already existed! Json: "
                            + content.toString());
                }
            }
        } else {
            if (!api.getClient().isReady()) {
                api.getClient().<ReadyHandler>getHandler("READY").acknowledgeGuild(guild, false, false, false);
            } else {
                //Proper GuildJoinedEvent is fired when guild was populated
                api.getEventManager()
                        .handle(new UnavailableGuildJoinedEvent(api, responseNumber, guild.getIdLong()));
            }
        }
    });
    return null;
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

public void sendChangesToCozy() {
    List<LoyaltyCard> unSyncedLoyaltyCards = LoyaltyCard.getAllUnsynced();
    int i = 0;// ww  w  .  ja v a  2s.co  m
    for (LoyaltyCard loyaltyCard : unSyncedLoyaltyCards) {
        URL urlO = null;
        try {
            JSONObject jsonObject = loyaltyCard.toJsonObject();
            mBuilder.setProgress(unSyncedLoyaltyCards.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new LoyaltyCardSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                loyaltyCard.setRemoteId(result);
                loyaltyCard.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:io.sponges.dubtrack4j.internal.subscription.callback.PlaylistUpdateCall.java

@Override
public void run(JSONObject json) throws IOException {
    int startTime = json.getInt("startTime");
    if (startTime != -1)
        return; // prevent double call

    JSONObject song = json.getJSONObject("song");
    JSONObject songInfo = json.getJSONObject("songInfo");

    String playlistId = song.getString("_id");
    String userId = song.getString("userid");
    String roomId = song.getString("roomid");
    long time = song.getLong("created");
    String songId = song.getString("songid");

    String songName = songInfo.getString("name");
    long songLength = songInfo.getLong("songLength");

    String sourceTypeId = songInfo.getString("type");
    SongInfo.SourceType sourceType = SongInfo.SourceType.valueOf(sourceTypeId.toUpperCase());
    String sourceId = songInfo.getString("fkid");

    RoomImpl room = dubtrack.loadRoom(roomId);
    User user = room.getOrLoadUser(userId);

    SongInfo sInfo = new SongInfo(songName, songLength, sourceType);
    if (sourceType == SongInfo.SourceType.YOUTUBE) {
        sInfo.setYoutubeId(sourceId);// w  ww  .ja  v a2 s .co m
    } else {
        sInfo.setSoundcloudId(sourceId);
    }

    Song s = new SongImpl(dubtrack, songId, user, room, sInfo);

    Song previous = room.getCurrentSong();
    room.setCurrent(s);
    room.setPlaylistId(playlistId);
    room.getInternalRoomQueue().remove(previous);
    room.loadRoomQueue(); // updating the queue

    dubtrack.getEventBus().post(new SongChangeEvent(previous, s, room));
}

From source file:edu.cwru.apo.Home.java

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.phone) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    SharedPreferences.Editor editor = getSharedPreferences(APO.PREF_FILE_NAME, MODE_PRIVATE)
                            .edit();/*from ww w  . j a  v  a2  s. co m*/
                    editor.putLong("updateTime", result.getLong("updateTime"));
                    editor.commit();
                    int numbros = result.getInt("numBros");
                    JSONArray caseID = result.getJSONArray("caseID");
                    JSONArray first = result.getJSONArray("first");
                    JSONArray last = result.getJSONArray("last");
                    JSONArray phone = result.getJSONArray("phone");
                    JSONArray family = result.getJSONArray("family");
                    ContentValues values;
                    for (int i = 0; i < numbros; i++) {
                        values = new ContentValues();
                        values.put("_id", caseID.getString(i));
                        values.put("first", first.getString(i));
                        values.put("last", last.getString(i));
                        values.put("phone", phone.getString(i));
                        values.put("family", family.getString(i));
                        database.replace("phoneDB", null, values);
                    }
                } else if (requestStatus.compareTo("timestamp invalid") == 0) {
                    Toast msg = Toast.makeText(this, "Invalid timestamp.  Please try again.",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("HMAC invalid") == 0) {
                    Auth.loggedIn = false;
                    Toast msg = Toast.makeText(this,
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                    finish();
                } else {
                    Toast msg = Toast.makeText(this, "Invalid requestStatus", Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else if (method == Methods.checkAppVersion) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    String appVersion = result.getString("version");
                    String appDate = result.getString("date");
                    final String appUrl = result.getString("url");
                    PackageInfo pinfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
                    ;
                    if (appVersion.compareTo(pinfo.versionName) != 0) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("Upgrade");
                        builder.setMessage("Update available, ready to upgrade?");
                        builder.setIcon(R.drawable.icon);
                        builder.setCancelable(false);
                        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent promptInstall = new Intent("android.intent.action.VIEW",
                                        Uri.parse("https://apo.case.edu:8090/app/" + appUrl));
                                startActivity(promptInstall);
                            }
                        });
                        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    } else {
                        Toast msg = Toast.makeText(this, "No updates found", Toast.LENGTH_LONG);
                        msg.show();
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NameNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private void handleFeedResponse(JSONObject jsonResponse, FeedListener listener) {
    FbSimplePost post;/* ww w.  j  a v  a  2s .c om*/
    ArrayList<FbSimplePost> posts = new ArrayList<FbSimplePost>();

    try {
        JSONArray objs = jsonResponse.getJSONArray("data");

        for (int i = 0; i < objs.length(); i++) {
            JSONObject obj = objs.getJSONObject(i);

            post = new FbSimplePost();
            post.setId(obj.getString("id"));

            JSONObject fromJson = obj.optJSONObject("from");
            if (fromJson != null) {
                FbSimpleUser from = new FbSimpleUser();
                from.setId(fromJson.getString("id"));
                from.setName(fromJson.getString("name"));

                post.setFrom(from);
            }

            post.setMessage(obj.optString("message"));
            post.setPicture(obj.optString("picture"));
            post.setLink(obj.optString("link"));
            post.setName(obj.optString("name"));
            post.setCaption(obj.optString("caption"));
            post.setDescription(obj.optString("description"));
            post.setSource(obj.optString("source"));
            post.setType(obj.optString("type"));

            post.setCreatedTime(new Date(obj.getLong("created_time")));
            post.setUpdatedTime(new Date(obj.getLong("updated_time")));

            JSONObject comments = obj.optJSONObject("comments");
            if (comments != null) {
                post.setNumberOfComments(comments.getInt("count"));
            }

            JSONObject likes = obj.optJSONObject("likes");
            if (likes != null) {
                post.setNumberOfLikes(likes.getInt("count"));
            }

            posts.add(post);
        }

        String nextPage = null;
        JSONObject paging = jsonResponse.optJSONObject("paging");
        if (paging != null) {
            nextPage = paging.optString("next");
        }

        listener.onComplete(posts, nextPage);

    } catch (JSONException e) {
        Util.logd(TAG, "Could not parse Json response", e);
        listener.onFail(e);
    }
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private FbEvent parseEvent(JSONObject eventJson) throws JSONException {
    FbEvent event = new FbEvent();

    event.setId(eventJson.getString("id"));
    event.setName(eventJson.getString("name"));
    event.setDescription(eventJson.optString("description"));
    event.setStartTime(dateWithFacebookUnixTimestamp(eventJson.getLong("start_time")));
    event.setEndTime(dateWithFacebookUnixTimestamp(eventJson.optLong("end_time")));
    event.setLocation(eventJson.optString("location"));
    event.setPrivacy(eventJson.optString("privacy"));

    JSONObject ownerJson = eventJson.optJSONObject("owner");
    if (ownerJson != null) {
        FbSimpleUser owner = new FbSimpleUser();
        owner.setId(ownerJson.getString("id"));
        owner.setName(ownerJson.optString("name"));
        event.setOwner(owner);// www . j a va2s.c  om
    }

    return event;
}

From source file:com.jellymold.boss.ImageSearch.java

protected void parseResults(JSONObject jobj) throws JSONException {

    if (jobj != null) {

        setResponseCode(jobj.getInt("responsecode"));
        if (jobj.has("nextpage"))
            setNextPage(jobj.getString("nextpage"));
        if (jobj.has("prevpage"))
            setPrevPage(jobj.getString("prevpage"));
        setTotalResults(jobj.getLong("totalhits"));
        long count = jobj.getLong("count");
        setPagerCount(count);/*from  w  ww.j  a va2s.co m*/
        setPagerStart(jobj.getLong("start"));
        this.setResults(new ArrayList<ImageSearchResult>((int) count));

        if (jobj.has("resultset_images")) {

            JSONArray res = jobj.getJSONArray("resultset_images");
            for (int i = 0; i < res.length(); i++) {
                JSONObject thisResult = res.getJSONObject(i);
                ImageSearchResult imageSearchResult = new ImageSearchResult();
                imageSearchResult.setDescription(thisResult.getString("abstract"));
                imageSearchResult.setClickUrl(thisResult.getString("clickurl"));
                imageSearchResult.setDate(thisResult.getString("date"));
                imageSearchResult.setTitle(thisResult.getString("title"));
                imageSearchResult.setUrl(thisResult.getString("url"));
                imageSearchResult.setSize(thisResult.getLong("size"));
                imageSearchResult.setFilename(thisResult.getString("filename"));
                imageSearchResult.setFormat(thisResult.getString("format"));
                imageSearchResult.setHeight(thisResult.getLong("height"));
                imageSearchResult.setMimeType(thisResult.getString("mimetype"));
                imageSearchResult.setRefererClickUrl(thisResult.getString("refererclickurl"));
                imageSearchResult.setRefererUrl(thisResult.getString("refererurl"));
                imageSearchResult.setThumbnailHeight(thisResult.getLong("thumbnail_height"));
                imageSearchResult.setThumbnailWidth(thisResult.getLong("thumbnail_width"));
                imageSearchResult.setThumbnailUrl(thisResult.getString("thumbnail_url"));
                this.getResults().add(imageSearchResult);
            }
        }
    }

}

From source file:org.b3log.solo.processor.util.Filler.java

/**
 * Fills archive dates.//from w  w  w.java 2s  . c o  m
 *
 * @param dataModel data model
 * @param preference the specified preference
 * @throws ServiceException service exception
 */
public void fillArchiveDates(final Map<String, Object> dataModel, final JSONObject preference)
        throws ServiceException {
    Stopwatchs.start("Fill Archive Dates");

    try {
        LOGGER.finer("Filling archive dates....");
        final List<JSONObject> archiveDates = archiveDateRepository.getArchiveDates();

        final String localeString = preference.getString(Preference.LOCALE_STRING);
        final String language = Locales.getLanguage(localeString);

        for (final JSONObject archiveDate : archiveDates) {
            final long time = archiveDate.getLong(ArchiveDate.ARCHIVE_TIME);
            final String dateString = ArchiveDate.DATE_FORMAT.format(time);
            final String[] dateStrings = dateString.split("/");
            final String year = dateStrings[0];
            final String month = dateStrings[1];
            archiveDate.put(ArchiveDate.ARCHIVE_DATE_YEAR, year);

            archiveDate.put(ArchiveDate.ARCHIVE_DATE_MONTH, month);
            if ("en".equals(language)) {
                final String monthName = Dates.EN_MONTHS.get(month);
                archiveDate.put(Common.MONTH_NAME, monthName);
            }
        }

        dataModel.put(ArchiveDate.ARCHIVE_DATES, archiveDates);
    } catch (final JSONException e) {
        LOGGER.log(Level.SEVERE, "Fills archive dates failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, "Fills archive dates failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}

From source file:com.esri.cordova.geolocation.AdvancedGeolocation.java

private void parseArgs(JSONArray args) {
    Log.d(TAG, "Execute args: " + args.toString());
    if (args.length() > 0) {
        try {/*from  w w w. j av a2  s  .  c  om*/
            final JSONObject obj = args.getJSONObject(0);
            _minTime = obj.getLong("minTime");
            _minDistance = obj.getLong("minDistance");
            _noWarn = obj.getBoolean("noWarn");
            _providers = obj.getString("providers");
            _useCache = obj.getBoolean("useCache");
            _returnSatelliteData = obj.getBoolean("satelliteData");
            _buffer = obj.getBoolean("buffer");
            _signalStrength = obj.getBoolean("signalStrength");
            _bufferSize = obj.getInt("bufferSize");

        } catch (Exception exc) {
            Log.d(TAG, ErrorMessages.INCORRECT_CONFIG_ARGS + ", " + exc.getMessage());
            sendCallback(PluginResult.Status.ERROR,
                    ErrorMessages.INCORRECT_CONFIG_ARGS + ", " + exc.getMessage());
        }
    }
}