Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

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

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

From source file:cgeo.geocaching.connector.gc.GCParser.java

private static List<LogEntry> parseLogs(final boolean friends, String rawResponse) {
    final List<LogEntry> logs = new ArrayList<LogEntry>();

    // for non logged in users the log book is not shown
    if (StringUtils.isBlank(rawResponse)) {
        return logs;
    }/* w w w.  ja v  a 2  s . c om*/

    try {
        final JSONObject resp = new JSONObject(rawResponse);
        if (!resp.getString("status").equals("success")) {
            Log.e("GCParser.loadLogsFromDetails: status is " + resp.getString("status"));
            return null;
        }

        final JSONArray data = resp.getJSONArray("data");

        for (int index = 0; index < data.length(); index++) {
            final JSONObject entry = data.getJSONObject(index);

            // FIXME: use the "LogType" field instead of the "LogTypeImage" one.
            final String logIconNameExt = entry.optString("LogTypeImage", ".gif");
            final String logIconName = logIconNameExt.substring(0, logIconNameExt.length() - 4);

            long date = 0;
            try {
                date = GCLogin.parseGcCustomDate(entry.getString("Visited")).getTime();
            } catch (final ParseException e) {
                Log.e("GCParser.loadLogsFromDetails: failed to parse log date.");
            }

            // TODO: we should update our log data structure to be able to record
            // proper coordinates, and make them clickable. In the meantime, it is
            // better to integrate those coordinates into the text rather than not
            // display them at all.
            final String latLon = entry.getString("LatLonString");
            final String logText = (StringUtils.isEmpty(latLon) ? "" : (latLon + "<br/><br/>"))
                    + TextUtils.removeControlCharacters(entry.getString("LogText"));
            final LogEntry logDone = new LogEntry(
                    TextUtils.removeControlCharacters(entry.getString("UserName")), date,
                    LogType.getByIconName(logIconName), logText);
            logDone.found = entry.getInt("GeocacheFindCount");
            logDone.friend = friends;

            final JSONArray images = entry.getJSONArray("Images");
            for (int i = 0; i < images.length(); i++) {
                final JSONObject image = images.getJSONObject(i);
                final String url = "http://imgcdn.geocaching.com/cache/log/large/"
                        + image.getString("FileName");
                final String title = TextUtils.removeControlCharacters(image.getString("Name"));
                final Image logImage = new Image(url, title);
                logDone.addLogImage(logImage);
            }

            logs.add(logDone);
        }
    } catch (final JSONException e) {
        // failed to parse logs
        Log.w("GCParser.loadLogsFromDetails: Failed to parse cache logs", e);
    }

    return logs;
}

From source file:org.openhab.io.myopenhab.internal.MyOpenHABClient.java

