List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java
private boolean setPayloadField(String fieldName, JSONObject payloadOut, JSONObject fieldsSrc, JSONObject dataSrc, String defaultValue) throws JSONException { boolean result = true; if (fieldsSrc != null && fieldsSrc.has(fieldName)) { payloadOut.put(fieldName, fieldsSrc.getString(fieldName)); } else if (dataSrc != null && dataSrc.has(fieldName)) { payloadOut.put(fieldName, dataSrc.getString(fieldName)); } else if (defaultValue != null) { payloadOut.put(fieldName, defaultValue); } else {// w ww . j a v a 2s . c o m result = false; } return result; }
From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java
private void store_set(Storage storage, UIRequest request, String path) throws UIException { try {/* w w w. j av a 2 s.c o m*/ JSONObject restrictions = new JSONObject(); JSONObject data = request.getJSONBody(); if (this.base.equals("role")) { JSONObject fields = data.optJSONObject("fields"); if ((fields.optString("roleName") == null || fields.optString("roleName").equals("")) && fields.optString("displayName") != null) { String test = fields.optString("displayName"); test = test.toUpperCase(); test.replaceAll("\\W", "_"); fields.put("roleName", "ROLE_" + test); data.put("fields", fields); } // If we are updating a role, then we need to clear the userperms cache // Note that creating a role does not impact things until we assign it if (!create) { ResponseCache.clearCache(ResponseCache.USER_PERMS_CACHE); } } if (this.record.getID().equals("media")) { JSONObject fields = data.optJSONObject("fields"); // Handle linked media references if (!fields.has("blobCsid") || StringUtils.isEmpty(fields.getString("blobCsid"))) { // If has blobCsid, already has media link so do nothing more // No media, so consider the source // "sourceUrl" is not a declared field in the app layer config, but the UI passes it in // Can consider mapping srcUri to this if want to clean that up if (fields.has("sourceUrl")) { // We have a source - see where it is from String uri = fields.getString("sourceUrl"); if (uri.contains(BLOBS_SERVICE_URL_PATTERN)) { // This is an uploaded blob, so just pull the csid and set into blobCsid String[] parts = uri.split(BLOBS_SERVICE_URL_PATTERN); // Split to get CSID String[] bits = parts[1].split("/"); // Strip off anything trailing the CSID fields.put("blobCsid", bits[0]); } else { // This must be an external Url source // External Source is handled as params to the CREATE/UPDATE of the media record restrictions.put(Record.BLOB_SOURCE_URL, uri); // Tell the Services to delete the original after creating derivatives restrictions.put(Record.BLOB_PURGE_ORIGINAL, Boolean.toString(true)); } fields.remove("sourceUrl"); data.put("fields", fields); } } } if (this.record.getID().equals("output")) { // // Invoke a report // ReportUtils.invokeReport(this, storage, request, path); } else if (this.record.getID().equals("batchoutput")) { //do a read instead of a create as reports are special and evil JSONObject fields = data.optJSONObject("fields"); JSONObject payload = new JSONObject(); payload.put("mode", "single"); if (fields.has("mode")) { payload.put("mode", fields.getString("mode")); } if (fields.has("docType")) { String type = spec.getRecordByWebUrl(fields.getString("docType")).getServicesTenantSg(); payload.put("docType", type); } if (fields.has("singleCSID")) { payload.put("singleCSID", fields.getString("singleCSID")); } else if (fields.has("groupCSID")) { payload.put("singleCSID", fields.getString("csid")); } JSONObject out = storage.retrieveJSON(base + "/" + path, payload); byte[] data_array = (byte[]) out.get("getByteBody"); String contentDisp = out.has("contentdisposition") ? out.getString("contentdisposition") : null; request.sendUnknown(data_array, out.getString("contenttype"), contentDisp); request.setCacheMaxAgeSeconds(0); // Ensure we do not cache report output. //request.sendJSONResponse(out); request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE); } else { // // <Please document this clause.> // FieldSet displayNameFS = this.record.getDisplayNameField(); String displayNameFieldName = (displayNameFS != null) ? displayNameFS.getID() : null; boolean remapDisplayName = false; String remapDisplayNameValue = null; boolean quickie = false; if (create) { quickie = (data.has("_view") && data.getString("_view").equals("autocomplete")); remapDisplayName = quickie && !"displayName".equals(displayNameFieldName); // Check to see if displayName field needs remapping from UI if (remapDisplayName) { // Need to map the field for displayName, and put it into a proper structure JSONObject fields = data.getJSONObject("fields"); remapDisplayNameValue = fields.getString("displayName"); if (remapDisplayNameValue != null) { // This needs generalizing, in case the remapped name is nested /* * From vocab handling where we know where the termDisplayName is FieldSet parentTermGroup = (FieldSet)displayNameFS.getParent(); JSONArray parentTermInfoArray = new JSONArray(); JSONObject termInfo = new JSONObject(); termInfo.put(displayNameFieldName, remapDisplayNameValue); parentTermInfoArray.put(termInfo); */ fields.put(displayNameFieldName, remapDisplayNameValue); fields.remove("displayName"); } } path = sendJSON(storage, null, data, restrictions); // REM - We needed a way to send query params, so I'm adding "restrictions" here data.put("csid", path); data.getJSONObject("fields").put("csid", path); // Is this needed??? /* String refName = data.getJSONObject("fields").getString("refName"); data.put("urn", refName); data.getJSONObject("fields").put("urn", refName); // This seems wrong - especially when we create from existing. if(remapDisplayName){ JSONObject newdata = new JSONObject(); newdata.put("urn", refName); newdata.put("displayName",quickieDisplayName); data = newdata; } */ } else { path = sendJSON(storage, path, data, restrictions); } if (path == null) { throw new UIException("Insufficient data for create (no fields?)"); } if (this.base.equals("role")) { assignPermissions(storage, path, data); } if (this.base.equals("termlist")) { assignTerms(storage, path, data); } data = reader.getJSON(storage, path); // We do a GET now to read back what we created. if (quickie) { JSONObject newdata = new JSONObject(); JSONObject fields = data.getJSONObject("fields"); String displayName = fields.getString(remapDisplayName ? displayNameFieldName : "displayName"); newdata.put("displayName", remapDisplayNameValue); String refName = fields.getString("refName"); newdata.put("urn", refName); data = newdata; } request.sendJSONResponse(data); request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE); if (create) request.setSecondaryRedirectPath(new String[] { url_base, path }); } } catch (JSONException x) { throw new UIException("Failed to parse JSON: " + x, x); } catch (ExistException x) { UIException uiexception = new UIException(x.getMessage(), 0, "", x); request.sendJSONResponse(uiexception.getJSON()); } catch (UnimplementedException x) { throw new UIException("Unimplemented exception: " + x, x); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x); request.setStatus(x.getStatus()); request.setFailure(true, uiexception); request.sendJSONResponse(uiexception.getJSON()); } catch (Exception x) { throw new UIException(x); } }
From source file:com.example.espn.headlines.Util.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 ww . 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:edu.stanford.junction.provider.irc.Junction.java
@Override public void doSendMessageToRole(String role, JSONObject message) { JSONObject jx;//w w w . j a v a 2s . co m if (message.has(NS_JX)) { jx = message.optJSONObject(NS_JX); } else { jx = new JSONObject(); try { message.put(NS_JX, jx); } catch (JSONException j) { } } try { jx.put("targetRole", role); } catch (Exception e) { } String msg = message.toString(); sendMsgTo(msg, "#" + mSession + "," + mNickname); }
From source file:ti.mobileapptracker.MobileapptrackerModule.java
private List<MATEventItem> convertToMATEventItems(Object[] arrItemMaps) { List<MATEventItem> listItems = new ArrayList<MATEventItem>(); try {//from w ww .j a va2 s. co m JSONArray arr = new JSONArray(Arrays.toString(arrItemMaps)); for (int i = 0; i < arr.length(); i++) { JSONObject item = arr.getJSONObject(i); String itemName = item.getString("item"); int quantity = 0; double unitPrice = 0; double revenue = 0; String attribute1 = null; String attribute2 = null; String attribute3 = null; String attribute4 = null; String attribute5 = null; if (item.has("quantity")) { quantity = item.getInt("quantity"); } if (item.has("unit_price")) { unitPrice = item.getDouble("unit_price"); } if (item.has("revenue")) { revenue = item.getDouble("revenue"); } if (item.has("attribute_sub1")) { attribute1 = item.getString("attribute_sub1"); } if (item.has("attribute_sub2")) { attribute2 = item.getString("attribute_sub2"); } if (item.has("attribute_sub3")) { attribute3 = item.getString("attribute_sub3"); } if (item.has("attribute_sub4")) { attribute4 = item.getString("attribute_sub4"); } if (item.has("attribute_sub5")) { attribute5 = item.getString("attribute_sub5"); } MATEventItem eventItem = new MATEventItem(itemName, quantity, unitPrice, revenue, attribute1, attribute2, attribute3, attribute4, attribute5); listItems.add(eventItem); } } catch (JSONException e) { e.printStackTrace(); } return listItems; }
From source file:net.mandaria.radioreddit.apis.RedditAPI.java
public static String Vote(Context context, RedditAccount account, int voteDirection, String fullname) { String errorMessage = ""; try {/*from w w w.ja va 2 s. c om*/ try { account.Modhash = updateModHash(context); if (account.Modhash == null) { errorMessage = context.getString(R.string.error_ThereWasAProblemVotingPleaseTryAgain); return errorMessage; } } catch (Exception ex) { errorMessage = ex.getMessage(); return errorMessage; } String url = context.getString(R.string.reddit_vote); // post values ArrayList<NameValuePair> post_values = new ArrayList<NameValuePair>(); BasicNameValuePair id = new BasicNameValuePair("id", fullname); post_values.add(id); BasicNameValuePair dir = new BasicNameValuePair("dir", Integer.toString(voteDirection)); post_values.add(dir); // not required //BasicNameValuePair r = new BasicNameValuePair("r", "radioreddit"); // TODO: shouldn't be hard coded, could be talkradioreddit //post_values.add(r); BasicNameValuePair uh = new BasicNameValuePair("uh", account.Modhash); post_values.add(uh); BasicNameValuePair api_type = new BasicNameValuePair("api_type", "json"); post_values.add(api_type); String outputVote = HTTPUtil.post(context, url, post_values); JSONTokener reddit_vote_tokener = new JSONTokener(outputVote); JSONObject reddit_vote_json = new JSONObject(reddit_vote_tokener); if (reddit_vote_json.has("json")) { JSONObject json = reddit_vote_json.getJSONObject("json"); if (json.has("errors") && json.getJSONArray("errors").length() > 0) { String error = json.getJSONArray("errors").getJSONArray(0).getString(1); errorMessage = error; } } // success! } catch (Exception ex) { // We fail to vote... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); errorMessage = ex.toString(); } return errorMessage; }
From source file:com.norman0406.slimgress.API.Interface.RequestResult.java
public static void handleRequest(JSONObject json, RequestResult result) { if (result == null) throw new RuntimeException("invalid result object"); try {//from w w w. j a v a2 s . c om // handle exception string if available String excString = json.optString("exception"); if (excString.length() > 0) result.handleException(excString); // handle error code if available String error = json.optString("error"); if (error.length() > 0) result.handleError(error); else if (json.has("error")) Log.w("RequestResult", "request contains an unknown error type"); // handle game basket if available JSONObject gameBasket = json.optJSONObject("gameBasket"); if (gameBasket != null) result.handleGameBasket(new GameBasket(gameBasket)); // handle result if available JSONObject resultObj = json.optJSONObject("result"); JSONArray resultArr = json.optJSONArray("result"); String resultStr = json.optString("result"); if (resultObj != null) result.handleResult(resultObj); else if (resultArr != null) result.handleResult(resultArr); else if (resultStr != null) result.handleResult(resultStr); else if (json.has("result")) Log.w("RequestResult", "request contains an unknown result type"); result.finished(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.dzt.uberclone.HomeFragment.java
private void handleDriverTracking(String json) { try {/*w ww . java 2 s .c o m*/ JSONObject jsonObject = new JSONObject(json); if (jsonObject.has("fee")) { trackDriverBoolean = false; double initialLat = jsonObject.getDouble("initial_lat"); double initialLng = jsonObject.getDouble("initial_lng"); double finalLat = jsonObject.getDouble("final_lat"); double finalLng = jsonObject.getDouble("final_lng"); String distance = jsonObject.getString("distance"); String time = jsonObject.getString("time"); String fee = jsonObject.getString("fee"); String finalFee = jsonObject.getString("final_fee"); Bundle params = new Bundle(); params.putString("originText", initialLat + "," + initialLng); params.putString("destinationText", finalLat + "," + finalLng); params.putString("timeText", time); params.putString("distanceText", distance); params.putString("feeText", fee); params.putString("finalFeeText", finalFee); params.putString("rideId", currentRideId); /* StringBuilder sb = new StringBuilder(); sb.append("You went from "); sb.append(initialLat); sb.append(","); sb.append(initialLng); sb.append(" to "); sb.append(finalLat); sb.append(","); sb.append(finalLng); sb.append(". Your time was "); sb.append(time); sb.append(" minutes and rode a distance of "); sb.append(distance); sb.append(" KM. Your fee is $"); sb.append(fee); sb.append(" and your adjusted fee is $"); sb.append(finalFee); Log.i("ride details", sb.toString()); Toast.makeText(getActivity(), sb.toString(), Toast.LENGTH_LONG).show(); */ Intent intent = new Intent(getActivity(), RideDetailsActivity.class); intent.putExtras(params); startActivity(intent); getActivity().finish(); } else { double lat = jsonObject.getDouble("latitude"); double lng = jsonObject.getDouble("longitude"); addAssignedUberMarker(lat, lng); } } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.funzio.pure2D.particles.nova.vo.MotionTrailVO.java
public static MotionTrailVO create(final JSONObject json) throws JSONException { if (!json.has("type")) { return null; }/* www .j a v a 2s . c o m*/ final String type = json.getString("type"); if (type.equalsIgnoreCase(SHAPE)) { return new MotionTrailShapeVO(json); } else { return null; } }
From source file:org.wso2.carbon.connector.integration.test.googleanalytics.GoogleanalyticsConnectorIntegrationTest.java
/** * Positive test case for createFilter method with optional parameters. * * @throws org.json.JSONException//from w w w. j a v a 2 s .c o m * @throws java.io.IOException */ @Test(groups = { "wso2.esb" }, description = "googleanalytics {createFilter} integration test with optional parameters.", dependsOnMethods = { "testListAccountSummariesWithMandatoryParameters" }) public void testCreateFilterWithOptionalParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:createFilter"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_createFilter_optional.json"); final JSONObject esbResponse = esbRestResponse.getBody(); final String filterId = esbResponse.getString("id"); connectorProperties.put("filterIdOpt", filterId); final String apiEndpoint = apiEndpointUrl + "/management/accounts/" + connectorProperties.getProperty("accountId") + "/filters/" + filterId + "?fields=" + connectorProperties.getProperty("fields"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap); final String apiEndpointField = apiEndpointUrl + "/management/accounts/" + connectorProperties.getProperty("accountId") + "/filters/" + filterId; RestResponse<JSONObject> apiRestResponseWithField = sendJsonRestRequest(apiEndpointField, "GET", apiRequestHeadersMap); final JSONObject apiResponse = apiRestResponse.getBody(); Assert.assertEquals(esbResponse.getString("kind"), apiResponse.getString("kind")); Assert.assertEquals(esbResponse.getString("id"), apiResponse.getString("id")); Assert.assertFalse(esbResponse.has("selfLink")); Assert.assertFalse(apiResponse.has("selfLink")); Assert.assertTrue(apiRestResponseWithField.getBody().has("selfLink")); }