Java Code Examples for org.json.JSONArray#remove()

The following examples show how to use org.json.JSONArray#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BookmarkManager.java    From webTube with GNU General Public License v3.0 6 votes vote down vote up
public void removeBookmark(String title) {
    String result = sp.getString("bookmarks", "[]");
    try {
        JSONArray bookmarksArray = new JSONArray(result);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            bookmarksArray.remove(bookmarkTitles.indexOf(title));
        } else {
            final List<JSONObject> objs = asList(bookmarksArray);
            objs.remove(bookmarkTitles.indexOf(title));
            final JSONArray out = new JSONArray();
            for (final JSONObject obj : objs) {
                out.put(obj);
            }
            bookmarksArray = out;
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("bookmarks", bookmarksArray.toString());
        editor.apply();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    initializeBookmarks(navigationView);
}
 
Example 2
Source File: GetCertificatedDatasets.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void synchronizeDatasets(List<IDataSet> spagobiDs, JSONArray ckanDs) throws JSONException {
	logger.debug("Synchronize resources...");
	long start = System.currentTimeMillis();
	Iterator<IDataSet> iterator = spagobiDs.iterator();
	while (iterator.hasNext()) {
		IDataSet ds = iterator.next();
		String config = JSONUtils.escapeJsonString(ds.getConfiguration());
		JSONObject jsonConf = ObjectUtils.toJSONObject(config);
		for (int i = 0; i < ckanDs.length(); i++) {
			if (jsonConf.getString("ckanId").equals(ckanDs.getJSONObject(i).getJSONObject("configuration").getString("ckanId"))) {
				ckanDs.remove(i);
				break;
			}
		}
	}
	logger.debug("Resources synchronized in " + (System.currentTimeMillis() - start) + "ms.");
}
 
Example 3
Source File: AuthorizationService.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Removes the right for the given user to put, post, get, or delete the given URI.
 * @param userId The user name
 * @param uri The URI to remove access to
 * @throws CoreException If an error occurred persisting user rights.
 */
public static void removeUserRight(String userId, String uri) throws CoreException {
	try {
		@SuppressWarnings("unused")
		Activator r = Activator.getDefault();
		UserInfo user = OrionConfiguration.getMetaStore().readUser(userId);
		JSONArray userRightArray = AuthorizationReader.getAuthorizationData(user);
		for (int i = 0; i < userRightArray.length(); i++) {
			if (uri.equals(((JSONObject) userRightArray.get(i)).get(ProtocolConstants.KEY_USER_RIGHT_URI)))
				userRightArray.remove(i);
		}
		AuthorizationReader.saveRights(user, userRightArray);
	} catch (Exception e) {
		throw new CoreException(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error persisting user rights", e));
	}
}
 
Example 4
Source File: JSONHelper.java    From springreplugin with Apache License 2.0 5 votes vote down vote up
/**
 * 根据Android API的版本,来决定是使用Remove方法(API 19),还是通过反射来做(低于API 19)
 */
public static void remove(JSONArray jsonArray, int index) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        jsonArray.remove(index);
    } else {
        removeBelowAPI19(jsonArray, index);
    }
}
 
Example 5
Source File: JSONArrayTest.java    From JSON-Java-unit-test with Apache License 2.0 5 votes vote down vote up
/**
 * Exercise the JSONArray.remove(index) method 
 * and confirm the resulting JSONArray.
 */
@Test
public void remove() {
    String arrayStr1 = 
        "["+
            "1"+
        "]";
    JSONArray jsonArray = new JSONArray(arrayStr1);
    jsonArray.remove(0);
    assertTrue("array should be empty", null == jsonArray.remove(5));
    assertTrue("jsonArray should be empty", jsonArray.isEmpty());
}
 
