List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:org.aosutils.android.youtube.YtApiClientV3.java
private static SearchResultIds searchYtIds(String query, String type, int maxResults, String pageToken, String apiKey) throws IOException, JSONException { ArrayList<String> ids = new ArrayList<>(); Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com") .path("/youtube/v3/search").appendQueryParameter("key", apiKey).appendQueryParameter("part", "id") .appendQueryParameter("order", "relevance") .appendQueryParameter("maxResults", Integer.toString(maxResults)).appendQueryParameter("q", query); if (type != null) { uriBuilder.appendQueryParameter("type", type); }//from ww w . j a v a 2 s . c o m if (pageToken != null) { uriBuilder.appendQueryParameter("pageToken", pageToken); } String uri = uriBuilder.build().toString(); String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT); JSONObject jsonObject = new JSONObject(output); String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null; JSONArray items = jsonObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); JSONObject id = item.getJSONObject("id"); ids.add(id.has("videoId") ? id.getString("videoId") : id.getString("playlistId")); } SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken); return searchResult; }
From source file:org.aosutils.android.youtube.YtApiClientV3.java
private static SearchResultIds playlistVideoIds(String playlistId, int maxResults, String pageToken, String apiKey) throws IOException, JSONException { ArrayList<String> ids = new ArrayList<>(); Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com") .path("/youtube/v3/playlistItems").appendQueryParameter("key", apiKey) .appendQueryParameter("part", "id,snippet") .appendQueryParameter("maxResults", Integer.toString(maxResults)) .appendQueryParameter("playlistId", playlistId); if (pageToken != null) { uriBuilder.appendQueryParameter("pageToken", pageToken); }/*w w w . j a va 2s. c o m*/ String uri = uriBuilder.build().toString(); String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT); JSONObject jsonObject = new JSONObject(output); String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null; JSONArray items = jsonObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); JSONObject snippet = item.getJSONObject("snippet"); JSONObject resourceId = snippet.getJSONObject("resourceId"); ids.add(resourceId.getString("videoId")); } SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken); return searchResult; }
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.github.cambierr.lorawanpacket.semtech.Rxpk.java
public Rxpk(JSONObject _json) throws MalformedPacketException { /**/* w ww .ja v a 2 s .co m*/ * tmst */ if (!_json.has("tmst")) { throw new MalformedPacketException("missing tmst"); } else { tmst = _json.getInt("tmst"); } /** * time */ if (!_json.has("time")) { throw new MalformedPacketException("missing time"); } else { time = _json.getString("time"); } /** * chan */ if (!_json.has("chan")) { throw new MalformedPacketException("missing chan"); } else { chan = _json.getInt("chan"); } /** * rfch */ if (!_json.has("rfch")) { throw new MalformedPacketException("missing rfch"); } else { rfch = _json.getInt("rfch"); } /** * freq */ if (!_json.has("freq")) { throw new MalformedPacketException("missing freq"); } else { freq = _json.getDouble("stat"); } /** * stat */ if (!_json.has("stat")) { throw new MalformedPacketException("missing stat"); } else { stat = _json.getInt("stat"); if (stat > 1 || stat < -1) { throw new MalformedPacketException("stat must be equal to -1, 0, or 1"); } } /** * modu */ if (!_json.has("modu")) { throw new MalformedPacketException("missing modu"); } else { modu = Modulation.parse(_json.getString("modu")); } /** * datr */ if (!_json.has("datr")) { throw new MalformedPacketException("missing datr"); } else { switch (modu) { case FSK: datr = _json.getInt("datr"); break; case LORA: datr = _json.getString("datr"); break; } } /** * codr */ if (!_json.has("codr")) { if (modu.equals(Modulation.FSK)) { codr = null; } else { throw new MalformedPacketException("missing codr"); } } else { codr = _json.getString("codr"); } /** * rssi */ if (!_json.has("rssi")) { throw new MalformedPacketException("missing rssi"); } else { rssi = _json.getInt("rssi"); } /** * lsnr */ if (!_json.has("lsnr")) { if (modu.equals(Modulation.FSK)) { lsnr = Double.MAX_VALUE; } else { throw new MalformedPacketException("missing lsnr"); } } else { lsnr = _json.getDouble("lsnr"); } /** * size */ if (!_json.has("size")) { throw new MalformedPacketException("missing size"); } else { size = _json.getInt("size"); } /** * data */ if (!_json.has("data")) { throw new MalformedPacketException("missing data"); } else { byte[] raw; try { raw = Base64.getDecoder().decode(_json.getString("data")); } catch (IllegalArgumentException ex) { throw new MalformedPacketException("malformed data"); } data = new PhyPayload(ByteBuffer.wrap(raw)); } }
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./* w w w . j av a 2 s .c o 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.asd.littleprincesbeauty.data.SqlNote.java
public boolean setContent(JSONObject js) { try {//from w w w.j a va2s.c o m 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:conexionSiabra.ConexionSiabra.java
public boolean check() { boolean result = false; Pair<String, String> elemento = new Pair<String, String>("", ""); if (!db.exiteOauth()) { Log.wtf("Token", "No existe"); result = false;//from w ww .j ava 2 s .c om } else { JSONObject jsonObject = oauth.peticionGet(elemento, url_check); if (jsonObject.has("Exito")) { result = true; } else if (jsonObject.has("detail")) { Log.wtf("Token", "Caducado"); db.eraseOauth(); result = false; } else if (jsonObject.has("Error")) { Log.wtf("Conexion", "Fallo"); result = false; } } return result; }
From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); // Log.i(AnkiDroidApp.TAG, "StudyOptionsFragment: onActivityResult"); if (resultCode == DeckPicker.RESULT_DB_ERROR) { closeStudyOptions(DeckPicker.RESULT_DB_ERROR); }/*w w w . j av a 2 s .c o m*/ if (resultCode == AnkiDroidApp.RESULT_TO_HOME) { closeStudyOptions(); return; } // TODO: proper integration of big widget if (resultCode == DeckPicker.RESULT_MEDIA_EJECTED) { closeStudyOptions(DeckPicker.RESULT_MEDIA_EJECTED); } else { if (!AnkiDroidApp.colIsOpen()) { reloadCollection(); mDontSaveOnStop = false; return; } if (requestCode == DECK_OPTIONS) { if (mCramInitialConfig != null) { mCramInitialConfig = null; try { JSONObject deck = AnkiDroidApp.getCol().getDecks().current(); if (deck.getInt("dyn") != 0 && deck.has("empty")) { deck.remove("empty"); } } catch (JSONException e) { throw new RuntimeException(e); } rebuildCramDeck(); } else { resetAndUpdateValuesFromDeck(); } } else if (requestCode == ADD_NOTE && resultCode != Activity.RESULT_CANCELED) { resetAndUpdateValuesFromDeck(); } else if (requestCode == REQUEST_REVIEW) { // Log.i(AnkiDroidApp.TAG, "Result code = " + resultCode); // TODO: Return to standard scheduler // TODO: handle big widget switch (resultCode) { default: // do not reload counts, if activity is created anew because it has been before destroyed by android resetAndUpdateValuesFromDeck(); break; case Reviewer.RESULT_NO_MORE_CARDS: prepareCongratsView(); setFragmentContentView(mCongratsView); break; } mDontSaveOnStop = false; } else if (requestCode == BROWSE_CARDS && (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED)) { mDontSaveOnStop = false; resetAndUpdateValuesFromDeck(); } else if (requestCode == STATISTICS && mCurrentContentView == CONTENT_CONGRATS) { resetAndUpdateValuesFromDeck(); mCurrentContentView = CONTENT_STUDY_OPTIONS; setFragmentContentView(mStudyOptionsView); } } }
From source file:org.runnerup.export.format.RunKeeper.java
public static ActivityEntity parseToActivity(JSONObject response, double unitMeters) throws JSONException { ActivityEntity newActivity = new ActivityEntity(); newActivity.setSport(RunKeeperSynchronizer.runkeeper2sportMap.get(response.getString("type")).getDbValue()); if (response.has("notes")) { newActivity.setComment(response.getString("notes")); }//from w w w . j a v a2s . co m newActivity.setTime((long) Float.parseFloat(response.getString("duration"))); newActivity.setDistance(Float.parseFloat(response.getString("total_distance"))); String startTime = response.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { newActivity.setStartTime(format.parse(startTime)); } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; } List<LapEntity> laps = new ArrayList<LapEntity>(); List<LocationEntity> locations = new ArrayList<LocationEntity>(); JSONArray distance = response.getJSONArray("distance"); JSONArray path = response.getJSONArray("path"); JSONArray hr = response.getJSONArray("heart_rate"); SortedMap<Long, HashMap<String, String>> pointsValueMap = createPointsMap(distance, path, hr); Iterator<Map.Entry<Long, HashMap<String, String>>> points = pointsValueMap.entrySet().iterator(); //lap hr int maxHr = 0; int sumHr = 0; int count = 0; //point speed long time = 0; float meters = 0.0f; //activity hr int maxHrOverall = 0; int sumHrOverall = 0; int countOverall = 0; while (points.hasNext()) { Map.Entry<Long, HashMap<String, String>> timePoint = points.next(); HashMap<String, String> values = timePoint.getValue(); LocationEntity lv = new LocationEntity(); lv.setActivityId(newActivity.getId()); lv.setTime(TimeUnit.SECONDS.toMillis(newActivity.getStartTime()) + timePoint.getKey()); String dist = values.get("distance"); if (dist == null) { continue; } String lat = values.get("latitude"); String lon = values.get("longitude"); String alt = values.get("altitude"); String heart = values.get("heart_rate"); String type = values.get("type"); if (lat == null || lon == null) { continue; } else { lv.setLatitude(Double.valueOf(lat)); lv.setLongitude(Double.valueOf(lon)); } if (alt != null) { lv.setAltitude(Double.valueOf(alt)); } if (pointsValueMap.firstKey().equals(timePoint.getKey())) { lv.setType(DB.LOCATION.TYPE_START); } else if (!points.hasNext()) { lv.setType(DB.LOCATION.TYPE_END); } else if (type != null) { lv.setType(RunKeeperSynchronizer.POINT_TYPE.get(type)); } // lap and activity max and avg hr if (heart != null) { lv.setHr(Integer.valueOf(heart)); maxHr = Math.max(maxHr, lv.getHr()); maxHrOverall = Math.max(maxHrOverall, lv.getHr()); sumHr += lv.getHr(); sumHrOverall += lv.getHr(); count++; countOverall++; } meters = Float.valueOf(dist) - meters; time = timePoint.getKey() - time; if (time > 0) { float speed = meters / (float) TimeUnit.MILLISECONDS.toSeconds(time); BigDecimal s = new BigDecimal(speed); s = s.setScale(2, BigDecimal.ROUND_UP); lv.setSpeed(s.floatValue()); } // create lap if distance greater than configured lap distance if (Float.valueOf(dist) >= unitMeters * laps.size()) { LapEntity newLap = new LapEntity(); newLap.setLap(laps.size()); newLap.setDistance(Float.valueOf(dist)); newLap.setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey())); newLap.setActivityId(newActivity.getId()); laps.add(newLap); // update previous lap with duration and distance if (laps.size() > 1) { LapEntity previousLap = laps.get(laps.size() - 2); previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance()); previousLap.setTime( (int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime()); if (hr != null && hr.length() > 0) { previousLap.setMaxHr(maxHr); previousLap.setAvgHr(sumHr / count); } maxHr = 0; sumHr = 0; count = 0; } } // update last lap with duration and distance if (!points.hasNext()) { LapEntity previousLap = laps.get(laps.size() - 1); previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance()); previousLap .setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime()); if (hr != null && hr.length() > 0) { previousLap.setMaxHr(maxHr); previousLap.setAvgHr(sumHr / count); } } lv.setLap(laps.size() - 1); locations.add(lv); } // calculate avg and max hr // update the activity newActivity.setMaxHr(maxHrOverall); if (countOverall > 0) { newActivity.setAvgHr(sumHrOverall / countOverall); } newActivity.putPoints(locations); newActivity.putLaps(laps); return newActivity; }