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.astifter.circatext.YahooJSONParser.java

private static long getLong(String tagName, JSONObject jObj) throws JSONException {
    return jObj.getLong(tagName);
}

From source file:com.nonobay.fana.udacityandroidproject1popularmovies.FetchMovieTask.java

/**
 * Take the String representing the complete movies in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>/*from  w  w w .  j av a2s. co  m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getMovieDataFromJson(String moviesJsonStr) throws JSONException {

    // Now we have a String representing the complete movie list in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    /* example
    {
    "page": 1,
    "results": [
        {
            "adult": false,
                "backdrop_path": "/razvUuLkF7CX4XsLyj02ksC0ayy.jpg",
                "genre_ids": [
            80,
                    28,
                    53
            ],
            "id": 260346,
                "original_language": "en",
                "original_title": "Taken 3",
                "overview": "Ex-government operative Bryan Mills finds his life is shattered when he's falsely accused of a murder that hits close to home. As he's pursued by a savvy police inspector, Mills employs his particular set of skills to track the real killer and exact his unique brand of justice.",
                "release_date": "2015-01-09",
                "poster_path": "/c2SSjUVYawDUnQ92bmTqsZsPEiB.jpg",
                "popularity": 11.737899,
                "title": "Taken 3",
                "video": false,
                "vote_average": 6.2,
                "vote_count": 698
        }
    ],
    "total_pages": 11543,
    "total_results": 230847
    }*/

    // These are the names of the JSON objects that need to be extracted.
    final String JSON_PAGE = "page";
    final String JSON_PAGE_TOTAL = "total_pages";
    final String JSON_MOVIE_LIST = "results";
    final String JSON_MOVIE_TOTAL = "total_results";

    final String JSON_MOVIE_ID = "id";
    final String JSON_MOVIE_TITLE = "original_title";
    final String JSON_MOVIE_DATE = "release_date";
    final String JSON_MOVIE_POSTER = "poster_path";
    final String JSON_MOVIE_OVERVIEW = "overview";
    final String JSON_MOVIE_VOTE_AVERAGE = "vote_average";

    try {

        JSONObject moviesJson = new JSONObject(moviesJsonStr);

        JSONArray movieArray = moviesJson.getJSONArray(JSON_MOVIE_LIST);

        // Insert the new movie information into the database
        Vector<ContentValues> cVVector = new Vector<>(movieArray.length());

        // These are the values that will be collected.
        String releaseTime;
        long movieId;
        double vote_average;
        String overview;
        String original_title;
        String poster_path;

        for (int i = 0; i < movieArray.length(); i++) {

            // Get the JSON object representing the movie
            JSONObject eachMovie = movieArray.getJSONObject(i);

            movieId = eachMovie.getLong(JSON_MOVIE_ID);
            original_title = eachMovie.getString(JSON_MOVIE_TITLE);
            overview = eachMovie.getString(JSON_MOVIE_OVERVIEW);
            poster_path = eachMovie.getString(JSON_MOVIE_POSTER);
            vote_average = eachMovie.getDouble(JSON_MOVIE_VOTE_AVERAGE);
            releaseTime = eachMovie.getString(JSON_MOVIE_DATE);

            ContentValues movieValues = new ContentValues();
            movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_ID, movieId);
            movieValues.put(MovieContract.MovieEntry.COLUMN_ORIGINAL_TITLE, original_title);
            movieValues.put(MovieContract.MovieEntry.COLUMN_POSTER_THUMBNAIL, poster_path);
            movieValues.put(MovieContract.MovieEntry.COLUMN_SYNOPSIS, overview);
            movieValues.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, releaseTime);
            movieValues.put(MovieContract.MovieEntry.COLUMN_USER_RATING, vote_average);

            cVVector.add(movieValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            mContext.getContentResolver().delete(MovieContract.MovieEntry.CONTENT_URI, null, null);
            mContext.getContentResolver().bulkInsert(MovieContract.MovieEntry.CONTENT_URI,
                    cVVector.toArray(new ContentValues[cVVector.size()]));
        }

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
}

From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertWeatherData(String data, SQLiteDatabase db) {
    try {/*from   w  w w.j a v  a2 s .c om*/
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject array = jsonArray.getJSONObject(i);
            JSONObject jsonObject = array.getJSONObject("weather");

            long timestamp = jsonObject.getLong("timestamp");
            int year = jsonObject.getInt("year");
            int month = jsonObject.getInt("month");
            int day = jsonObject.getInt("day");
            int max_temp_c = jsonObject.getInt("max_temp_c");
            int max_temp_f = jsonObject.getInt("max_temp_f");
            int min_temp_c = jsonObject.getInt("min_temp_c");
            int min_temp_f = jsonObject.getInt("min_temp_f");
            int wind_speed_miles = jsonObject.getInt("wind_speed_miles");
            int wind_speed_km = jsonObject.getInt("wind_speed_km");
            String wind_direction = jsonObject.getString("wind_direction");
            int wind_degree = jsonObject.getInt("wind_degree");
            String icon_url = jsonObject.getString("icon_url");
            String description = jsonObject.getString("weather_description");
            Double precipitation = jsonObject.getDouble("precipitation");

            String inS = "INSERT INTO weather VALUES(" + timestamp + "," + year + "," + month + "," + day + ","
                    + max_temp_c + "," + max_temp_f + "," + min_temp_c + "," + min_temp_f + ","
                    + wind_speed_miles + "," + wind_speed_km + ",'" + wind_direction + "'," + wind_degree + ",'"
                    + icon_url + "','" + description + "'," + precipitation + ")";
            db.execSQL(inS);
        }
    } catch (Exception e) {
        System.out.println(e);
        return false;
    }
    return true;
}

