List of usage examples for org.json JSONObject optString
public String optString(String key)
From source file:org.jenkinsci.plugins.testrail.TestRailClient.java
private Case createCaseFromJson(JSONObject o) { Case s = new Case(); s.setTitle(o.getString("title")); s.setId(o.getInt("id")); s.setSectionId(o.getInt("section_id")); s.setRefs(o.optString("refs")); return s;//from ww w . j ava2 s. co m }
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
/** * Inserts an object into the database and flags it to be sent by * the transport layer./*from w w w . ja va 2 s . c o m*/ */ long addToFeed(String appId, String feedName, ContentValues values) { try { JSONObject json = new JSONObject(values.getAsString(DbObject.JSON)); String type = values.getAsString(DbObject.TYPE); long nextSeqId = getFeedMaxSequenceId(Contact.MY_ID, feedName) + 1; long timestamp = new Date().getTime(); json.put(DbObjects.TYPE, type); json.put(DbObjects.FEED_NAME, feedName); json.put(DbObjects.SEQUENCE_ID, nextSeqId); json.put(DbObjects.TIMESTAMP, timestamp); json.put(DbObjects.APP_ID, appId); // Explicit column referencing avoids database errors. ContentValues cv = new ContentValues(); cv.put(DbObject._ID, getNextId()); cv.put(DbObject.APP_ID, appId); cv.put(DbObject.FEED_NAME, feedName); cv.put(DbObject.CONTACT_ID, Contact.MY_ID); cv.put(DbObject.TYPE, type); cv.put(DbObject.SEQUENCE_ID, nextSeqId); cv.put(DbObject.JSON, json.toString()); cv.put(DbObject.TIMESTAMP, timestamp); cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime()); if (values.containsKey(DbObject.RAW)) { cv.put(DbObject.RAW, values.getAsByteArray(DbObject.RAW)); } if (values.containsKey(DbObject.KEY_INT)) { cv.put(DbObject.KEY_INT, values.getAsInteger(DbObject.KEY_INT)); } if (json.has(DbObject.CHILD_FEED_NAME)) { cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME)); } if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT) throw new RuntimeException("Messasge size is too large for sending"); Long objId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv); if (json.has(DbObjects.TARGET_HASH)) { long hashA = json.optLong(DbObjects.TARGET_HASH); long idA = objIdForHash(hashA); String relation; if (json.has(DbObjects.TARGET_RELATION)) { relation = json.optString(DbObjects.TARGET_RELATION); } else { relation = DbRelation.RELATION_PARENT; } if (idA == -1) { Log.e(TAG, "No objId found for hash " + hashA); } else { addObjRelation(idA, objId, relation); } } Uri objUri = DbObject.uriForObj(objId); mContext.getContentResolver().registerContentObserver(objUri, false, new ModificationObserver(mContext, objId)); return objId; } catch (Exception e) { // TODO, too spammy //e.printStackTrace(System.err); return -1; } }
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
long addObjectByJson(long contactId, JSONObject json, long hash, byte[] raw, Integer intKey) { try {/* w ww . j a v a 2s. c o m*/ long objId = getNextId(); long seqId = json.optLong(DbObjects.SEQUENCE_ID); long timestamp = json.getLong(DbObjects.TIMESTAMP); String feedName = json.getString(DbObjects.FEED_NAME); String type = json.getString(DbObjects.TYPE); String appId = json.getString(DbObjects.APP_ID); ContentValues cv = new ContentValues(); cv.put(DbObject._ID, objId); cv.put(DbObject.APP_ID, appId); cv.put(DbObject.FEED_NAME, feedName); cv.put(DbObject.CONTACT_ID, contactId); cv.put(DbObject.TYPE, type); cv.put(DbObject.SEQUENCE_ID, seqId); cv.put(DbObject.JSON, json.toString()); cv.put(DbObject.TIMESTAMP, timestamp); cv.put(DbObject.HASH, hash); cv.put(DbObject.SENT, 1); cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime()); if (raw != null) { cv.put(DbObject.RAW, raw); } if (intKey != null) { cv.put(DbObject.KEY_INT, intKey); } // TODO: Deprecated!! if (json.has(DbObject.CHILD_FEED_NAME)) { cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME)); } if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT) throw new RuntimeException("Messasge size is too large for sending"); long newObjId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv); String notifyName = feedName; if (json.has(DbObjects.TARGET_HASH)) { long hashA = json.optLong(DbObjects.TARGET_HASH); long idA = objIdForHash(hashA); notifyName = feedName + ":" + hashA; String relation; if (json.has(DbObjects.TARGET_RELATION)) { relation = json.optString(DbObjects.TARGET_RELATION); } else { relation = DbRelation.RELATION_PARENT; } if (idA == -1) { Log.e(TAG, "No objId found for hash " + hashA); } else { addObjRelation(idA, newObjId, relation); } } ContentResolver resolver = mContext.getContentResolver(); DungBeetleContentProvider.notifyDependencies(this, resolver, notifyName); updateObjModification(App.instance().getMusubi().objForId(newObjId)); return objId; } catch (Exception e) { if (DBG) Log.e(TAG, "Error adding object by json.", e); return -1; } }
From source file:org.catnut.metadata.WeiboAPIError.java
/** * volley?/*from w w w . ja va2s . c o m*/ * * @param volleyError * @return WeiboAPIError */ public static WeiboAPIError fromVolleyError(VolleyError volleyError) { // very bad situation! if (volleyError.networkResponse == null) { String message = volleyError.getLocalizedMessage(); return new WeiboAPIError(-1, null, TextUtils.isEmpty(message) ? volleyError.getClass().getName() : message); } // ?response body String jsonString; try { jsonString = new String(volleyError.networkResponse.data); } catch (Exception e) { Log.wtf(TAG, e); // fall back to http error! String msg = volleyError.getLocalizedMessage(); return new WeiboAPIError(volleyError.networkResponse.statusCode, null, TextUtils.isEmpty(msg) ? "Unknown error! Please try again later:-(" : msg); } try { JSONObject jsonObject = new JSONObject(jsonString); return new WeiboAPIError(jsonObject.optInt(ERROR_CODE), jsonObject.optString(REQUEST), jsonObject.optString(ERROR)); } catch (JSONException e) { Log.wtf(TAG, e.getLocalizedMessage()); } // never happen? return null; }
From source file:com.phonegap.plugins.discoverscanar.DiscoverScanAR.java
/** * Executes the request./*from ww w. j a v a 2 s. c o m*/ * * This method is called from the WebView thread. To do a non-trivial amount of work, use: * cordova.getThreadPool().execute(runnable); * * To run on the UI thread, use: * cordova.getActivity().runOnUiThread(runnable); * * @param action The action to execute. * @param args The exec() arguments. * @param callbackContext The callback context used when calling back into JavaScript. * @return Whether the action was valid. * * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java */ @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { this.callbackContext = callbackContext; if (action.equals(ENCODE)) { JSONObject obj = args.optJSONObject(0); if (obj != null) { String type = obj.optString(TYPE); String data = obj.optString(DATA); // If the type is null then force the type to text if (type == null) { type = TEXT_TYPE; } if (data == null) { callbackContext.error("User did not specify data to encode"); return true; } encode(type, data); } else { callbackContext.error("User did not specify data to encode"); return true; } } else if (action.equals(SCAN)) { // Section threading of http://docs.phonegap.com/en/2.3.0/guide_plugin-development_android_index.md.html // But it still displayed the error "Plugin should use CordovaInterface.getThreadPool" cordova.getThreadPool().execute(new Runnable() { //CordovaInterface.getThreadPool().execute(new Runnable() { public void run() { scan(); } }); } else if (action.equals(ARSCAN)) { JSONObject obj = args.optJSONObject(0); // If the type is null then force the type to text final String json_file = (obj != null) ? obj.optString(JSONFILE) : null; /* final String json_file = null; if (obj != null) { json_file = obj.optString(JSONFILE); // If the type is null then force the type to text }*/ if (json_file != null) { cordova.getThreadPool().execute(new Runnable() { //CordovaInterface.getThreadPool().execute(new Runnable() { public void run() { arscan(json_file); } }); } else { callbackContext.error("User did not specify a json file to load"); } } else { return false; } return true; }
From source file:eu.trentorise.smartcampus.ac.network.RemoteConnector.java
/** * @param string// w w w . j a va 2 s .c o m * @param refresh * @param clientId * @param clientSecret * @throws AACException */ public static TokenData refreshToken(String service, String refresh, String clientId, String clientSecret) throws AACException { HttpResponse resp = null; HttpEntity entity = null; Log.i(TAG, "refreshing token: " + refresh); String url = service + PATH_TOKEN + "?grant_type=refresh_token&refresh_token=" + refresh + "&client_id=" + clientId + "&client_secret=" + clientSecret; HttpPost post = new HttpPost(url); post.setEntity(entity); post.setHeader("Accept", "application/json"); try { resp = getHttpClient().execute(post); String response = EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { TokenData data = TokenData.valueOf(response); Log.v(TAG, "Successful authentication"); return data; } Log.e(TAG, "Error validating " + resp.getStatusLine()); try { JSONObject error = new JSONObject(response); if (error != null && error.has("error")) { throw new AACException(HttpStatus.SC_UNAUTHORIZED, "OAuth error " + error.optString("error_description")); } } catch (JSONException e) { Log.w(TAG, "Unknown response message:" + resp.getStatusLine()); } throw new AACException("Error validating " + resp.getStatusLine()); // } catch (Exception e) { // Log.e(TAG, "Exception when getting authtoken", e); // if (resp != null) { // throw new AACException(resp.getStatusLine().getStatusCode(), ""+e.getMessage()); // } else { // throw new AACException(e); // } } catch (ClientProtocolException e) { if (resp != null) { throw new AACException(resp.getStatusLine().getStatusCode(), "" + e.getMessage()); } else { throw new AACException(e); } } catch (IOException e) { if (resp != null) { throw new AACException(resp.getStatusLine().getStatusCode(), "" + e.getMessage()); } else { throw new AACException(e); } } finally { Log.v(TAG, "refresh token completing"); } }
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.FeedRefObj.java
public void render(Context context, ViewGroup frame, Obj obj, boolean allowInteractions) { JSONObject content = obj.getJson(); byte[] raw = obj.getRaw(); TextView view = new TextView(context); view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); String feedName = content.optString(FEED_ID); view.setText(feedName);/*from w w w .j a v a 2s .com*/ view.setBackgroundColor(Feed.colorFor(feedName)); frame.addView(view); }
From source file:com.basetechnology.s0.agentserver.field.ChoiceField.java
public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) { String type = fieldJson.optString("type"); if (type == null || !type.equals("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)); }/* ww w. j ava 2s .co m*/ int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0; String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null; return new ChoiceField(symbolTable, name, label, description, defaultValue, choices, nominalWidth, compute); }
From source file:com.sina.weibo.sdk_lib.openapi.models.PoiList.java
public static PoiList parse(String jsonString) { if (TextUtils.isEmpty(jsonString)) { return null; }/*from ww w .j av a 2 s.c om*/ PoiList poiList = new PoiList(); try { JSONObject jsonObject = new JSONObject(jsonString); poiList.totalNumber = jsonObject.optString("total_number"); JSONArray jsonArray = jsonObject.optJSONArray("geos"); if (jsonArray != null && jsonArray.length() > 0) { int length = jsonArray.length(); poiList.pois = new ArrayList<Poi>(length); for (int ix = 0; ix < length; ix++) { poiList.pois.add(Poi.parse(jsonArray.optJSONObject(ix))); } } } catch (JSONException e) { e.printStackTrace(); } return poiList; }
From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java
private void inflateAmortizationSpinner(ResponseBody result) { final List<AmortizationType> amortizationType = new ArrayList<>(); // you can use this array to populate your spinner final ArrayList<String> amortizationTypeNames = new ArrayList<String>(); //Try to get response body BufferedReader reader = null; StringBuilder sb = new StringBuilder(); try {//from w w w . jav a2s . c o m reader = new BufferedReader(new InputStreamReader(result.byteStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line); } JSONObject obj = new JSONObject(sb.toString()); if (obj.has("amortizationTypeOptions")) { JSONArray amortizationTypes = obj.getJSONArray("amortizationTypeOptions"); for (int i = 0; i < amortizationTypes.length(); i++) { JSONObject amortizationTypeObject = amortizationTypes.getJSONObject(i); AmortizationType amortization = new AmortizationType(); amortization.setId(amortizationTypeObject.optInt("id")); amortization.setValue(amortizationTypeObject.optString("value")); amortizationType.add(amortization); amortizationTypeNames.add(amortizationTypeObject.optString("value")); amortizationTypeIdHashMap.put(amortization.getValue(), amortization.getId()); } } String stringResult = sb.toString(); } catch (Exception e) { Log.e(LOG_TAG, "", e); } final ArrayAdapter<String> amortizationTypeAdapter = new ArrayAdapter<>(getActivity(), layout.simple_spinner_item, amortizationTypeNames); amortizationTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item); sp_amortization.setAdapter(amortizationTypeAdapter); sp_amortization.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { amortizationTypeId = amortizationTypeIdHashMap.get(amortizationTypeNames.get(i)); Log.d("ammortization" + amortizationTypeNames.get(i), String.valueOf(amortizationTypeId)); if (amortizationTypeId != -1) { } else { Toast.makeText(getActivity(), getString(R.string.error_select_fund), Toast.LENGTH_SHORT).show(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }