List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:com.markupartist.sthlmtraveling.provider.planner.Planner.java
public Trip2 addIntermediateStops(final Context context, Trip2 trip, JourneyQuery query) throws IOException { Uri u = Uri.parse(apiEndpoint2());//ww w . ja va2s.co m Uri.Builder b = u.buildUpon(); b.appendEncodedPath("journey/v1/intermediate/"); b.appendQueryParameter("ident", query.ident); b.appendQueryParameter("seqnr", query.seqnr); int references = 0; String reference = null; for (SubTrip st : trip.subTrips) { if ((!TextUtils.isEmpty(st.reference)) && st.intermediateStop.isEmpty()) { b.appendQueryParameter("reference", st.reference); references++; reference = st.reference; } } u = b.build(); if (references == 0) { return trip; } HttpHelper httpHelper = HttpHelper.getInstance(context); HttpURLConnection connection = httpHelper.getConnection(u.toString()); String rawContent; int statusCode = connection.getResponseCode(); switch (statusCode) { case 200: rawContent = httpHelper.getBody(connection); try { JSONObject baseResponse = new JSONObject(rawContent); if (baseResponse.has("stops")) { if (baseResponse.isNull("stops")) { Log.d(TAG, "stops was null, ignoring."); } else if (references == 1) { JSONArray intermediateStopsJson = baseResponse.getJSONArray("stops"); for (SubTrip st : trip.subTrips) { if (reference.equals(st.reference)) { for (int i = 0; i < intermediateStopsJson.length(); i++) { st.intermediateStop .add(IntermediateStop.fromJson(intermediateStopsJson.getJSONObject(i))); } } } } else { JSONObject intermediateStopsJson = baseResponse.getJSONObject("stops"); for (SubTrip st : trip.subTrips) { if (intermediateStopsJson.has(st.reference)) { JSONArray jsonArray = intermediateStopsJson.getJSONArray(st.reference); for (int i = 0; i < jsonArray.length(); i++) { st.intermediateStop.add(IntermediateStop.fromJson(jsonArray.getJSONObject(i))); } } } } } else { Log.w(TAG, "Invalid response when fetching intermediate stops."); } } catch (JSONException e) { Log.w(TAG, "Could not parse the reponse for intermediate stops."); } break; case 400: // Bad request rawContent = httpHelper.getErrorBody(connection); try { BadResponse br = BadResponse.fromJson(new JSONObject(rawContent)); Log.e(TAG, "Invalid response for intermediate stops: " + br.toString()); } catch (JSONException e) { Log.e(TAG, "Could not parse the reponse for intermediate stops."); } default: Log.e(TAG, "Status code not OK from intermediate stops API, was " + statusCode); } return trip; }
From source file:com.markupartist.sthlmtraveling.provider.planner.Planner.java
public SubTrip addIntermediateStops(Context context, SubTrip subTrip, JourneyQuery query) throws IOException { Uri u = Uri.parse(apiEndpoint2());//from w w w.ja v a 2 s. co m Uri.Builder b = u.buildUpon(); b.appendEncodedPath("journey/v1/intermediate/"); b.appendQueryParameter("ident", query.ident); b.appendQueryParameter("seqnr", query.seqnr); b.appendQueryParameter("reference", subTrip.reference); u = b.build(); HttpHelper httpHelper = HttpHelper.getInstance(context); HttpURLConnection connection = httpHelper.getConnection(u.toString()); String rawContent; int statusCode = connection.getResponseCode(); switch (statusCode) { case 200: rawContent = httpHelper.getBody(connection); try { JSONObject baseResponse = new JSONObject(rawContent); if (baseResponse.has("stops")) { JSONArray intermediateStopJsonArray = baseResponse.getJSONArray("stops"); for (int i = 0; i < intermediateStopJsonArray.length(); i++) { subTrip.intermediateStop .add(IntermediateStop.fromJson(intermediateStopJsonArray.getJSONObject(i))); } } else { Log.w(TAG, "Invalid response when fetching intermediate stops."); } } catch (JSONException e) { Log.w(TAG, "Could not parse the reponse for intermediate stops."); } break; case 400: rawContent = httpHelper.getErrorBody(connection); try { BadResponse br = BadResponse.fromJson(new JSONObject(rawContent)); Log.e(TAG, "Invalid response for intermediate stops: " + br.toString()); } catch (JSONException e) { Log.e(TAG, "Could not parse the reponse for intermediate stops."); } default: Log.e(TAG, "Status code not OK from intermediate stops API, was " + statusCode); } return subTrip; }
From source file:com.markupartist.sthlmtraveling.provider.planner.Planner.java
private Response doJourneyQuery(final Context context, JourneyQuery query, int scrollDirection) throws IOException, BadResponse { Uri u = Uri.parse(apiEndpoint2());//from ww w .j av a 2 s. c om Uri.Builder b = u.buildUpon(); b.appendEncodedPath("v1/journey/"); if (scrollDirection > -1) { b.appendQueryParameter("dir", String.valueOf(scrollDirection)); b.appendQueryParameter("ident", query.ident); b.appendQueryParameter("seq", query.seqnr); } else { if (query.origin.hasLocation()) { b.appendQueryParameter("origin", query.origin.name); b.appendQueryParameter("origin_latitude", String.valueOf(query.origin.latitude / 1E6)); b.appendQueryParameter("origin_longitude", String.valueOf(query.origin.longitude / 1E6)); } else { b.appendQueryParameter("origin", String.valueOf(query.origin.getNameOrId())); } if (query.destination.hasLocation()) { b.appendQueryParameter("destination", query.destination.name); b.appendQueryParameter("destination_latitude", String.valueOf(query.destination.latitude / 1E6)); b.appendQueryParameter("destination_longitude", String.valueOf(query.destination.longitude / 1E6)); } else { b.appendQueryParameter("destination", String.valueOf(query.destination.getNameOrId())); } for (String transportMode : query.transportModes) { b.appendQueryParameter("transport", transportMode); } if (query.time != null) { b.appendQueryParameter("date", query.time.format("%d.%m.%Y")); b.appendQueryParameter("time", query.time.format("%H:%M")); } if (!query.isTimeDeparture) { b.appendQueryParameter("arrival", "1"); } if (query.hasVia()) { b.appendQueryParameter("via", query.via.name); } if (query.alternativeStops) { b.appendQueryParameter("alternative", "1"); } } // Include intermediate stops. //b.appendQueryParameter("intermediate_stops", "1"); u = b.build(); HttpHelper httpHelper = HttpHelper.getInstance(context); HttpURLConnection connection = httpHelper.getConnection(u.toString()); Response r = null; String rawContent; int statusCode = connection.getResponseCode(); switch (statusCode) { case 200: rawContent = httpHelper.getBody(connection); try { JSONObject baseResponse = new JSONObject(rawContent); if (baseResponse.has("journey")) { r = Response.fromJson(baseResponse.getJSONObject("journey")); } else { Log.w(TAG, "Invalid response"); } } catch (JSONException e) { Log.d(TAG, "Could not parse the reponse..."); throw new IOException("Could not parse the response."); } break; case 400: rawContent = httpHelper.getErrorBody(connection); BadResponse br; try { br = BadResponse.fromJson(new JSONObject(rawContent)); } catch (JSONException e) { Log.d(TAG, "Could not parse the reponse..."); throw new IOException("Could not parse the response."); } throw br; default: Log.d(TAG, "Status code not OK from API, was " + statusCode); throw new IOException("A remote server error occurred when getting deviations."); } return r; }
From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java
public Object[] sync(Connection con) { mSyncMsg = ""; // if the deck has any pending changes, flush them first and bump mod time mCol.save();// w w w . j a v a 2 s .co m // step 1: login & metadata HttpResponse ret = mServer.meta(); if (ret == null) { return null; } int returntype = ret.getStatusLine().getStatusCode(); if (returntype == 403) { return new Object[] { "badAuth" }; } else if (returntype != 200) { return new Object[] { "error", returntype, ret.getStatusLine().getReasonPhrase() }; } try { mCol.getDb().getDatabase().beginTransaction(); try { // Log.i(AnkiDroidApp.TAG, "Sync: getting meta data from server"); JSONObject rMeta = new JSONObject(mServer.stream2String(ret.getEntity().getContent())); long rscm = rMeta.getLong("scm"); int rts = rMeta.getInt("ts"); mRMod = rMeta.getLong("mod"); mMaxUsn = rMeta.getInt("usn"); mMediaUsn = rMeta.getInt("musn"); mSyncMsg = rMeta.getString("msg"); // skip uname, AnkiDroid already stores and shows it if (!rMeta.getBoolean("cont")) { // Don't add syncMsg; it can be fetched by UI code using the accessor return new Object[] { "serverAbort" }; } else { // don't abort, but ui should show messages after sync finishes // and require confirmation if it's non-empty } // Log.i(AnkiDroidApp.TAG, "Sync: building local meta data"); JSONObject lMeta = meta(); mLMod = lMeta.getLong("mod"); mMinUsn = lMeta.getInt("usn"); long lscm = lMeta.getLong("scm"); int lts = lMeta.getInt("ts"); long diff = Math.abs(rts - lts); if (diff > 300) { return new Object[] { "clockOff", diff }; } if (mLMod == mRMod) { // Log.i(AnkiDroidApp.TAG, "Sync: no changes - returning"); return new Object[] { "noChanges" }; } else if (lscm != rscm) { // Log.i(AnkiDroidApp.TAG, "Sync: full sync necessary - returning"); return new Object[] { "fullSync" }; } mLNewer = mLMod > mRMod; // step 2: deletions publishProgress(con, R.string.sync_deletions_message); // Log.i(AnkiDroidApp.TAG, "Sync: collection removed data"); JSONObject lrem = removed(); JSONObject o = new JSONObject(); o.put("minUsn", mMinUsn); o.put("lnewer", mLNewer); o.put("graves", lrem); // Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving removed data"); JSONObject rrem = mServer.start(o); if (rrem == null) { // Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (rrem.has("errorType")) { // Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[] { "error", rrem.get("errorType"), rrem.get("errorReason") }; } // Log.i(AnkiDroidApp.TAG, "Sync: applying removed data"); remove(rrem); // ... and small objects publishProgress(con, R.string.sync_small_objects_message); // Log.i(AnkiDroidApp.TAG, "Sync: collection small changes"); JSONObject lchg = changes(); JSONObject sch = new JSONObject(); sch.put("changes", lchg); // Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving small changes"); JSONObject rchg = mServer.applyChanges(sch); if (rchg == null) { // Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (rchg.has("errorType")) { // Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[] { "error", rchg.get("errorType"), rchg.get("errorReason") }; } // Log.i(AnkiDroidApp.TAG, "Sync: merging small changes"); mergeChanges(lchg, rchg); // step 3: stream large tables from server publishProgress(con, R.string.sync_download_chunk); while (true) { // Log.i(AnkiDroidApp.TAG, "Sync: downloading chunked data"); JSONObject chunk = mServer.chunk(); if (chunk == null) { // Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (chunk.has("errorType")) { // Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[] { "error", chunk.get("errorType"), chunk.get("errorReason") }; } // Log.i(AnkiDroidApp.TAG, "Sync: applying chunked data"); applyChunk(chunk); if (chunk.getBoolean("done")) { break; } } // step 4: stream to server publishProgress(con, R.string.sync_upload_chunk); while (true) { // Log.i(AnkiDroidApp.TAG, "Sync: collecting chunked data"); JSONObject chunk = chunk(); JSONObject sech = new JSONObject(); sech.put("chunk", chunk); // Log.i(AnkiDroidApp.TAG, "Sync: sending chunked data"); mServer.applyChunk(sech); if (chunk.getBoolean("done")) { break; } } // step 5: sanity check during beta testing JSONObject c = sanityCheck(); JSONObject sanity = mServer.sanityCheck2(c); if (sanity == null || !sanity.optString("status", "bad").equals("ok")) { return new Object[] { "sanityCheckError", null }; } // finalize publishProgress(con, R.string.sync_finish_message); // Log.i(AnkiDroidApp.TAG, "Sync: sending finish command"); long mod = mServer.finish(); if (mod == 0) { return new Object[] { "finishError" }; } // Log.i(AnkiDroidApp.TAG, "Sync: finishing"); finish(mod); publishProgress(con, R.string.sync_writing_db); mCol.getDb().getDatabase().setTransactionSuccessful(); } finally { mCol.getDb().getDatabase().endTransaction(); } } catch (JSONException e) { throw new RuntimeException(e); } catch (IllegalStateException e) { throw new RuntimeException(e); } catch (OutOfMemoryError e) { AnkiDroidApp.saveExceptionReportFile(e, "Syncer-sync"); return new Object[] { "OutOfMemoryError" }; } catch (IOException e) { AnkiDroidApp.saveExceptionReportFile(e, "Syncer-sync"); return new Object[] { "IOException" }; } return new Object[] { "success" }; }
From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java
public void mergeChanges(JSONObject lchg, JSONObject rchg) { try {/*from w ww . j a va2 s . c o m*/ // then the other objects mergeModels(rchg.getJSONArray("models")); mergeDecks(rchg.getJSONArray("decks")); mergeTags(rchg.getJSONArray("tags")); if (rchg.has("conf")) { mergeConf(rchg.getJSONObject("conf")); } // this was left out of earlier betas if (rchg.has("crt")) { mCol.setCrt(rchg.getLong("crt")); } } catch (JSONException e) { throw new RuntimeException(e); } prepareToChunk(); }
From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java
public void applyChunk(JSONObject chunk) { try {/* w ww . ja va 2 s. c om*/ if (chunk.has("revlog")) { mergeRevlog(chunk.getJSONArray("revlog")); } if (chunk.has("cards")) { mergeCards(chunk.getJSONArray("cards")); } if (chunk.has("notes")) { mergeNotes(chunk.getJSONArray("notes")); } } catch (JSONException e) { throw new RuntimeException(e); } }
From source file:com.basetechnology.s0.agentserver.field.MultiChoiceField.java
public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) { String type = fieldJson.optString("type"); if (type == null || !type.equals("multi_choice_field")) return null; String name = fieldJson.has("name") ? fieldJson.optString("name") : null; String label = fieldJson.has("label") ? fieldJson.optString("label") : null; String description = fieldJson.has("description") ? fieldJson.optString("description") : null; String defaultValue = fieldJson.has("default_value") ? fieldJson.optString("default_value") : null; List<String> choices = new ArrayList<String>(); if (fieldJson.has("choices")) { JSONArray choicesJson = fieldJson.optJSONArray("choices"); int n = choicesJson.length(); for (int i = 0; i < n; i++) choices.add(choicesJson.optString(i)); }/* w ww .j ava2 s . c om*/ int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0; String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null; return new MultiChoiceField(symbolTable, name, label, description, defaultValue, choices, nominalWidth, compute); }
From source file:com.EconnectTMS.CustomerInformation.java
public void Run(String IncomingMessage, String intid) throws MalformedURLException, UnsupportedEncodingException, IOException { try {//from w w w . jav a 2s.c om strRecievedData = IncomingMessage.split("#"); processingcode = strRecievedData[0]; switch (processingcode) { case "800000": AccountNumber = strRecievedData[1]; URL url = new URL(CUSTOMER_DETAILS_URL); Map<String, String> params = new LinkedHashMap<>(); params.put("username", CUSTOMER_DETAILS_USERNAME); params.put("password", CUSTOMER_DETAILS_PASSWORD); params.put("source", CUSTOMER_DETAILS_SOURCE_ID); params.put("account", AccountNumber); postData = new StringBuilder(); for (Map.Entry<String, String> param : params.entrySet()) { if (postData.length() != 0) { postData.append('&'); } postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); } urlParameters = postData.toString(); conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { result += line; } writer.close(); reader.close(); JSONObject respobj = new JSONObject(result); if (respobj.has("FSTNAME") || respobj.has("MIDNAME") || respobj.has("LSTNAME")) { if (respobj.has("FSTNAME")) { fname = respobj.get("FSTNAME").toString().toUpperCase() + ' '; } if (respobj.has("MIDNAME")) { mname = respobj.get("MIDNAME").toString().toUpperCase() + ' '; } if (respobj.has("LSTNAME")) { lname = respobj.get("LSTNAME").toString().toUpperCase() + ' '; } strCustomerName = fname + mname + lname; } else { strCustomerName = " "; } System.out.println("result:" + result); func.SendPOSResponse(strCustomerName + "#", intid); return; default: break; } } catch (Exception ex) { strCustomerName = ""; func.log("\nSEVERE CustomerInformation() :: " + ex.getMessage() + "\n" + func.StackTraceWriter(ex), "ERROR"); } }
From source file:edu.stanford.junction.api.activity.ActivityScript.java
public ActivityScript(JSONObject json) { mJSON = json;//from w ww . j a v a 2s . c o m // TODO: Deprecate. These should not be in the activityDescription. // preferred if (json.has("switchboard")) { host = json.optString("switchboard"); } // deprecated else if (json.has("host")) { host = json.optString("host"); } // TODO: rename this field if (json.has(("ad"))) { activityID = json.optString("ad"); } if (json.has("friendlyName")) { friendlyName = json.optString("friendlyName"); } if (json.has("sessionID")) { sessionID = json.optString("sessionID"); } //////////////////////////////////////////// roleSpecs = json.optJSONObject("roles"); }
From source file:edu.stanford.junction.api.activity.ActivityScript.java
public JSONObject getRolePlatform(String role, String platform) { try {//from w ww. jav a2 s . c o m JSONObject spec = getRoleSpec(role); if (spec == null) return null; spec = spec.optJSONObject("platforms"); if (spec == null) return null; if (spec.has(platform)) { return spec.getJSONObject(platform); } } catch (Exception e) { e.printStackTrace(); } return null; }