List of usage examples for org.apache.commons.collections CollectionUtils subtract
public static Collection subtract(final Collection a, final Collection b)
From source file:com.dianping.lion.service.impl.ConfigReleaseServiceImpl.java
@SuppressWarnings("unchecked") @Override//from w w w .java 2 s . co m public ConfigRollbackResult rollbackSnapshotSet(ConfigSnapshotSet snapshotSet, String[] keys) { ConfigRollbackResult rollbackResult = new ConfigRollbackResult(); final int projectId = snapshotSet.getProjectId(); final int envId = snapshotSet.getEnvId(); try { List<ConfigSnapshot> configSnapshots = configReleaseDao.findConfigSnapshots(snapshotSet.getId()); List<ConfigInstanceSnapshot> configInstSnapshots = configReleaseDao .findConfigInstSnapshots(snapshotSet.getId()); List<Config> currentConfigs = configService.findConfigs(projectId); List<ConfigInstance> currentConfigInsts = configService.findInstances(projectId, envId); Map<Integer, Date> modifyTimes = configService.findModifyTime(projectId, envId); Map<String, ConfigSnapshot> configSnapshotMap = new HashMap<String, ConfigSnapshot>( configSnapshots.size()); for (ConfigSnapshot configSnapshot : configSnapshots) { configSnapshotMap.put(configSnapshot.getKey(), configSnapshot); } Map<Integer, List<ConfigInstanceSnapshot>> configInstSnapshotMap = new HashMap<Integer, List<ConfigInstanceSnapshot>>( configSnapshots.size()); for (ConfigInstanceSnapshot configInstSnapshot : configInstSnapshots) { List<ConfigInstanceSnapshot> instList = configInstSnapshotMap.get(configInstSnapshot.getConfigId()); if (instList == null) { instList = new ArrayList<ConfigInstanceSnapshot>(); configInstSnapshotMap.put(configInstSnapshot.getConfigId(), instList); } instList.add(configInstSnapshot); } Set<String> configSnapshotKeys = configSnapshotMap.keySet(); final Map<String, Config> currentConfigMap = new HashMap<String, Config>(currentConfigs.size()); for (Config currentConfig : currentConfigs) { currentConfigMap.put(currentConfig.getKey(), currentConfig); } Map<Integer, List<ConfigInstance>> currentConfigInstMap = new HashMap<Integer, List<ConfigInstance>>( currentConfigInsts.size()); for (ConfigInstance currentConfigInst : currentConfigInsts) { List<ConfigInstance> instList = currentConfigInstMap.get(currentConfigInst.getConfigId()); if (instList == null) { instList = new ArrayList<ConfigInstance>(); currentConfigInstMap.put(currentConfigInst.getConfigId(), instList); } instList.add(currentConfigInst); } Set<String> currentConfigKeys = currentConfigMap.keySet(); Set<String> notRemovedKeys = new HashSet<String>(); Set<String> selectedKeys = null; if (keys != null) { selectedKeys = new HashSet<String>(); for (String key : keys) { selectedKeys.add(key); } } //1. ???? /* Notice: * ??????????? * */ Collection<String> configNeedRemoveKeys = CollectionUtils.subtract(currentConfigKeys, configSnapshotKeys); notRemovedKeys.addAll(configNeedRemoveKeys); // for (final String configNeedRemoveKey : configNeedRemoveKeys) { // this.transactionTemplate.execute(new TransactionCallbackWithoutResult() { // @Override // protected void doInTransactionWithoutResult(TransactionStatus status) { // Config configNeedRemove = currentConfigMap.get(configNeedRemoveKey); // configService.deleteInstance(configNeedRemove.getId(), envId); // } // }); // } //2. ?????? Collection<String> intersectionKeys = CollectionUtils.intersection(currentConfigKeys, configSnapshotKeys); for (String intersectionKey : intersectionKeys) { if (selectedKeys != null && !selectedKeys.contains(intersectionKey)) continue; ConfigSnapshot configSnapshot = configSnapshotMap.get(intersectionKey); final Config currentConfig = currentConfigMap.get(intersectionKey); final List<ConfigInstanceSnapshot> snapshotInstList = configInstSnapshotMap .get(configSnapshot.getConfigId()); final List<ConfigInstance> currentInstList = currentConfigInstMap.get(currentConfig.getId()); boolean snapshotNoInst = snapshotInstList == null || snapshotInstList.isEmpty(); boolean currentNoInst = currentInstList == null || currentInstList.isEmpty(); if (snapshotNoInst == true && currentNoInst == false) { notRemovedKeys.add(intersectionKey); } else if (snapshotNoInst == false && currentNoInst == true) { //??configinstanceregister server this.transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { restoreConfigInstSnapshots(currentConfig.getId(), envId, snapshotInstList); } }); } else if (snapshotNoInst == false && currentNoInst == false) { Date modifyTime = modifyTimes.get(currentConfig.getId()); Date recordModifyTime = configSnapshot.getValueModifyTime(); if (modifyTime == null || recordModifyTime == null || !modifyTime.equals(recordModifyTime)) { boolean onlyOneSnapshotInst = snapshotInstList.size() == 1; boolean onlyOneCurrentInst = currentInstList.size() == 1; if (onlyOneSnapshotInst && onlyOneCurrentInst) { ConfigInstanceSnapshot snapshotInst = snapshotInstList.get(0); ConfigInstance currentInst = currentInstList.get(0); if (snapshotInst.getContext().equals(currentInst.getContext()) && snapshotInst.getValue().equals(currentInst.getValue())) { continue; } } this.transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { configDao.deleteInstances(currentConfig.getId(), envId); restoreConfigInstSnapshots(currentConfig.getId(), envId, snapshotInstList); } }); } } } //3. ??? Collection<String> configNeedAddKeys = CollectionUtils.subtract(configSnapshotKeys, currentConfigKeys); for (final String configNeedAddKey : configNeedAddKeys) { if (selectedKeys != null && !selectedKeys.contains(configNeedAddKey)) continue; final ConfigSnapshot configSnapshot = configSnapshotMap.get(configNeedAddKey); final List<ConfigInstanceSnapshot> snapshotInstList = configInstSnapshotMap .get(configSnapshot.getConfigId()); if (snapshotInstList != null && !snapshotInstList.isEmpty()) { this.transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { int configId = configService.createConfig(configSnapshot.toConfig()); restoreConfigInstSnapshots(configId, envId, snapshotInstList); } }); } } rollbackResult.setNotRemovedKeys(notRemovedKeys); return rollbackResult; } catch (RuntimeException e) { Project project = projectService.getProject(projectId); logger.error("rollback configs failed with[project=" + project.getName() + ", task=" + snapshotSet.getTask() + "].", e); throw e; } }
From source file:biz.netcentric.cq.tools.actool.acls.AceBeanInstallerImpl.java
@SuppressWarnings("unchecked") private List<AccessControlEntry> getModifiedAces(final JackrabbitAccessControlList oldAcl, JackrabbitAccessControlList newAcl) throws RepositoryException { final List<AccessControlEntry> oldAces = Arrays.asList(oldAcl.getAccessControlEntries()); final List<AccessControlEntry> newAces = Arrays.asList(newAcl.getAccessControlEntries()); return (List<AccessControlEntry>) CollectionUtils.subtract(newAces, oldAces); }
From source file:com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserSetupProcessor.java
protected void alignInternalAndExternalUser(Set remoteExternalUserRoles, User user) { Set<Role> jrsUserRoles = user.getRoles(); logger.info("Starting align for user: " + user.getFullName() + " with remoteExternalUserRoles at size of " + remoteExternalUserRoles.size()); Collection jrsInternalUserRoles = CollectionUtils.select(jrsUserRoles, new Predicate() { public boolean evaluate(Object input) { if (!(input instanceof Role)) { return false; }/*from w ww . j ava2s . com*/ return !((Role) input).isExternallyDefined(); } }); if (logger.isDebugEnabled()) { logger.debug("jrsInternalUserRoles: " + roleCollectionToString(jrsInternalUserRoles)); } Collection<Role> jrsInternalRolesNotInRoleMap = CollectionUtils.select(jrsInternalUserRoles, new Predicate() { public boolean evaluate(Object input) { return !getOrganizationRoleMap().containsValue(((Role) input).getRoleName()) && !getOrganizationRoleMap() .containsValue(((Role) input).getRoleName() + ROLE_SUFFIX); } }); if (logger.isDebugEnabled()) { logger.debug("jrsInternalRolesNotInRoleMap: " + roleCollectionToString(jrsInternalRolesNotInRoleMap)); } //assign default internal roles if needed Collection<Role> defaultInternalRolesToAdd = CollectionUtils .subtract(getNewDefaultInternalRoles(user.getUsername()), jrsInternalRolesNotInRoleMap); jrsInternalRolesNotInRoleMap.addAll(defaultInternalRolesToAdd); Collection<Role> newUserRoles = remoteExternalUserRoles; newUserRoles.addAll(jrsInternalRolesNotInRoleMap); if (logger.isDebugEnabled()) { logger.debug("internal and external roles to persist: " + roleCollectionToString(newUserRoles)); } persistRoles(new HashSet<Role>(newUserRoles)); user.setRoles(new HashSet<Role>(newUserRoles)); updateUserAttributes(user); getUserAuthorityService().putUser(new ExecutionContextImpl(), user); }
From source file:edu.internet2.middleware.changelogconsumer.googleapps.GoogleAppsFullSync.java
private void processMatchedGroups(boolean dryRun, Collection<ComparableGroupItem> matchedGroups) { for (ComparableGroupItem item : matchedGroups) { LOG.info("Google Apps Consumer '{}' Full Sync - examining matched group: {} ({})", new Object[] { consumerName, item.getGrouperGroup().getName(), item }); Group gooGroup = null;//from w w w .j av a 2s .co m try { gooGroup = connector.fetchGooGroup(item.getName()); } catch (IOException e) { LOG.error("Google Apps Consume '{}' Full Sync - Error fetching matched group ({}): {}", new Object[] { consumerName, item.getName(), e.getMessage() }); } boolean updated = false; if (gooGroup == null) { LOG.error( "Google Apps Consume '{}' Full Sync - Error fetching matched group ({}); it disappeared during processing.", new Object[] { consumerName, item.getName() }); } else { if (!item.getGrouperGroup().getDescription().equalsIgnoreCase(gooGroup.getDescription())) { if (!dryRun) { gooGroup.setDescription(item.getGrouperGroup().getDescription()); updated = true; } } if (!item.getGrouperGroup().getDisplayExtension().equalsIgnoreCase(gooGroup.getName())) { if (!dryRun) { gooGroup.setName(item.getGrouperGroup().getDisplayExtension()); updated = true; } } if (updated) { try { connector.updateGooGroup(item.getName(), gooGroup); } catch (IOException e) { LOG.error("Google Apps Consume '{}' Full Sync - Error updating matched group ({}): {}", new Object[] { consumerName, item.getName(), e.getMessage() }); } } //Retrieve Membership ArrayList<ComparableMemberItem> grouperMembers = new ArrayList<ComparableMemberItem>(); for (edu.internet2.middleware.grouper.Member member : item.getGrouperGroup().getMembers()) { if (member.getSubjectType() == SubjectTypeEnum.PERSON) { grouperMembers.add(new ComparableMemberItem( connector.getAddressFormatter().qualifySubjectAddress(member.getSubjectId()), member)); } } ArrayList<ComparableMemberItem> googleMembers = new ArrayList<ComparableMemberItem>(); List<Member> memberList = null; try { memberList = connector.getGooMembership(item.getName()); } catch (IOException e) { LOG.error( "Google Apps Consume '{}' Full Sync - Error fetching membership list for group({}): {}", new Object[] { consumerName, item.getName(), e.getMessage() }); } if (memberList == null) { LOG.error( "Google Apps Consume '{}' Full Sync - Error fetching membership list for group ({}); it's null", new Object[] { consumerName, item.getName() }); } else { for (Member member : memberList) { googleMembers.add(new ComparableMemberItem(member.getEmail())); } Collection<ComparableMemberItem> extraMembers = CollectionUtils.subtract(googleMembers, grouperMembers); if (!properties.shouldIgnoreExtraGoogleMembers()) { processExtraGroupMembers(item, extraMembers, dryRun); } Collection<ComparableMemberItem> missingMembers = CollectionUtils.subtract(grouperMembers, googleMembers); processMissingGroupMembers(item, missingMembers, gooGroup, dryRun); Collection<ComparableMemberItem> matchedMembers = CollectionUtils.intersection(grouperMembers, googleMembers); processMatchedGroupMembers(item, matchedMembers, dryRun); } } } }
From source file:edu.harvard.med.screensaver.ui.arch.datatable.column.TableColumnManager.java
public void setColumns(List<? extends TableColumn<R, ?>> columns) { Set<TableColumn<R, ?>> oldColumns = new HashSet<TableColumn<R, ?>>(_columns); _columns.clear();//from w w w .jav a2 s.c o m _columns.addAll(columns); _columnsSelectionTree = null; // force re-create _name2Column.clear(); for (TableColumn<R, ?> column : columns) { column.addObserver(this); if (_name2Column.containsKey(column.getName())) { throw new IllegalArgumentException("column " + column + " has non-unique name"); } _name2Column.put(column.getName(), column); } updateVisibleColumns(new ColumnVisibilityChangedEvent(CollectionUtils.subtract(columns, oldColumns), CollectionUtils.subtract(oldColumns, columns))); }
From source file:gov.nih.nci.caarray.util.CaArrayAuditLogProcessor.java
@SuppressWarnings({ "PMD.ExcessiveParameterList", "unchecked" }) private void logGroup(AuditLogRecord record, Group entity, String property, String columnName, Object oldVal, Object newVal) {/*from w w w. j a va 2 s . c o m*/ if ("groupName".equals(property)) { // there is no group.users event on insert so we'll log new users here. if (record.getType() == AuditType.INSERT) { addDetail(record, columnName, "Group " + newVal + " created", oldVal, newVal); if (entity.getUsers() != null) { for (Object u : entity.getUsers()) { String msg = "User " + ((User) u).getLoginName() + " added to group " + entity.getGroupName(); addDetail(record, columnName, msg, null, u); } } } else if (record.getType() == AuditType.UPDATE) { String msg = "Group name changed from " + oldVal + " to " + newVal; addDetail(record, columnName, msg, oldVal, newVal); } } else if ("users".equals(property)) { Collection<User> tmp = CollectionUtils.subtract((Set<User>) oldVal, (Set<User>) newVal); for (User u : tmp) { String msg = "User " + u.getLoginName() + " removed from group " + entity.getGroupName(); addDetail(record, columnName, msg, u, null); } tmp = CollectionUtils.subtract((Set<User>) newVal, (Set<User>) oldVal); for (User u : tmp) { String msg = "User " + u.getLoginName() + " added to group " + entity.getGroupName(); addDetail(record, columnName, msg, null, u); } } else { LOG.debug("ignoring property " + record.getEntityName() + "." + property); } }
From source file:net.sourceforge.fenixedu.domain.accounting.PaymentPlan.java
protected Collection<PaymentPlanRule> getNotSpecificPaymentRules() { /*// w ww . j a v a2s . c om * All payment rules could be connected do * DegreeCurricularPlanServiceAgreementTemplate, but for now are just * value types */ return CollectionUtils.subtract(PaymentPlanRuleManager.getAllPaymentPlanRules(), getSpecificPaymentPlanRules()); }
From source file:com.aurel.track.item.consInf.ConsInfBL.java
/** * Gets the difference in watchers/* w w w . j av a2 s . c o m*/ * @param oldValues * @param newValues * @param addList * @param deleteList */ private static void loadWatcherDifference(List<Integer> oldValues, List<Integer> newValues, List<Integer> addList, List<Integer> deleteList) { if ((oldValues == null || oldValues.isEmpty()) && (newValues == null || newValues.isEmpty())) { return; } if (oldValues == null) { for (Integer objectID : newValues) { addList.add(objectID); } } else { if (newValues == null) { for (Integer objectID : oldValues) { deleteList.add(objectID); } } else { Collection<Integer> toRemove = CollectionUtils.subtract(oldValues, newValues); for (Integer objectID : toRemove) { deleteList.add(objectID); } Collection<Integer> toAdd = CollectionUtils.subtract(newValues, oldValues); for (Integer objectID : toAdd) { addList.add(objectID); } } } }
From source file:com.yahoo.pulsar.broker.service.PersistentQueueE2ETest.java
@Test(enabled = false) public void testRoundRobinBatchDistribution() throws Exception { final String topicName = "persistent://prop/use/ns-abc/shared-topic5"; final String subName = "sub5"; final int numMsgs = 137; /* some random number different than default batch size of 100 */ final AtomicInteger counter1 = new AtomicInteger(0); final AtomicInteger counter2 = new AtomicInteger(0); final AtomicInteger counter3 = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(numMsgs * 3); ConsumerConfiguration conf1 = new ConsumerConfiguration(); conf1.setSubscriptionType(SubscriptionType.Shared); conf1.setReceiverQueueSize(10);//from w w w .ja va 2 s . c o m conf1.setMessageListener((consumer, msg) -> { try { counter1.incrementAndGet(); consumer.acknowledge(msg); latch.countDown(); } catch (Exception e) { fail("Should not fail"); } }); ConsumerConfiguration conf2 = new ConsumerConfiguration(); conf2.setSubscriptionType(SubscriptionType.Shared); conf2.setReceiverQueueSize(10); conf2.setMessageListener((consumer, msg) -> { try { counter2.incrementAndGet(); consumer.acknowledge(msg); latch.countDown(); } catch (Exception e) { fail("Should not fail"); } }); ConsumerConfiguration conf3 = new ConsumerConfiguration(); conf3.setSubscriptionType(SubscriptionType.Shared); conf3.setReceiverQueueSize(10); conf3.setMessageListener((consumer, msg) -> { try { counter3.incrementAndGet(); consumer.acknowledge(msg); latch.countDown(); } catch (Exception e) { fail("Should not fail"); } }); // subscribe and close, so that distribution can be checked after // all messages are published Consumer consumer1 = pulsarClient.subscribe(topicName, subName, conf1); Consumer consumer2 = pulsarClient.subscribe(topicName, subName, conf2); Consumer consumer3 = pulsarClient.subscribe(topicName, subName, conf3); List<CompletableFuture<MessageId>> futures = Lists.newArrayListWithCapacity(numMsgs); Producer producer = pulsarClient.createProducer(topicName); for (int i = 0; i < numMsgs * 3; i++) { String message = "msg-" + i; futures.add(producer.sendAsync(message.getBytes())); } FutureUtil.waitForAll(futures).get(); producer.close(); latch.await(1, TimeUnit.SECONDS); /* * total messages = 137 * 3 = 411 Each consumer has 10 permits. There will be 411 / 3*10 = 13 full distributions * i.e. each consumer will get 130 messages. In the 14th round, the balance is 411 - 130*3 = 21. Two consumers * will get another batch of 10 messages (Total: 140) and the 3rd one will get the last one (Total: 131) */ assertTrue(CollectionUtils.subtract(Lists.newArrayList(140, 140, 131), Lists.newArrayList(counter1.get(), counter2.get(), counter3.get())).isEmpty()); consumer1.close(); consumer2.close(); consumer3.close(); admin.persistentTopics().delete(topicName); }
From source file:net.sourceforge.fenixedu.domain.alumni.AlumniReportFile.java
public static List<AlumniReportFile> readUndoneJobs() { return new ArrayList(CollectionUtils .subtract(ExecutionYear.readCurrentExecutionYear().getAlumniReportFilesSet(), readDoneJobs())); }