Example 6
Source File: HomeActivityDelegate.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
private void reassignDroppedIcon() {
    if(startDragIndex == endDragIndex) return;

    try {
        SharedPreferences pref = U.getSharedPreferences(this);
        JSONArray jsonIcons = new JSONArray(pref.getString(PREF_DESKTOP_ICONS, "[]"));
        int iconToRemove = -1;

        DesktopIconInfo oldInfo = getDesktopIconInfo(startDragIndex);
        DesktopIconInfo newInfo = getDesktopIconInfo(endDragIndex);

        for(int i = 0; i < jsonIcons.length(); i++) {
            DesktopIconInfo info = DesktopIconInfo.fromJson(jsonIcons.getJSONObject(i));
            if(info != null && info.column == oldInfo.column && info.row == oldInfo.row) {
                newInfo.entry = info.entry;
                iconToRemove = i;
                break;
            }
        }

        if(iconToRemove > -1) {
            jsonIcons.remove(iconToRemove);
            jsonIcons.put(newInfo.toJson(this));

            pref.edit().putString(PREF_DESKTOP_ICONS, jsonIcons.toString()).apply();
        }
    } catch (JSONException e) { /* Gracefully fail */ }
}
 
Example 7
Source File: RascalMetricsTest.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private boolean compareJSONArrays(JSONArray a1, JSONArray a2) {
	//1. Check number of objects in array
	if(a1.length() != a2.length()) {
		System.err.println("[ERROR] The dump file has " + a1.length() 
		+ " objects while the new DB collection has " + a2.length() + " objects.");
		return false;
	}

	//2. Check that objects have the same value
	for(int i = 0; i < a1.length(); i++) {
		try {
			boolean found = false;
			Object obj = a1.get(i);
			
			if(obj instanceof JSONObject) {
				JSONObject o1 = a1.getJSONObject(i);

				for(int j = 0; j < a2.length(); j++) {
					JSONObject o2 = a2.getJSONObject(j);
					if(compareJSONObjects(o1,o2)) {
						found = true;
						// So we don't iterate multiple times over the same object.
						a2.remove(j);
						break;
					}
				}
				if(!found) {
					return false;
				}
			}
		}
		catch(JSONException e) {
			System.err.println("We got an error when getting a JSONObject: " + a1);
		}
	}

	//3. Otherwise, everything is fine!
	return true;
}
 
Example 8
Source File: ExcelExporter.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONArray filterDataStoreColumns(JSONArray columns) {
	try {
		for (int i = 0; i < columns.length(); i++) {
			String element = columns.getString(i);
			if (element != null && element.equals("recNo")) {
				columns.remove(i);
				break;
			}
		}
	} catch (JSONException e) {
		logger.error("Can not filter Columns Array");
	}
	return columns;
}
 
Example 9
Source File: QueryJSONSerializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONObject extractCalendar(JSONArray record, JSONArray filter, IDataSource dataSource) throws SerializationException {

		String calendarFieldUniqueName = getCalendarFieldUniqueName(dataSource);

		JSONObject ret = new JSONObject();
		try {
			if (record != null && record.length() > 0 && filter != null && filter.length() > 0) {
				for (int i = 0; i < record.length(); i++) {
					JSONObject tmpRec = record.getJSONObject(i);
					if (tmpRec.getString(QuerySerializationConstants.ID).equals(calendarFieldUniqueName)) {
						record.remove(i);
						ret.put(QuerySerializationConstants.FIELDS, tmpRec);
						break;
					}
				}

				for (int i = 0; i < filter.length(); i++) {
					JSONObject tmpFilt = filter.getJSONObject(i);
					if (tmpFilt.getString(QuerySerializationConstants.FILTER_ID).equals(QuerySerializationConstants.CALENDAR_FILTER)) {
						filter.remove(i);
						ret.put(QuerySerializationConstants.FILTERS, tmpFilt);
						break;
					}
				}

			}
		} catch (Throwable t) {
			throw new SerializationException("An error occurred while serializing field ", t);
		}
		return ret;
	}
 
Example 10
Source File: TestUtils.java    From ambry with Apache License 2.0 5 votes vote down vote up
void removeReplicaFromPartition(Replica replicaToRemove) {
  version += 1;
  String partitionName = replicaToRemove.getPartitionId().toPathString();
  int index;
  for (index = 0; index < jsonPartitions.length(); ++index) {
    String partitionId = String.valueOf(((JSONObject) jsonPartitions.get(index)).get("id"));
    if (partitionId.equals(partitionName)) {
      break;
    }
  }
  JSONObject jsonPartition = (JSONObject) jsonPartitions.get(index);
  JSONArray jsonReplicas = (JSONArray) jsonPartition.get("replicas");
  int replicaIdx;
  DataNode targetNode = (DataNode) replicaToRemove.getDataNodeId();
  for (replicaIdx = 0; replicaIdx < jsonReplicas.length(); ++replicaIdx) {
    JSONObject jsonReplica = (JSONObject) jsonReplicas.get(replicaIdx);
    String hostname = (String) jsonReplica.get("hostname");
    int port = (int) jsonReplica.get("port");
    if (hostname.equals(targetNode.getHostname()) && port == targetNode.getPort()) {
      break;
    }
  }
  // remove given replica from replicas
  jsonReplicas.remove(replicaIdx);
  jsonPartition.put("replicas", jsonReplicas);
  jsonPartitions.put(index, jsonPartition);
  JSONObject jsonPartitionLayout =
      getJsonPartitionLayout(testHardwareLayout.getHardwareLayout().getClusterName(), version, partitionCount,
          jsonPartitions);
  this.partitionLayout =
      new PartitionLayout(testHardwareLayout.getHardwareLayout(), jsonPartitionLayout, clusterMapConfig);
}
 
Example 11
Source File: FavouriteHistoryStage.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private JSONObject removeAndGetTest(String section) {
    JSONArray history = TestRunnerHistory.getInstance().getHistory(section);
    for (int i = 0; i < history.length(); i++) {
        JSONObject test = history.getJSONObject(i);
        JSONObject selectedItem = historyView.getSelectionModel().getSelectedItem();
        if (test.getString("name").equals(selectedItem.getString("name"))) {
            historyView.getItems().remove(historyView.getSelectionModel().getSelectedItem());
            history.remove(i);
            return test;
        }
    }
    return null;
}
 
Example 12
Source File: UnSavedHistoryStage.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private JSONObject removeAndGetTest(String section) {
    JSONArray history = TestRunnerHistory.getInstance().getHistory(section);
    for (int i = 0; i < history.length(); i++) {
        JSONObject test = history.getJSONObject(i);
        JSONObject selectedItem = historyView.getSelectionModel().getSelectedItem();
        if (test.getString("name").equals(selectedItem.getString("name"))) {
            historyView.getItems().remove(historyView.getSelectionModel().getSelectedItem());
            history.remove(i);
            return test;
        }
    }
    return null;
}
 
Example 13
Source File: TestPropertiesInfo.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void removeTestIfPresent(JSONObject issue) {
    JSONArray tests = issue.getJSONArray("tests");
    for (int i = 0; i < tests.length(); i++) {
        JSONObject testObj = tests.getJSONObject(i);
        String name = testObj.getString("path");
        if (name.equals(path)) {
            tests.remove(i);
        }
    }
}
 
Example 14
Source File: Utilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static void removeFormFromSection(String formName, JSONObject section) throws JSONException {
    JSONArray jsonArray = section.getJSONArray(ATTR_FORMS);
    if (jsonArray != null && jsonArray.length() > 0) {
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (jsonObject.has(ATTR_FORMNAME)) {
                String tmpFormName = jsonObject.getString(ATTR_FORMNAME);
                if (tmpFormName.equals(formName)) {
                    jsonArray.remove(i);
                    return;
                }
            }
        }
    }
}
 
Example 15
Source File: CacheConstants.java    From VideoOS-Android-SDK with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 保存最近使用的小程序的ID
 *
 * @param context
 * @param id
 */
public static void putVisionProgramId(Context context, String fileName, @NonNull String id) {

    String data = VenvyPreferenceHelper.getString(context, fileName, RECENT_MINI_APP_ID, "[]");
    try {
        JSONArray array = new JSONArray(data);
        // 判断数据是否之前存在
        boolean isContains = false;
        for (int i = 0, len = array.length(); i < len; i++) {
            isContains = ((String) array.opt(i)).equals(id);
            if (isContains) {
                array.remove(i);
                array.put(id);
                break;
            }
        }
        if (!isContains) {
            // id有最大值限制,超过限制将最早缓存的remove
            if (array.length() >= CACHE_IDS_MAX) {
                array.remove(0);
            }
            array.put(id);
        }

        VenvyPreferenceHelper.putString(context, fileName, RECENT_MINI_APP_ID, array.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: UtilTest.java    From prebid-mobile-android with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetObjectWithoutEmptyValues() throws JSONException {

    //Test 1
    JSONObject node1111 = new JSONObject();

    JSONObject node111 = new JSONObject();
    node111.put("key111", node1111);

    JSONObject node11 = new JSONObject();
    node11.put("key11", node111);

    JSONObject node1 = new JSONObject();
    node1.put("key1", node11);

    node1.put("emptyObject", "");
    List<String> array = new ArrayList<>();
    array.add("");
    node1.put("emptyArray", new JSONArray(array));

    JSONObject result1 = Util.getObjectWithoutEmptyValues(node1);

    Assert.assertNull(result1);

    //Test 2
    node1111.put("key1111", "value1111");
    JSONObject result2 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertEquals("{\"key1\":{\"key11\":{\"key111\":{\"key1111\":\"value1111\"}}}}", result2.toString());

    //Test 3
    node1111.remove("key1111");
    JSONObject node121 = new JSONObject();
    node121.put("key121", "value121");
    node11.put("key12", node121);

    JSONObject result3 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertEquals("{\"key1\":{\"key12\":{\"key121\":\"value121\"}}}", result3.toString());

    //Test 4
    node11.remove("key12");
    JSONArray node21 = new JSONArray();
    node1.put("key2", node21);
    JSONObject result4 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertNull(result4);

    //Test5
    node21.put("value21");
    JSONObject result5 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertEquals("{\"key2\":[\"value21\"]}", result5.toString());

    //Test6
    node21.remove(0);
    JSONObject node211 = new JSONObject();
    node21.put(node211);
    JSONObject result6 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertNull(result6);

    //Test7
    node211.put("key211", "value211");
    JSONObject result7 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertEquals("{\"key2\":[{\"key211\":\"value211\"}]}", result7.toString());

    //Test8
    node21.remove(0);
    JSONArray node212 = new JSONArray();
    node21.put(node212);
    JSONObject result8 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertNull(result8);

    //Test9
    JSONArray node31 = new JSONArray();
    node1.put("key3", node31);
    JSONObject node311 = new JSONObject();
    node31.put(node311);
    JSONObject node312 = new JSONObject();
    node312.put("key312", "value312");
    node31.put(node312);
    JSONObject result9 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertEquals("{\"key3\":[{\"key312\":\"value312\"}]}", result9.toString());

    //Test10
    JSONArray node313 = new JSONArray();
    JSONObject node3131 = new JSONObject();
    node3131.put("key3131", "value3131");
    node313.put(node3131);
    JSONObject node3132 = new JSONObject();
    node313.put(node3132);
    node31.put(node313);
    JSONObject result10 = Util.getObjectWithoutEmptyValues(node1);
    Assert.assertEquals("{\"key3\":[{\"key312\":\"value312\"},[{\"key3131\":\"value3131\"}]]}", result10.toString());
}
 
Example 17
Source File: GitLogTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testLogFile() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);

	String projectName = getMethodName().concat("Project");
	JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());

	JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
	String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

	// modify
	JSONObject testTxt = getChild(project, "test.txt");
	modifyFile(testTxt, "test.txt change");
	addFile(testTxt);

	// commit1
	WebRequest request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
	WebResponse response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	// modify again
	JSONObject folder = getChild(project, "folder");
	JSONObject folderTxt = getChild(folder, "folder.txt");
	modifyFile(folderTxt, "folder.txt change");
	addFile(folderTxt);

	// commit2
	request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
	response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	// get log for file
	JSONObject log = logObject(testTxt.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_HEAD));

	String repositoryPath = log.getString(GitConstants.KEY_REPOSITORY_PATH);
	assertEquals("test.txt", repositoryPath);

	JSONArray commitsArray = log.getJSONArray(ProtocolConstants.KEY_CHILDREN);

	assertEquals(2, commitsArray.length());

	JSONObject commit = commitsArray.getJSONObject(0);
	assertEquals("commit1", commit.getString(GitConstants.KEY_COMMIT_MESSAGE));

	// check commit content location
	assertEquals("test.txt change", getCommitContent(commit));

	// check commit diff location
	String[] parts = GitDiffTest.getDiff(commit.getString(GitConstants.KEY_DIFF));

	assertEquals("", parts[1]); // no diff between the commit and working tree

	// check commit location
	JSONObject jsonObject = logObject(commit.getString(ProtocolConstants.KEY_LOCATION));

	assertEquals(log.getString(GitConstants.KEY_CLONE), jsonObject.getString(GitConstants.KEY_CLONE));
	assertEquals(log.getString(GitConstants.KEY_REPOSITORY_PATH), jsonObject.getString(GitConstants.KEY_REPOSITORY_PATH));
	assertNull(jsonObject.optString(GitConstants.KEY_LOG_TO_REF, null));
	assertNull(jsonObject.optString(GitConstants.KEY_LOG_FROM_REF, null));
	JSONArray a1 = jsonObject.getJSONArray(ProtocolConstants.KEY_CHILDREN);
	JSONArray a2 = log.getJSONArray(ProtocolConstants.KEY_CHILDREN);
	assertThat(a1, isJSONArrayEqual(a2));

	// check second commit		
	commit = commitsArray.getJSONObject(1);
	assertEquals("Initial commit", commit.getString(GitConstants.KEY_COMMIT_MESSAGE));
	// check commit content location
	assertEquals("test", getCommitContent(commit));

	// check commit diff location
	parts = GitDiffTest.getDiff(commit.getString(GitConstants.KEY_DIFF));

	StringBuilder sb = new StringBuilder();
	sb.append("diff --git a/test.txt b/test.txt").append("\n");
	sb.append("index 30d74d2..3146ed5 100644").append("\n");
	sb.append("--- a/test.txt").append("\n");
	sb.append("+++ b/test.txt").append("\n");
	sb.append("@@ -1 +1 @@").append("\n");
	sb.append("-test").append("\n");
	sb.append("\\ No newline at end of file").append("\n");
	sb.append("+test.txt change").append("\n");
	sb.append("\\ No newline at end of file").append("\n");
	assertEquals(sb.toString(), parts[1]);

	// check commit location
	jsonObject = logObject(commit.getString(ProtocolConstants.KEY_LOCATION));
	JSONObject log2 = log;
	JSONArray commitsArray2 = log2.getJSONArray(ProtocolConstants.KEY_CHILDREN);
	commitsArray2.remove(0);
	assertEquals(log.getString(GitConstants.KEY_CLONE), jsonObject.getString(GitConstants.KEY_CLONE));
	assertEquals(log.getString(GitConstants.KEY_REPOSITORY_PATH), jsonObject.getString(GitConstants.KEY_REPOSITORY_PATH));
	assertNull(jsonObject.optString(GitConstants.KEY_LOG_TO_REF, null));
	assertNull(jsonObject.optString(GitConstants.KEY_LOG_FROM_REF, null));
	assertThat(commitsArray2, isJSONArrayEqual(log.getJSONArray(ProtocolConstants.KEY_CHILDREN)));
}
 