From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertSurfData(String data, SQLiteDatabase db) {
    /* Delete any current versions with the same request timestamps */
    try {/*from   ww w . ja  va  2 s  .  co  m*/
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject surf = jsonArray.getJSONObject(i);
            db.execSQL("DELETE FROM surf WHERE timestamp = " + surf.getLong("timestamp"));
        }
    } catch (Exception e) {
        System.err.println("Could not delete data");
    }

    /* Now actually do the inserts! */
    try {
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject surf = jsonArray.getJSONObject(i);
            int location = surf.getInt("location");
            long timestamp = surf.getLong("timestamp");
            long localtime = surf.getLong("local_time");
            int year = surf.getInt("year");
            int month = surf.getInt("month");
            int day = surf.getInt("day");
            int hour = surf.getInt("hour");
            int minute = surf.getInt("minute");
            int faded_rating = surf.getInt("faded_rating");
            int solid_rating = surf.getInt("solid_rating");
            double min_surf = surf.getDouble("min_surf_height");
            double abs_min_surf = surf.getDouble("abs_min_surf_height");
            double max_surf = surf.getDouble("max_surf_height");
            double abs_max_surf = surf.getDouble("abs_max_surf_height");
            double swell_height = surf.getDouble("swell_height");
            double swell_period = surf.getDouble("swell_period");
            double swell_angle = surf.getDouble("swell_angle");
            String swell_direction = surf.getString("swell_direction");
            String swell_chart_url = surf.getString("swell_chart");
            String period_chart_url = surf.getString("period_chart");
            String wind_chart_url = surf.getString("wind_chart");
            String pressure_chart_url = surf.getString("pressure_chart");
            String sst_chart_url = surf.getString("sst_chart");

            String inS = "INSERT INTO surf VALUES(" + location + "," + timestamp + "," + localtime + "," + year
                    + "," + month + "," + day + "," + hour + "," + minute + "," + faded_rating + ","
                    + solid_rating + "," + min_surf + "," + abs_min_surf + "," + max_surf + "," + abs_max_surf
                    + "," + swell_height + "," + swell_period + "," + swell_angle + ",'" + swell_direction
                    + "','" + swell_chart_url + "','" + period_chart_url + "','" + wind_chart_url + "','"
                    + pressure_chart_url + "','" + sst_chart_url + "')";
            db.execSQL(inS);
        }
    } catch (Exception e) {
        System.out.println(e);
        return false;
    }
    return true;
}

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

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

    JSONObject userJson = content.getJSONObject("user");
    final long userId = userJson.getLong("id");
    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, userId, () -> {
            handle(responseNumber, allContent);
        });//  w ww. j  a  va 2 s .  c  om
        EventCache.LOG.debug("Got GuildMember update but JDA currently does not have the Guild cached. "
                + content.toString());
        return null;
    }

    MemberImpl member = (MemberImpl) guild.getMembersMap().get(userId);
    if (member == null) {
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> {
            handle(responseNumber, allContent);
        });
        EventCache.LOG.debug(
                "Got GuildMember update but Member is not currently present in Guild. " + content.toString());
        return null;
    }

    Set<Role> currentRoles = member.getRoleSet();
    List<Role> newRoles = toRolesList(guild, content.getJSONArray("roles"));

    //If newRoles is null that means that we didn't find a role that was in the array and was cached this event
    if (newRoles == null)
        return null;

    //Find the roles removed.
    List<Role> removedRoles = new LinkedList<>();
    each: for (Role role : currentRoles) {
        for (Iterator<Role> it = newRoles.iterator(); it.hasNext();) {
            Role r = it.next();
            if (role.equals(r)) {
                it.remove();
                continue each;
            }
        }
        removedRoles.add(role);
    }

    if (removedRoles.size() > 0)
        currentRoles.removeAll(removedRoles);
    if (newRoles.size() > 0)
        currentRoles.addAll(newRoles);

    if (removedRoles.size() > 0) {
        api.getEventManager()
                .handle(new GuildMemberRoleRemoveEvent(api, responseNumber, guild, member, removedRoles));
    }
    if (newRoles.size() > 0) {
        api.getEventManager().handle(new GuildMemberRoleAddEvent(api, responseNumber, guild, member, newRoles));
    }
    if (content.has("nick")) {
        String prevNick = member.getNickname();
        String newNick = content.isNull("nick") ? null : content.getString("nick");
        if (!Objects.equals(prevNick, newNick)) {
            member.setNickname(newNick);
            api.getEventManager().handle(
                    new GuildMemberNickChangeEvent(api, responseNumber, guild, member, prevNick, newNick));
        }
    }
    return null;
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader,
        HttpServletResponse response, IFileStore file)
        throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException {
    JSONObject changes = OrionServlet.readJSONRequest(request);
    //read file to memory
    Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null));
    StringWriter oldFile = new StringWriter();
    IOUtilities.pipe(fileReader, oldFile, true, false);
    StringBuffer oldContents = oldFile.getBuffer();

    JSONArray changeList = changes.getJSONArray("diff");
    for (int i = 0; i < changeList.length(); i++) {
        JSONObject change = changeList.getJSONObject(i);
        long start = change.getLong("start");
        long end = change.getLong("end");
        String text = change.getString("text");
        oldContents.replace((int) start, (int) end, text);
    }/*w  w w.ja v a  2  s. c om*/

    String newContents = oldContents.toString();
    boolean failed = false;
    if (changes.has("contents")) {
        String contents = changes.getString("contents");
        if (!newContents.equals(contents)) {
            failed = true;
            newContents = contents;
        }
    }
    Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8");
    IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true);
    if (failed) {
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0    "
                                + changes.toString(),
                        null));
        return;
    }

    // return metadata with the new Etag
    handleGetMetadata(request, response, response.getWriter(), file);
}

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

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

    GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug("GUILD_ROLE_DELETE was received for a Guild that is not yet cached: " + content);
        return null;
    }/* w  ww  .  j  ava 2  s.  com*/

    final long roleId = content.getLong("role_id");
    Role removedRole = guild.getRolesMap().remove(roleId);
    if (removedRole == null) {
        api.getEventCache().cache(EventCache.Type.ROLE, roleId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug("GUILD_ROLE_DELETE was received for a Role that is not yet cached: " + content);
        return null;
    }

    //Now that the role is removed from the Guild, remove it from all users.
    for (Member m : guild.getMembersMap().valueCollection()) {
        MemberImpl member = (MemberImpl) m;
        member.getRoleSet().remove(removedRole);
    }
    api.getEventManager().handle(new RoleDeleteEvent(api, responseNumber, removedRole));
    return null;
}

