Example usage for org.json JSONObject getDouble

List of usage examples for org.json JSONObject getDouble

Introduction

In this page you can find the example usage for org.json JSONObject getDouble.

Prototype

public double getDouble(String key) throws JSONException 

Source Link

Document

Get the double value associated with a key.

Usage

From source file:rocks.teammolise.myunimol.webapp.login.HomeServlet.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods./*ww  w.  ja  v  a  2  s . c  om*/
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //il tipo di risultato della servlet
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        JSONObject recordBook = new APIConsumer().consume("getRecordBook", username, password);
        JSONObject result = new JSONObject();
        result.put("average", recordBook.getDouble("average"));
        result.put("weightedAverage", recordBook.getDouble("weightedAverage"));

        JSONArray exams = recordBook.getJSONArray("exams");
        float acquiredCFU = 0;
        int totalExams = 0;
        for (int i = 0; i < exams.length(); i++) {
            if (!exams.getJSONObject(i).getString("vote").contains("/")) {
                acquiredCFU += exams.getJSONObject(i).getInt("cfu");
                totalExams++;
            }
        }
        double percentCfuUgly = (acquiredCFU * 100) / userInfo.getTotalCFU();
        //Arrotonda la percentuale alla prima cifra decimale
        double percentCfu = Math.round(percentCfuUgly * 10D) / 10D;
        result.put("totalCFU", (int) userInfo.getTotalCFU());
        result.put("acquiredCFU", (int) acquiredCFU);
        result.put("percentCFU", percentCfu);
        result.put("totalExams", totalExams);

        out.write(result.toString());
    } catch (UnirestException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    } catch (JSONException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    } finally {
        out.close();
    }

}

From source file:com.bmwcarit.barefoot.roadmap.RoadPoint.java

/**
 * Creates a {@link RoadPoint} object from its JSON representation.
 *
 * @param json JSON representation of the {@link RoadPoint} object.
 * @param map {@link RoadMap} as reference of the {@link RoadPoint}.
 * @return {@link RoadPoint} object./*from   w  w w  . ja  v  a 2  s  .com*/
 * @throws JSONException thrown on JSON extraction or parsing error.
 */
public static RoadPoint fromJSON(JSONObject json, RoadMap map) throws JSONException {
    Road road = Road.fromJSON(json, map);
    double fraction = json.getDouble("frac");
    return new RoadPoint(road, fraction);
}

From source file:com.nextgis.maplib.display.TMSRenderer.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    mAntiAlias = jsonObject.getBoolean(JSON_TMSRENDERER_ANTIALIAS);
    mFilterBitmap = jsonObject.getBoolean(JSON_TMSRENDERER_FILTERBMP);
    mDither = jsonObject.getBoolean(JSON_TMSRENDERER_DITHER);
    mContrast = (float) jsonObject.getDouble(JSON_TMSRENDERER_CONTRAST);
    mBrightness = (float) jsonObject.getDouble(JSON_TMSRENDERER_BRIGHTNESS);
    mForceToGrayScale = jsonObject.getBoolean(JSON_TMSRENDERER_GRAYSCALE);

    mRasterPaint.setAntiAlias(mAntiAlias);
    mRasterPaint.setFilterBitmap(mFilterBitmap);
    mRasterPaint.setDither(mDither);//  w  ww  .ja  v  a2  s  . c  o m

    setContrastBrightness(mContrast, mBrightness, mForceToGrayScale);
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.TestController.java

/**
 * Save the details of the last executed step
 * @param executionId the execution id for the current test
 * @param model/*from   w  w  w .  j a v a2 s  . c o m*/
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@RequestMapping("/test/put/{executionId}")
public void saveStep(@PathVariable("executionId") String execId, HttpServletRequest request,
        HttpServletResponse response, Model model) throws Exception {

    String executionId = _cleanExtensions(execId);

    if (!isValidTest(request, executionId)) {
        sendOutput(response, "{\"error\":\"Invalid test execution id.\"}");
        return;
    }

    try {

        String data = null;
        InputStream is = request.getInputStream();

        if (is != null) {
            try {
                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                data = sb.toString();
            } finally {
                is.close();
            }

        }

        if (data == null) {
            sendOutput(response, "{\"error\":\"No data received.\"}");
            return;
        }

        final JSONObject info = new JSONObject(data);

        final Integer stepId = info.getInt("stepId");
        final String cluster = info.getJSONObject("cluster").toString();
        final String times = info.getJSONObject("times").toString();
        final JSONObject tagExecutionInfo = info.getJSONObject("tagExecutionInfo");

        int itemCount = 0;
        final Iterator keys = tagExecutionInfo.keys();
        while (keys.hasNext()) {
            final String cnt = (String) keys.next();
            final Integer tagCount = Integer.valueOf(cnt);
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId,
                    tagCount);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            final JSONObject itemInfo = tagExecutionInfo.getJSONObject(cnt);

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(tagCount);
            exec.setBaseEffort(itemInfo.getDouble("baseEffort"));
            exec.setBaseRelevantEffort(itemInfo.getDouble("baseRelevantEffort"));
            exec.setUserEffort(itemInfo.getDouble("userEffort"));
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags(itemInfo.getJSONObject("tags").toString());

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
            itemCount++;
        }

        //if no tagged items
        if (itemCount == 0) {
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId, 0);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(0);
            exec.setBaseEffort(0.0D);
            exec.setBaseRelevantEffort(0.0D);
            exec.setUserEffort(0.0D);
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags("{}");

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
        }

        sendOutput(response, "{\"success\":true}");

    } catch (Exception e) {
        sendOutput(response, "{\"error\":" + JSONObject.quote(e.getMessage()) + "}");
        return;
    }

}

From source file:com.astifter.circatext.YahooJSONParser.java

private static float getFloat(String tagName, JSONObject jObj) throws JSONException {
    return (float) jObj.getDouble(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 a  va2 s . c  o  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 ww.j  a  va 2s . co m
        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 {/* w w  w  .j  av a 2s .com*/
        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: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 www.j  av a2 s.c o  m*/
 */
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:tom.udacity.sample.sunrise.WeatherDataParser.java

/**
 * Given a string of the form returned by the api call:
 * http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
 * retrieve the maximum temperature for the day indicated by dayIndex
 * (Note: 0-indexed, so 0 would refer to the first day).
 */// w  ww  .  ja  v  a 2s  .c o m
private static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex) throws JSONException {
    JSONObject data = new JSONObject(weatherJsonStr);
    JSONArray days = data.getJSONArray("list");
    JSONObject dayJson = days.getJSONObject(dayIndex);
    JSONObject temp = dayJson.getJSONObject("temp");
    return temp.getDouble("max");
}