private void handleRequestEvent(JSONObject data) {
    try {//from   w  w  w  .jav a2  s  .com
        // Get myOH unique request Id
        int requestId = data.getInt("id");
        logger.debug("Got request {}", requestId);
        // Get request path
        String requestPath = data.getString("path");
        // Get request method
        String requestMethod = data.getString("method");
        // Get request body
        String requestBody = data.getString("body");
        // Get JSONObject for request headers
        JSONObject requestHeadersJson = data.getJSONObject("headers");
        logger.debug(requestHeadersJson.toString());
        // Get JSONObject for request query parameters
        JSONObject requestQueryJson = data.getJSONObject("query");
        // Create URI builder with base request URI of openHAB and path from request
        String newPath = URIUtil.addPaths(localBaseUrl, requestPath);
        @SuppressWarnings("unchecked")
        Iterator<String> queryIterator = requestQueryJson.keys();
        // Add query parameters to URI builder, if any
        newPath += "?";
        while (queryIterator.hasNext()) {
            String queryName = queryIterator.next();
            newPath += queryName;
            newPath += "=";
            newPath += URLEncoder.encode(requestQueryJson.getString(queryName), "UTF-8");
            if (queryIterator.hasNext())
                newPath += "&";
        }
        // Finally get the future request URI
        URI requestUri = new URI(newPath);
        // All preparations which are common for different methods are done
        // Now perform the request to openHAB
        // If method is GET
        logger.debug("Request method is " + requestMethod);
        Request request = jettyClient.newRequest(requestUri);
        setRequestHeaders(request, requestHeadersJson);
        request.header("X-Forwarded-Proto", "https");
        if (requestMethod.equals("GET")) {
            request.method(HttpMethod.GET);
        } else if (requestMethod.equals("POST")) {
            request.method(HttpMethod.POST);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else if (requestMethod.equals("PUT")) {
            request.method(HttpMethod.PUT);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else {
            // TODO: Reject unsupported methods
            logger.error("Unsupported request method " + requestMethod);
            return;
        }
        ResponseListener listener = new ResponseListener(requestId);
        request.onResponseHeaders(listener).onResponseContent(listener).onRequestFailure(listener)
                .send(listener);
        // If successfully submitted request to http client, add it to the list of currently
        // running requests to be able to cancel it if needed
        runningRequests.put(requestId, request);
    } catch (JSONException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
    }
}

From source file:org.openhab.io.myopenhab.internal.MyOpenHABClient.java

private void handleCancelEvent(JSONObject data) {
    try {/*from  w w  w. j ava 2  s.c  om*/
        int requestId = data.getInt("id");
        logger.debug("Received cancel for request {}", requestId);
        // Find and abort running request
        if (runningRequests.containsKey(requestId)) {
            Request request = runningRequests.get(requestId);
            request.abort(new InterruptedException());
            runningRequests.remove(requestId);
        }
    } catch (JSONException e) {
        logger.error(e.getMessage());
    }
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLBaseTest.java

/**
 * Extracts the value of key: "id" from a response
 * @param response/* w  w w  .jav a2  s  . co m*/
 * @return
 * @throws IOException
 * @throws JSONException
 */
private static int getId(CloseableHttpResponse response) throws IOException, JSONException {
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));
    JSONObject responseJson = new JSONObject(bufferedReader.readLine());
    bufferedReader.close();
    response.close();

    // Gets the ID of the dataset.
    int id = responseJson.getInt("id");
    return id;
}

From source file:com.dvd.ui.UpdateBooking.java

private void getData() {
    try {// www .j  a  va2s. c om
        if (isServiceOn) {
            String result = "";
            String url1 = "http://localhost:8080/getBooking";

            // String q = URLEncoder.encode(original, "UTF-8");
            URL url = new URL(url1);

            URL obj = url;
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            con.setRequestMethod("GET");

            // add request header
            con.setRequestProperty("User-Agent", "Mozilla/5.0");

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // print result
            result = response.toString();
            // Parse to get translated text

            JSONObject jsonObject = new JSONObject(result);
            JSONArray bookingJsonList = jsonObject.getJSONArray("body");
            List<Booking> list = new ArrayList<>();

            if (bookingJsonList != null) {

                for (int i = 0; i < bookingJsonList.length(); i++) {
                    JSONObject c = bookingJsonList.getJSONObject(i);

                    int id = c.getInt("id");
                    int copyNum = c.getInt("copyNumber");
                    int userId = c.getInt("userID");
                    String da = c.getString("bookingAddedDate");

                    Booking d = new Booking();
                    d.setBookingAddedDate(da);
                    d.setUserID(userId);
                    d.setCopyNumber(copyNum);
                    d.setId(id);
                    System.out.println(d);
                    list.add(d);
                }
                bookingList = list;
            }

        } else {

            BookingRepository repository = new BookingRepository();

            List<BookingDao> s = repository.getBookingList();
            if (s != null) {
                bookingList = new ArrayList<Booking>();
                for (BookingDao bookingDao : s) {
                    DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
                    // Using DateFormat format method we can create a string
                    // representation of a date with the defined format.
                    String dateAdded = df.format(bookingDao.getBookingAddedDate());

                    bookingList.add(new Booking(bookingDao.getId(), bookingDao.getCopyNumber(),
                            bookingDao.getUserID(), dateAdded));
                }

            }

        }

    } catch (Exception e) {

        System.out.println(e);

    }
}

From source file:com.example.quadros_10084564.sunshine_v2.FetchWeatherTask.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  .  j ava 2 s.  c o  m
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

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

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

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

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

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

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

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

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // 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);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted");

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

From source file:at.tugraz.iaik.magnum.conf.MethodHookConfig.java

public static MethodHookConfig fromJsonString(String json) throws Exception {
    JSONObject jsO = new JSONObject(json);
    byte type = (byte) jsO.getInt(TYPE);
    int numInvocations = jsO.getInt(NUM_INVOCATIONS);
    String methodName = jsO.getString(NAME_METHOD);
    return numInvocations > 0 ? new MethodHookConfig(methodName, numInvocations)
            : new MethodHookConfig(methodName, type);
}

From source file:com.github.koraktor.steamcondenser.community.SteamGame.java

/**
 * Returns the overall number of players currently playing this game
 *
 * @return The number of players playing this game
 * @throws JSONException In case of misformatted JSON data
 * @throws WebApiException on Web API errors
 *//*from   w  ww  . j a v  a2  s.  c  om*/
public int getPlayerCount() throws JSONException, WebApiException {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("appid", this.appId);
    String jsonString = WebApi.getJSON("ISteamUserStats", "GetNumberOfCurrentPlayers", 1, params);
    JSONObject result = new JSONObject(jsonString).getJSONObject("response");

    return result.getInt("player_count");
}

From source file:com.soomla.store.domain.data.StaticPriceModel.java

/**
 * Creates a {@link StaticPriceModel} with the given JSONObject.
 * @param jsonObject is a JSONObject representation of the required {@link StaticPriceModel}.
 * @return an instance of {@link StaticPriceModel}.
 * @throws JSONException/*w w w  .  ja  v  a  2 s. c  om*/
 */
public static StaticPriceModel fromJSONObject(JSONObject jsonObject) throws JSONException {
    JSONObject valuesJSONObject = jsonObject.getJSONObject(JSONConsts.GOOD_PRICE_MODEL_VALUES);
    Iterator<?> keys = valuesJSONObject.keys();
    HashMap<String, Integer> values = new HashMap<String, Integer>();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        values.put(key, valuesJSONObject.getInt(key));
    }

    return new StaticPriceModel(values);
}