From source file:drusy.ui.panels.WifiStatePanel.java

public void addUsersForWifiId(int id, final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    String statement = Config.FREEBOX_API_WIFI_STATIONS.replace("{id}", String.valueOf(id));
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting WiFi id", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override/*w ww  . j a  va2  s .c o m*/
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            clearUsers();
            if (success == true) {
                final JSONArray usersList = obj.getJSONArray("result");

                for (int i = 0; i < usersList.length(); ++i) {
                    JSONObject user = usersList.getJSONObject(i);
                    final String hostname = user.getString("hostname");
                    final long txBytes = user.getLong("tx_rate");
                    final long rxBytes = user.getLong("rx_rate");
                    JSONObject host = user.getJSONObject("host");
                    final String host_type = host.getString("host_type");

                    addUser(host_type, hostname, txBytes, rxBytes);
                }
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Wi-Fi State (get users)", msg);
            }

            if (updater != null) {
                updater.updated();
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Wi-Fi State (get users)", ex.getMessage());

            if (updater != null) {
                updater.updated();
            }
        }
    });
}

From source file:tom.udacity.sample.sunrise.WeatherDataParser.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from  ww w. ja  v a2  s  . c  om*/
 */
public String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationQuery)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.
    final String OWM_LIST = "list";
    final String OWM_WEATHER = "weather";
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";
    final String OWM_DATETIME = "dt";
    final String OWM_DESCRIPTION = "main";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    String[] resultStrs = new String[numDays];
    for (int i = 0; i < weatherArray.length(); i++) {
        // For now, using the format "Day, description, hi/low"
        String day;
        String description;
        String highAndLow;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        long dateTime = dayForecast.getLong(OWM_DATETIME);
        day = getReadableDateString(dateTime);

        // description is in a child array called "weather", which is 1 element long.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        double high = temperatureObject.getDouble(OWM_MAX);
        double low = temperatureObject.getDouble(OWM_MIN);

        highAndLow = formatHighLows(high, low);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    return resultStrs;
}

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

public static Eltako_FRW_ws_SmokeAlarmDataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new Eltako_FRW_ws_SmokeAlarmDataImpl(SmokeAlarmStatus.UNKNOWN, null);

    try {/*from   ww  w .j a va2  s. c  o  m*/
        SmokeAlarmStatus status = SmokeAlarmStatus.valueOf(lastKnownData.getString("smokeAlarmStatus"));
        Date date = new Date(lastKnownData.getLong("date"));

        return new Eltako_FRW_ws_SmokeAlarmDataImpl(status, 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 Eltako_FRW_ws_SmokeAlarmDataImpl(SmokeAlarmStatus.UNKNOWN, null);
    }
}