Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

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

@Test
public void testGetJSONData() throws Exception {
    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("test", "param");

    String data = mock(String.class);
    spy(WebApi.class);
    doReturn(data).when(WebApi.class, "getJSON", "interface", "method", 2, params);
    JSONObject json = mock(JSONObject.class);
    JSONObject result = mock(JSONObject.class);
    when(json.getJSONObject("result")).thenReturn(result);
    when(result.getInt("status")).thenReturn(1);
    whenNew(JSONObject.class).withParameterTypes(String.class).withArguments(data).thenReturn(json);

    assertThat(WebApi.getJSONData("interface", "method", 2, params), is(result));
}

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

@Test
public void testGetJSONDataFailed() throws Exception {
    String data = mock(String.class);
    spy(WebApi.class);
    doReturn(data).when(WebApi.class, "getJSON", "interface", "method", 2, null);
    JSONObject json = mock(JSONObject.class);
    JSONObject result = mock(JSONObject.class);
    when(json.getJSONObject("result")).thenReturn(result);
    when(result.getInt("status")).thenReturn(0);
    when(result.getString("statusDetail")).thenReturn("Error");
    whenNew(JSONObject.class).withParameterTypes(String.class).withArguments(data).thenReturn(json);

    this.exception.expect(WebApiException.class);
    this.exception
            .expectMessage("The Web API request failed with the following error: Error (status code: 0).");

    WebApi.getJSONData("interface", "method", 2);
}

From source file:org.loklak.server.Accounting.java

/**
 * cleanup deletes all old entries and frees up the memory.
 * some outside process muss call this frequently
 * @return self//from  w ww  . j av a 2 s . c  om
 */
public Accounting cleanup() {
    if (!this.has("requests"))
        return this;
    JSONObject requests = this.getJSONObject("requests");
    for (String path : requests.keySet()) {
        JSONObject events = requests.getJSONObject(path);
        // shrink that map and delete everything which is older than now minus one hour
        long pivotTime = System.currentTimeMillis() - ONE_HOUR_MILLIS;
        while (events.length() > 0 && Long.parseLong(events.keys().next()) < pivotTime)
            events.remove(events.keys().next());
        if (events.length() == 0)
            requests.remove(path);
    }
    return this;
}

From source file:org.loklak.server.Accounting.java

public synchronized Accounting addRequest(String path, String query) {
    if (!this.has("requests"))
        this.put("requests", new JSONObject());
    JSONObject requests = this.getJSONObject("requests");
    if (!requests.has(path))
        requests.put(path, new TreeMap<String, String>());
    JSONObject events = requests.getJSONObject(path);
    events.put(Long.toString(System.currentTimeMillis() + ((uc++) % 1000)), query); // the counter is used to distinguish very fast concurrent requests
    return this;
}

From source file:org.loklak.server.Accounting.java

public synchronized JSONObject getRequests(String path) {
    if (!this.has("requests"))
        return EMPTY_MAP;
    JSONObject requests = this.getJSONObject("requests");
    if (!requests.has(path))
        return EMPTY_MAP;
    JSONObject events = requests.getJSONObject(path);
    return events;
}

From source file:com.facebook.android.FBUtil.java

/**
 * Parse a server response into a JSON Object. This is a basic
 * implementation using org.json.JSONObject representation. More
 * sophisticated applications may wish to do their own parsing.
 *
 * The parsed JSON is checked for a variety of error fields and
 * a FacebookException is thrown if an error condition is set,
 * populated with the error message and error type or code if
 * available.//from   w w w. j a  va 2 s  .co  m
 *
 * @param response - string representation of the response
 * @return the response as a JSON Object
 * @throws JSONException - if the response is not valid JSON
 * @throws FacebookError - if an error condition is set
 */

