List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:org.collectionspace.chain.csp.persistence.services.TestPermissions.java
@Test public void testRoles() throws Exception { //create user JSONObject userdata = createUser("user1.json"); String userId = userdata.getString("userId"); String csidId = userdata.getString("accountId"); assertFalse(userdata == null);// w w w . ja v a 2 s .com //list roles for user //cspace-services/authorization/roles/{csid}/permroles/xxx Storage ss; ss = makeServicesStorage(); JSONObject data = ss.getPathsJSON("accounts/" + userId + "/accountrole", null); String[] roleperms = (String[]) data.get("listItems"); log.info(data.toString()); if (roleperms.length > 0) { log.info("has roles already"); } //create a role JSONObject roledata = createRole("role.json"); String role = roledata.getString("roleId"); log.info(roledata.toString()); assertFalse(roledata == null); //add a role JSONObject addroledata = new JSONObject(); addroledata.put("roleId", role); addroledata.put("roleName", roledata.getString("roleName")); JSONArray rolearray = new JSONArray(); rolearray.put(addroledata); JSONObject addrole = new JSONObject(); addrole.put("role", rolearray); addrole.put("account", userdata); log.info(addrole.toString()); //add permissions to role String path = ss.autocreateJSON("userrole", addrole, null); log.info(path); assertNotNull(path); //delete role ss.deleteJSON("role/" + role); try { ss.retrieveJSON("role/" + role, new JSONObject()); assertFalse(true); // XXX use JUnit exception annotation } catch (UnderlyingStorageException e) { assertTrue(true); // XXX use JUnit exception annotation } //delete user ss.deleteJSON("users/" + csidId); }
From source file:org.collectionspace.chain.csp.persistence.services.TestPermissions.java
@Test public void testPermissions() throws Exception { //create role JSONObject roledata = createRole("role.json"); String role = roledata.getString("roleId"); log.info(roledata.toString());//from ww w . j ava 2 s .co m assertFalse(roledata == null); //list permissions for role //cspace-services/authorization/roles/{csid}/permroles/xxx Storage ss; ss = makeServicesStorage(); JSONObject data = ss.getPathsJSON("roles/" + role + "/permrole", null); String[] roleperms = (String[]) data.get("listItems"); log.info(data.toString()); if (roleperms.length > 0) { log.info("has permissions already"); } //add a permission //get acquisition crudl ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL String resourceName = "acquisition"; JSONObject permrestrictions = new JSONObject(); permrestrictions.put("keywords", resourceName); permrestrictions.put("queryString", "CRUDL"); permrestrictions.put("queryTerm", "actGrp"); JSONObject pdata = ss.getPathsJSON("permission", permrestrictions); String[] perms = (String[]) pdata.get("listItems"); String permID = ""; if (perms.length > 0) { permID = perms[0]; } else { //need to create this permission type fail("missing permission type Acquisition CRUDL " + permrestrictions.toString()); } JSONObject permdata = new JSONObject(); permdata.put("permissionId", permID); permdata.put("resourceName", resourceName); JSONArray permarray = new JSONArray(); permarray.put(permdata); JSONObject addperm = new JSONObject(); addperm.put("permission", permarray); addperm.put("role", roledata); log.info(addperm.toString()); //add permissions to role String path = ss.autocreateJSON("permrole", addperm, null); log.info(path); assertNotNull(path); //test permissions is in role //delete role ss.deleteJSON("role/" + role); try { ss.retrieveJSON("role/" + role, new JSONObject()); assertFalse(true); // XXX use JUnit exception annotation } catch (UnderlyingStorageException e) { assertTrue(true); // XXX use JUnit exception annotation } }
From source file:org.akvo.caddisfly.helper.TestConfigHelper.java
/** * Creates the json result containing the results for test. * @param testInfo information about the test * @param results the results for the test * @param color the color extracted// w w w . j ava2 s . c om * @param resultImageUrl the url of the image * @param groupingType type of grouping * @return the result in json format */ public static JSONObject getJsonResult(TestInfo testInfo, SparseArray<String> results, int color, String resultImageUrl, StripTest.GroupType groupingType) { JSONObject resultJson = new JSONObject(); try { resultJson.put(SensorConstants.TYPE, SensorConstants.TYPE_NAME); resultJson.put(SensorConstants.NAME, testInfo.getName()); resultJson.put(SensorConstants.UUID, testInfo.getId()); JSONArray resultsJsonArray = new JSONArray(); for (TestInfo.SubTest subTest : testInfo.getSubTests()) { JSONObject subTestJson = new JSONObject(); subTestJson.put(SensorConstants.NAME, subTest.getDesc()); subTestJson.put(SensorConstants.UNIT, subTest.getUnit()); subTestJson.put(SensorConstants.ID, subTest.getId()); // If a result exists for the sub test id then add it if (results.size() >= subTest.getId()) { subTestJson.put(SensorConstants.VALUE, results.get(subTest.getId())); } if (color > -1) { subTestJson.put("resultColor", Integer.toHexString(color & BIT_MASK)); // Add calibration details to result subTestJson.put("calibratedDate", testInfo.getCalibrationDateString()); subTestJson.put("reagentExpiry", testInfo.getExpiryDateString()); subTestJson.put("reagentBatch", testInfo.getBatchNumber()); JSONArray calibrationSwatches = new JSONArray(); for (Swatch swatch : testInfo.getSwatches()) { calibrationSwatches.put(Integer.toHexString(swatch.getColor() & BIT_MASK)); } subTestJson.put("calibration", calibrationSwatches); } resultsJsonArray.put(subTestJson); if (groupingType == StripTest.GroupType.GROUP) { break; } } resultJson.put(SensorConstants.RESULT, resultsJsonArray); if (!resultImageUrl.isEmpty()) { resultJson.put(SensorConstants.IMAGE, resultImageUrl); } // Add current date to result resultJson.put("testDate", new SimpleDateFormat(SensorConstants.DATE_TIME_FORMAT, Locale.US) .format(Calendar.getInstance().getTime())); // Add user preference details to the result resultJson.put(SensorConstants.USER, TestConfigHelper.getUserPreferences()); // Add app details to the result resultJson.put(SensorConstants.APP, TestConfigHelper.getAppDetails()); // Add standard diagnostic details to the result resultJson.put(SensorConstants.DEVICE, TestConfigHelper.getDeviceDetails()); } catch (JSONException e) { Timber.e(e); } return resultJson; }
From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java
public TokenResponse sign(String jsonRequest, String origin, Boolean isDeny) throws JSONException, IOException, U2FException { if (BuildConfig.DEBUG) Log.d(TAG, "Starting to process sign request: " + jsonRequest); JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue(); JSONArray authenticateRequestArray = null; if (request.has("authenticateRequests")) { authenticateRequestArray = request.getJSONArray("authenticateRequests"); if (authenticateRequestArray.length() == 0) { throw new U2FException("Failed to get authentication request!"); }/* w w w . jav a 2s . co m*/ } else { authenticateRequestArray = new JSONArray(); authenticateRequestArray.put(request); } Log.i(TAG, "Found " + authenticateRequestArray.length() + " authentication requests"); AuthenticateResponse authenticateResponse = null; String authenticatedChallenge = null; JSONObject authRequest = null; for (int i = 0; i < authenticateRequestArray.length(); i++) { if (BuildConfig.DEBUG) Log.d(TAG, "Process authentication request: " + authRequest); authRequest = (JSONObject) authenticateRequestArray.get(i); if (!authRequest.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) { throw new U2FException("Unsupported U2F_V2 version!"); } String version = authRequest.getString(JSON_PROPERTY_VERSION); String appParam = authRequest.getString(JSON_PROPERTY_APP_ID); String challenge = authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE); byte[] keyHandle = Base64.decode(authRequest.getString(JSON_PROPERTY_KEY_HANDLE), Base64.URL_SAFE | Base64.NO_WRAP); authenticateResponse = u2fKey.authenticate(new AuthenticateRequest(version, AuthenticateRequest.USER_PRESENCE_SIGN, challenge, appParam, keyHandle)); if (BuildConfig.DEBUG) Log.d(TAG, "Authentication response: " + authenticateResponse); if (authenticateResponse != null) { authenticatedChallenge = challenge; break; } } if (authenticateResponse == null) { return null; } JSONObject clientData = new JSONObject(); if (isDeny) { clientData.put(JSON_PROPERTY_REQUEST_TYPE, AUTHENTICATE_CANCEL_TYPE); } else { clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_AUTHENTICATE); } clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE)); clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin); String keyHandle = authRequest.getString(JSON_PROPERTY_KEY_HANDLE); String clientDataString = clientData.toString(); byte[] resp = rawMessageCodec.encodeAuthenticateResponse(authenticateResponse); JSONObject response = new JSONObject(); response.put("signatureData", Utils.base64UrlEncode(resp)); response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII")))); response.put("keyHandle", keyHandle); TokenResponse tokenResponse = new TokenResponse(); tokenResponse.setResponse(response.toString()); tokenResponse.setChallenge(authenticatedChallenge); tokenResponse.setKeyHandle(keyHandle); return tokenResponse; }
From source file:com.hichinaschool.flashcards.anki.CardEditor.java
@Override protected Dialog onCreateDialog(int id) { StyledDialog dialog = null;//from w w w . j a v a2 s. c o m Resources res = getResources(); StyledDialog.Builder builder = new StyledDialog.Builder(this); switch (id) { case DIALOG_TAGS_SELECT: builder.setTitle(R.string.card_details_tags); builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mAddNote) { try { JSONArray ja = new JSONArray(); for (String t : selectedTags) { ja.put(t); } mCol.getModels().current().put("tags", ja); mCol.getModels().setChanged(); } catch (JSONException e) { throw new RuntimeException(e); } mEditorNote.setTags(selectedTags); } mCurrentTags = selectedTags; updateTags(); } }); builder.setNegativeButton(res.getString(R.string.cancel), null); mNewTagEditText = (EditText) new EditText(this); mNewTagEditText.setHint(R.string.add_new_tag); InputFilter filter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (source.charAt(i) == ' ' || source.charAt(i) == ',') { return ""; } } return null; } }; mNewTagEditText.setFilters(new InputFilter[] { filter }); ImageView mAddTextButton = new ImageView(this); mAddTextButton.setImageResource(R.drawable.ic_addtag); mAddTextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tag = mNewTagEditText.getText().toString(); if (tag.length() != 0) { if (mEditorNote.hasTag(tag)) { mNewTagEditText.setText(""); return; } selectedTags.add(tag); actualizeTagDialog(mTagsDialog); mNewTagEditText.setText(""); } } }); FrameLayout frame = new FrameLayout(this); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL); params.rightMargin = 10; mAddTextButton.setLayoutParams(params); frame.addView(mNewTagEditText); frame.addView(mAddTextButton); builder.setView(frame, false, true); dialog = builder.create(); mTagsDialog = dialog; break; case DIALOG_DECK_SELECT: ArrayList<CharSequence> dialogDeckItems = new ArrayList<CharSequence>(); // Use this array to know which ID is associated with each // Item(name) final ArrayList<Long> dialogDeckIds = new ArrayList<Long>(); ArrayList<JSONObject> decks = mCol.getDecks().all(); Collections.sort(decks, new JSONNameComparator()); builder.setTitle(R.string.deck); for (JSONObject d : decks) { try { if (d.getInt("dyn") == 0) { dialogDeckItems.add(d.getString("name")); dialogDeckIds.add(d.getLong("id")); } } catch (JSONException e) { throw new RuntimeException(e); } } // Convert to Array String[] items = new String[dialogDeckItems.size()]; dialogDeckItems.toArray(items); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { long newId = dialogDeckIds.get(item); if (mCurrentDid != newId) { if (mAddNote) { try { // TODO: mEditorNote.setDid(newId); mEditorNote.model().put("did", newId); mCol.getModels().setChanged(); } catch (JSONException e) { throw new RuntimeException(e); } } mCurrentDid = newId; updateDeck(); } } }); dialog = builder.create(); mDeckSelectDialog = dialog; break; case DIALOG_MODEL_SELECT: ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>(); // Use this array to know which ID is associated with each // Item(name) final ArrayList<Long> dialogIds = new ArrayList<Long>(); ArrayList<JSONObject> models = mCol.getModels().all(); Collections.sort(models, new JSONNameComparator()); builder.setTitle(R.string.note_type); for (JSONObject m : models) { try { dialogItems.add(m.getString("name")); dialogIds.add(m.getLong("id")); } catch (JSONException e) { throw new RuntimeException(e); } } // Convert to Array String[] items2 = new String[dialogItems.size()]; dialogItems.toArray(items2); builder.setItems(items2, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { long oldModelId; try { oldModelId = mCol.getModels().current().getLong("id"); } catch (JSONException e) { throw new RuntimeException(e); } long newId = dialogIds.get(item); if (oldModelId != newId) { mCol.getModels().setCurrent(mCol.getModels().get(newId)); JSONObject cdeck = mCol.getDecks().current(); try { cdeck.put("mid", newId); } catch (JSONException e) { throw new RuntimeException(e); } mCol.getDecks().save(cdeck); int size = mEditFields.size(); String[] oldValues = new String[size]; for (int i = 0; i < size; i++) { oldValues[i] = mEditFields.get(i).getText().toString(); } setNote(); resetEditFields(oldValues); mTimerHandler.removeCallbacks(checkDuplicatesRunnable); duplicateCheck(false); } } }); dialog = builder.create(); break; case DIALOG_RESET_CARD: builder.setTitle(res.getString(R.string.reset_card_dialog_title)); builder.setMessage(res.getString(R.string.reset_card_dialog_message)); builder.setPositiveButton(res.getString(R.string.yes), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // for (long cardId : // mDeck.getCardsFromFactId(mEditorNote.getId())) { // mDeck.cardFromId(cardId).resetCard(); // } // mDeck.reset(); // setResult(Reviewer.RESULT_EDIT_CARD_RESET); // mCardReset = true; // Themes.showThemedToast(CardEditor.this, // getResources().getString( // R.string.reset_card_dialog_confirmation), true); } }); builder.setNegativeButton(res.getString(R.string.no), null); builder.setCancelable(true); dialog = builder.create(); break; case DIALOG_INTENT_INFORMATION: dialog = createDialogIntentInformation(builder, res); } return dialog; }
From source file:com.facebook.share.internal.OpenGraphJSONUtility.java
private static JSONArray toJSONArray(final List list, final PhotoJSONProcessor photoJSONProcessor) throws JSONException { final JSONArray result = new JSONArray(); for (Object item : list) { result.put(toJSONValue(item, photoJSONProcessor)); }//from w w w . j a v a 2 s. c o m return result; }
From source file:nl.spellenclubeindhoven.dominionshuffle.LoadSaveActivity.java
public boolean saveSlot(int number, String name, CardSelector cardSelector) { try {//www .j a va 2 s . c om boolean result = DataReader.writeStringToFile(this, String.format("slot%d.json", number), getCardSelector().toJson()); if (result == false) { return false; } } catch (JSONException ignore) { return false; } // Save slotname (if saving the selection worked) adapter.getItem(number).name = name; JSONArray jsonArray = new JSONArray(); for (int i = 0; i < adapter.getCount(); i++) { jsonArray.put(adapter.getItem(i).name); } return DataReader.writeStringToFile(this, "slots.json", jsonArray.toString()); }
From source file:com.fuse.billing.android.IabHelper.java
public String querySkuDetailsAsJsonString(String itemType, String skuArrayJsonString) throws IabException { try {// ww w . ja va 2 s . c o m JSONArray skuJsonArray = new JSONArray(skuArrayJsonString); List<String> skuList = new ArrayList<String>(); for (int i = 0; i < skuJsonArray.length(); i++) { skuList.add(skuJsonArray.getString(i)); } List<SkuDetails> skuDetailsList = new ArrayList<SkuDetails>(); int r = querySkuDetails(itemType, skuList, skuDetailsList); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error querying sku details"); } JSONArray skuDetailsJsonArray = new JSONArray(); for (SkuDetails skuDetails : skuDetailsList) { skuDetailsJsonArray.put(skuDetails.toJSON()); } return skuDetailsJsonArray.toString(); } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e); } catch (JSONException e) { throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while querying sku details.", e); } }
From source file:com.fuse.billing.android.IabHelper.java
public String queryPurchasesAsJsonString(String itemType) throws IabException { try {//from w w w . j av a2 s . co m List<Purchase> purchases = new ArrayList<Purchase>(); int r = queryPurchases(purchases, itemType); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned items)."); } // Yup, there will be some redundant (de)serialization going on here. // We don't care as it's very little data. JSONArray jsonArray = new JSONArray(); for (Purchase purchase : purchases) { jsonArray.put(purchase.toJSON()); } return jsonArray.toString(); } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e); } catch (JSONException e) { throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e); } }
From source file:org.runnerup.export.format.FacebookCourse.java
private JSONArray trail(long activityId) throws JSONException { final String cols[] = { DB.LOCATION.TYPE, DB.LOCATION.LATITUDE, DB.LOCATION.LONGITUDE, DB.LOCATION.TIME, DB.LOCATION.SPEED };//from w w w. j a va2 s. c o m Cursor c = mDB.query(DB.LOCATION.TABLE, cols, DB.LOCATION.ACTIVITY + " = " + activityId, null, null, null, null); if (c.moveToFirst()) { Location prev = null, last = null; double sumDist = 0; long sumTime = 0; double accTime = 0; final double period = 30; JSONArray arr = new JSONArray(); do { switch (c.getInt(0)) { case DB.LOCATION.TYPE_START: case DB.LOCATION.TYPE_RESUME: last = new Location("Dill"); last.setLatitude(c.getDouble(1)); last.setLongitude(c.getDouble(2)); last.setTime(c.getLong(3)); accTime = period * 1000; // always emit first point // start/resume break; case DB.LOCATION.TYPE_END: accTime = period * 1000; // always emit last point case DB.LOCATION.TYPE_GPS: case DB.LOCATION.TYPE_PAUSE: Location l = new Location("Sill"); l.setLatitude(c.getDouble(1)); l.setLongitude(c.getDouble(2)); l.setTime(c.getLong(3)); if (!c.isNull(4)) l.setSpeed(c.getFloat(4)); if (last != null) { sumDist += l.distanceTo(last); sumTime += l.getTime() - last.getTime(); accTime += l.getTime() - last.getTime(); } prev = last; last = l; } if (Math.round(accTime / 1000) >= period) { arr.put(point(prev, last, sumTime, sumDist)); accTime -= period * 1000; } } while (c.moveToNext()); c.close(); return arr; } c.close(); return null; }