From source file:org.uiautomation.ios.server.command.web.ScrollHandler.java

public ScrollHandler(IOSServerManager driver, WebDriverLikeRequest request) throws Exception {
    super(driver, request);

    JSONObject payload = request.getPayload();
    String elementId = payload.optString("element");

    Dimension screenSize = driver.getSession(request.getSession()).getNativeDriver().getScreenSize();

    Point fromPoint;//  ww  w  .  ja  v  a  2s . c  o  m
    if (!payload.isNull("element") && !elementId.equals("")) {
        RemoteWebNativeBackedElement element = (RemoteWebNativeBackedElement) getSession().getRemoteWebDriver()
                .createElement(elementId);
        fromPoint = element.getLocation();
    } else {
        fromPoint = new Point(screenSize.getWidth() / 2, screenSize.getHeight() / 2);
    }
    fromPoint = CoordinateUtils.forcePointOnScreen(fromPoint, screenSize);
    Point toPoint = new Point(fromPoint.getX() + payload.getInt("xoffset"),
            fromPoint.getY() + payload.getInt("yoffset"));
    toPoint = CoordinateUtils.forcePointOnScreen(toPoint, screenSize);
    String js = scrollTemplate.replace(":sessionId", request.getSession())
            .replace("fromX", Integer.toString(fromPoint.getX()))
            .replace("fromY", Integer.toString(fromPoint.getY()))
            .replace("toX", Integer.toString(toPoint.getX())).replace("toY", Integer.toString(toPoint.getY()));

    setJS(js);
}