public static JSONObject parseJson(String response) throws JSONException, FacebookError {
    // Edge case: when sending a POST request to /[post_id]/likes
    // the return value is 'true' or 'false'. Unfortunately
    // these values cause the JSONObject constructor to throw
    // an exception.
    if (response.equals("false")) {
        throw new FacebookError("request failed");
    }
    if (response.equals("true")) {
        response = "{value : true}";
    }
    JSONObject json = new JSONObject(response);

    // errors set by the server are not consistent
    // they depend on the method and endpoint
    if (json.has("error")) {
        JSONObject error = json.getJSONObject("error");
        throw new FacebookError(error.getString("message"), error.getString("type"), 0);
    }
    if (json.has("error_code") && json.has("error_msg")) {
        throw new FacebookError(json.getString("error_msg"), "",
                Integer.parseInt(json.getString("error_code")));
    }
    if (json.has("error_code")) {
        throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code")));
    }
    if (json.has("error_msg")) {
        throw new FacebookError(json.getString("error_msg"));
    }
    if (json.has("error_reason")) {
        throw new FacebookError(json.getString("error_reason"));
    }
    return json;
}

From source file:com.clearner.youtube.PlaylistItem.java

public PlaylistItem(JSONObject jsonItem) throws JSONException {
    id = jsonItem.getString("id");
    final JSONObject snippet = jsonItem.getJSONObject("snippet");
    position = snippet.getInt("position");
    title = snippet.getString("title");
    description = snippet.getString("description");
    thumbnailUrl = snippet.getJSONObject("thumbnails").getJSONObject("medium").getString("url");
    videoId = snippet.getJSONObject("resourceId").getString("videoId");
}

From source file:com.asd.littleprincesbeauty.data.SqlNote.java

public boolean setContent(JSONObject js) {
    try {//from  w w w  .  j av  a2 s . c om
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            Log.w(TAG, "cannot set system folder");
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            // for folder we can only update the snnipet and type
            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
            JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
            long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
            if (mIsCreate || mId != id) {
                mDiffNoteValues.put(NoteColumns.ID, id);
            }
            mId = id;

            long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0;
            if (mIsCreate || mAlertDate != alertDate) {
                mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
            }
            mAlertDate = alertDate;

            int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID)
                    : ResourceParser.getDefaultBgId(mContext);
            if (mIsCreate || mBgColorId != bgColorId) {
                mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
            }
            mBgColorId = bgColorId;

            long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mCreatedDate != createDate) {
                mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
            }
            mCreatedDate = createDate;

            int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT)
                    : 0;
            if (mIsCreate || mHasAttachment != hasAttachment) {
                mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
            }
            mHasAttachment = hasAttachment;

            long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mModifiedDate != modifiedDate) {
                mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
            }
            mModifiedDate = modifiedDate;

            long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0;
            if (mIsCreate || mParentId != parentId) {
                mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
            }
            mParentId = parentId;

            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;

            int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
                    : AppWidgetManager.INVALID_APPWIDGET_ID;
            if (mIsCreate || mWidgetId != widgetId) {
                mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
            }
            mWidgetId = widgetId;

            int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE)
                    : Notes.TYPE_WIDGET_INVALIDE;
            if (mIsCreate || mWidgetType != widgetType) {
                mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
            }
            mWidgetType = widgetType;

            long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID)
                    ? note.getLong(NoteColumns.ORIGIN_PARENT_ID)
                    : 0;
            if (mIsCreate || mOriginParent != originParent) {
                mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
            }
            mOriginParent = originParent;

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                SqlData sqlData = null;
                if (data.has(DataColumns.ID)) {
                    long dataId = data.getLong(DataColumns.ID);
                    for (SqlData temp : mDataList) {
                        if (dataId == temp.getId()) {
                            sqlData = temp;
                        }
                    }
                }

                if (sqlData == null) {
                    sqlData = new SqlData(mContext);
                    mDataList.add(sqlData);
                }

                sqlData.setContent(data);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return false;
    }
    return true;
}

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

public void addUsersForSwitchIdAndHostname(int id, final String hostname) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    String statement = Config.FREEBOX_API_SWITCH_ID.replace("{id}", String.valueOf(id));
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting Switch information",
            false);/*from   w w w.j  a  v  a 2 s .  co m*/

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONObject result = obj.getJSONObject("result");
                long txBytes = result.getLong("tx_bytes_rate");
                long rxBytes = result.getLong("rx_bytes_rate");

                addUser("", hostname, txBytes, rxBytes);
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Switch information", msg);
            }

            setVisible(true);
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Switch information", ex.getMessage());
        }
    });
}

From source file:de.schildbach.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*from   ww w  .j  av  a  2 s. c o  m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final Fiat rate = Fiat.parseFiat(currencyCode, rateStr);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new org.bitcoinj.utils.ExchangeRate(rate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}