Example 18
Source File: TestRunnerHistory.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
private void removeExceeding() {
    JSONArray his = getHistory("unsaved");
    if (his.length() > Preferences.instance().getValue("testrunner", "remember-count", 10)) {
        his.remove(0);
    }
}
 
Example 19
Source File: KeggParser.java    From act with GNU General Public License v3.0 4 votes vote down vote up
private static void jsonArrayRemove(JSONArray a, Object toRemove) {
  for (int i = 0; i< a.length(); i++) {
    if (a.get(i).equals(toRemove))
      a.remove(i);
  }
}
 
Example 20
Source File: TagsManager.java    From geopaparazzi with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Utility method to get the formitems of a form object.
 * <p>
 * <p>Note that the entering json object has to be one
 * object of the main array, not THE main array itself,
 * i.e. a choice was already done.
 *
 * @param formObj the single object.
 * @return the array of items of the contained form or <code>null</code> if
 * no form is contained.
 * @throws JSONException if something goes wrong.
 */
public static JSONArray getFormItems(JSONObject formObj) throws JSONException {
    if (formObj.has(TAG_FORMITEMS)) {
        JSONArray formItemsArray = formObj.getJSONArray(TAG_FORMITEMS);
        int emptyIndex = -1;
        while ((emptyIndex = hasEmpty(formItemsArray)) >= 0) {
            formItemsArray.remove(emptyIndex);
        }
        return formItemsArray;
    }
    return new JSONArray();
}