Example usage for org.apache.commons.collections CollectionUtils subtract

List of usage examples for org.apache.commons.collections CollectionUtils subtract

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils subtract.

Prototype

public static Collection subtract(final Collection a, final Collection b) 

Source Link

Document

Returns a new Collection containing a - b.

Usage

From source file:org.pentaho.platform.engine.security.userroledao.hibernate.HibernateUserRoleDao.java

/**
 * This method is more complex because it must manage this role's users manually.
 *//*from ww w.  j a  v a  2  s  . com*/
@SuppressWarnings("unchecked")
public void updateRole(IPentahoRole roleToUpdate) throws NotFoundException, UncategorizedUserRoleDaoException {
    Assert.notNull(roleToUpdate, Messages.getString("HibernateUserRoleDao.ERROR_0005_ROLE_CANNOT_BE_NULL")); //$NON-NLS-1$
    Assert.hasLength(roleToUpdate.getName(),
            Messages.getString("HibernateUserRoleDao.ERROR_0006_ROLE_NAME_CANNOT_BE_BLANK")); //$NON-NLS-1$

    IPentahoRole originalRole = getRole(roleToUpdate.getName());

    if (originalRole == null) {
        throw new NotFoundException(roleToUpdate.getName());
    }

    // make a copy of originalRole's users since the merge call below will change the users
    Set<IPentahoUser> originalRoleUsers = new HashSet<IPentahoUser>(originalRole.getUsers());

    try {
        getHibernateTemplate().update(getHibernateTemplate().merge(roleToUpdate));
    } catch (DataAccessException e) {
        throw new UncategorizedUserRoleDaoException(
                Messages.getString("HibernateUserRoleDao.ERROR_0004_DATA_ACCESS_EXCEPTION"), e); //$NON-NLS-1$
    }

    // manually manage users set

    // use relative complement (aka set-theoretic difference, aka subtraction) to get the users to add and users to 
    // remove
    Set<IPentahoUser> usersToAdd = new HashSet<IPentahoUser>(
            CollectionUtils.subtract(roleToUpdate.getUsers(), originalRoleUsers));
    Set<IPentahoUser> usersToRemove = new HashSet<IPentahoUser>(
            CollectionUtils.subtract(originalRoleUsers, roleToUpdate.getUsers()));

    for (IPentahoUser user : usersToAdd) {
        addUser(roleToUpdate, user.getUsername());
    }

    for (IPentahoUser user : usersToRemove) {
        removeUser(roleToUpdate, user.getUsername());
    }

}

From source file:org.pentaho.pms.ui.concept.editor.AvailSecurityOwnersTableViewer.java

protected List<SecurityOwner> findUnused(List<SecurityOwner> usedOwners, List<String> users,
        List<String> roles) {
    List<SecurityOwner> allOwners = new ArrayList<SecurityOwner>();
    // make a single list with SecurityOwner objects
    for (String user : users) {
        allOwners.add(new SecurityOwner(SecurityOwner.OWNER_TYPE_USER, user));
    }//from   w w w .  jav  a 2 s  . c  om
    for (String role : roles) {
        allOwners.add(new SecurityOwner(SecurityOwner.OWNER_TYPE_ROLE, role));
    }
    return new ArrayList<SecurityOwner>(CollectionUtils.subtract(allOwners, usedOwners));
}

From source file:org.pentaho.pms.ui.concept.editor.PropertyGroupHelper.java

/**
 * Gets a subset of all properties belonging to given group, eliminating properties currently present in the given
 * concept.//w  w  w . j  a va 2s  .c o m
 * @param group the group to search
 * @param conceptModel the concept to search
 * @return a set of property IDs
 */
@SuppressWarnings("unchecked")
public static List<String> getUnusedPropertiesForGroup(final String group, final IConceptModel conceptModel) {
    if (GROUP_CUSTOM.equals(group)) {
        return Collections.<String>emptyList();
    }
    final List allProperties = getPropertiesForGroup(group);
    final List usedProperties = getUsedPropertiesForGroup(group, conceptModel);
    return new ArrayList<String>(CollectionUtils.subtract(allProperties, usedProperties));
}

From source file:org.sipfoundry.sipxconfig.site.dialplan.AttendantMenuPanel.java

public List<Validator> getDialPadSelectionValidators() {
    String[] regexMetaChars = { DialPad.STAR.getName() };

    List<Validator> validators = new ArrayList<Validator>(2);
    validators.add(new Required());

    String dialPadRegex = StringUtils.EMPTY;
    Collection<DialPad> freeDialPads = CollectionUtils.subtract(Arrays.asList(DialPad.KEYS),
            getMenuItems().getCurrentMenuDialPads());

    for (DialPad freeDialPad : freeDialPads) {
        String dialPadNumber = freeDialPad.getName();
        if (Arrays.asList(regexMetaChars).contains(dialPadNumber)) {
            dialPadNumber = "\\" + dialPadNumber;
        }//  w  ww. j  a  va  2 s  .c  om

        dialPadRegex += dialPadNumber;
    }

    Pattern pattern = new Pattern();
    if (dialPadRegex.isEmpty()) {
        pattern.setPattern("\\[\\]");
    } else {
        pattern.setPattern("[" + dialPadRegex + "]");
    }
    pattern.setMessage(getMessages().format(KEY_IN_USE_ERROR, ""));
    validators.add(pattern);

    return validators;
}

From source file:org.sonar.server.component.ComponentService.java

public Collection<String> componentUuids(DbSession session, @Nullable Collection<String> componentKeys,
        boolean ignoreMissingComponents) {
    Collection<String> componentUuids = newArrayList();
    if (componentKeys != null && !componentKeys.isEmpty()) {
        List<ComponentDto> components = dbClient.componentDao().getByKeys(session, componentKeys);

        if (!ignoreMissingComponents && components.size() < componentKeys.size()) {
            Collection<String> foundKeys = Collections2.transform(components,
                    new Function<ComponentDto, String>() {
                        @Override
                        public String apply(ComponentDto component) {
                            return component.key();
                        }/*from w ww  .  j  a  v a  2  s . co  m*/
                    });
            throw new NotFoundException("The following component keys do not match any component:\n"
                    + Joiner.on('\n').join(CollectionUtils.subtract(componentKeys, foundKeys)));
        }

        for (ComponentDto component : components) {
            componentUuids.add(component.uuid());
        }
    }
    return componentUuids;
}

From source file:org.sonar.server.issue.RemoveTagsAction.java

@Override
@SuppressWarnings("unchecked")
protected Collection<String> getTagsToSet(Context context, Collection<String> tagsFromParams) {
    return CollectionUtils.subtract(context.issue().tags(), tagsFromParams);
}

From source file:org.squashtest.tm.service.internal.customfield.PrivateCustomFieldValueServiceImpl.java

@SuppressWarnings("unchecked")
@Override//  ww  w. j av  a  2 s.  c  o m
public void createAllCustomFieldValues(Collection<? extends BoundEntity> entities, Project p) {

    if (entities.isEmpty()) {
        return;
    }

    BoundEntity firstEntity = entities.iterator().next();

    Project project = p;
    if (p == null) {
        project = firstEntity.getProject();
    }

    List<CustomFieldBinding> bindings = optimizedFindCustomField(firstEntity, project);

    /* **************************************************************************************************
     * [Issue 3808]
     *
     * It seems that after #2061 (revision 9540a9a08c49) a defensive block of code was added in order to
     * prevent the creation of a custom field if it exists already for the target entity.
     *
     * I don't know really why it was needed but it killed performances, so I'm rewriting it
     * and hope it makes it faster. Best should be to get rid of it completely. Its inefficient and ugly.
     ************************************************************************************************* */

    MultiValueMap bindingPerEntities = findEffectiveBindings(entities);

    /* **** /[Issue 3808]  ************/

    // main loop
    for (BoundEntity entity : entities) {

        Collection<CustomFieldBinding> toBeBound = bindings;

        Collection<CustomFieldBinding> effectiveBindings = bindingPerEntities
                .getCollection(entity.getBoundEntityId());

        if (effectiveBindings != null) {
            toBeBound = CollectionUtils.subtract(bindings, effectiveBindings);
        }

        for (CustomFieldBinding toBind : toBeBound) {
            CustomFieldValue value = toBind.createNewValue();
            value.setBoundEntity(entity);
            customFieldValueDao.save(value);

        }

        if (BindableEntity.TEST_CASE == entity.getBoundEntityType()) {
            indexationService.reindexTestCase(entity.getBoundEntityId());
        }
        if (BindableEntity.REQUIREMENT_VERSION == entity.getBoundEntityType()) {
            indexationService.reindexRequirementVersion(entity.getBoundEntityId());
        }
    }

}

From source file:org.sventon.appl.RepositoryConfigurations.java

/**
 * Compare two configurations using the names of the repository configurations.
 *
 * @param configsToCompare New configurations to compare with.
 * @return A {@link org.sventon.appl.RepositoryConfigurations.ConfigsDiff} instance describing what
 *         needs to be added and removed to this configs instance to get to the {@code configsToCompare} instance.
 *//*from   w  w w .j a v a  2s .  c om*/
public ConfigsDiff diffByRepositoryName(RepositoryConfigurations configsToCompare) {

    ConfigsDiff diff = new ConfigsDiff();

    Set<RepositoryName> oldRepositoryNames = getAllConfigurationNames();
    Set<RepositoryName> newRepositoryNames = configsToCompare.getAllConfigurationNames();

    @SuppressWarnings({ "unchecked" })
    Collection<RepositoryName> removed = CollectionUtils.subtract(oldRepositoryNames, newRepositoryNames);
    @SuppressWarnings({ "unchecked" })
    Collection<RepositoryName> added = CollectionUtils.subtract(newRepositoryNames, oldRepositoryNames);

    for (RepositoryName repositoryName : added) {
        diff.added.add(configsToCompare.getConfiguration(repositoryName));
    }

    for (RepositoryName repositoryName : removed) {
        diff.removed.add(getConfiguration(repositoryName));
    }

    return diff;

}

From source file:services.plugins.subversion.subv1.SubversionPluginRunner.java

/**
 * Check if the update of the system role may have an impact on the
 * subversion LDAP configuration./*from w ww .j  a  va 2  s.c o  m*/
 * 
 * @param eventMessage
 *            the event message
 */
private void checkImpactOfSystemLevelRoleUpdate(EventMessage eventMessage) {
    // A role was updated, check if this role was associated with
    // the permission SCM_DEVELOPER_PERMISSION
    // or SCM_ADMIN
    Long changedRole = eventMessage.getInternalId();
    List<String> previousListOfPermissions = ((SystemLevelRoleTypeEventMessage.PayLoad) eventMessage
            .getPayload()).getPreviousPermissionNames();

    // Check if the permission is new or removed
    List<String> currentPermissions = new ArrayList<String>();
    SystemLevelRoleType roleType = SystemLevelRoleType.getActiveRoleFromId(changedRole);
    if (roleType.systemPermissions != null) {
        for (SystemPermission systemPermission : roleType.systemPermissions) {
            currentPermissions.add(systemPermission.name);
        }
    }

    Collection<?> changedPermissions = CollectionUtils.disjunction(previousListOfPermissions,
            currentPermissions);
    if (changedPermissions.contains(IMafConstants.SCM_DEVELOPER_PERMISSION)
            || changedPermissions.contains(IMafConstants.SCM_ADMIN_PERMISSION)) {
        List<Principal> principals = Principal.getPrincipalsWithSystemLevelRoleId(changedRole);

        // Part of removed permissions
        Collection<?> removedPermissions = CollectionUtils.subtract(previousListOfPermissions,
                currentPermissions);
        if (removedPermissions.contains(IMafConstants.SCM_DEVELOPER_PERMISSION)) {
            removeUsersFromLdapGroupFollowingRoleUpdate(principals, getDeveloperLdapGroup());
        }
        if (removedPermissions.contains(IMafConstants.SCM_ADMIN_PERMISSION)) {
            removeUsersFromLdapGroupFollowingRoleUpdate(principals, getDeliveryManagerLdapGroup());
        }

        // Part of added permission
        Collection<?> addedPermissions = CollectionUtils.subtract(currentPermissions,
                previousListOfPermissions);
        if (addedPermissions.contains(IMafConstants.SCM_DEVELOPER_PERMISSION)) {
            addUsersToLdapGroupFollowingRoleUpdate(principals, getDeveloperLdapGroup());
        }
        if (addedPermissions.contains(IMafConstants.SCM_ADMIN_PERMISSION)) {
            addUsersToLdapGroupFollowingRoleUpdate(principals, getDeliveryManagerLdapGroup());
        }
    }
}

From source file:ubic.gemma.core.loader.expression.AffyPowerToolsProbesetSummarize.java

/**
 * For either 3' or Exon arrays./*www .j  av a 2  s  . c  o m*/
 *
 * @param ee ee
 * @param aptOutputFileToRead file
 * @param targetPlatform (thawed) deal with data from this platform (call multiple times if there is more than one
 *        platform)
 * @param originalPlatform can be the same as the targetPlatform. But we specify this in case there is more than one
 *        original platform, so we're not trying to match up bioassays that are not relevant.
 * @param bioAssaysToUse that we're dealing with (could be a subset of a multi-platform experiment)
 * @return raw data vectors
 * @throws IOException io problem
 * @throws FileNotFoundException file not found
 */
Collection<RawExpressionDataVector> processData(ExpressionExperiment ee, String aptOutputFileToRead,
        ArrayDesign targetPlatform, ArrayDesign originalPlatform, Collection<BioAssay> bioAssaysToUse)
        throws IOException {

    this.checkFileReadable(aptOutputFileToRead);

    AffyPowerToolsProbesetSummarize.log.info("Parsing " + aptOutputFileToRead);

    try (InputStream is = new FileInputStream(aptOutputFileToRead)) {
        DoubleMatrix<String, String> matrix = this.parse(is);

        if (matrix.rows() == 0) {
            throw new IllegalStateException("Matrix from APT had no rows");
        }
        if (matrix.columns() == 0) {
            throw new IllegalStateException("Matrix from APT had no columns");
        }

        if (bioAssaysToUse.isEmpty()) {
            throw new IllegalStateException("No bioassays were on the platform: " + originalPlatform);
        }

        // this might just be confusing.
        //            if ( ee.getBioAssays().size() > bioAssaysToUse.size() ) {
        //                AffyPowerToolsProbesetSummarize.log
        //                        .info( "Using " + bioAssaysToUse.size() + "/" + ee.getBioAssays().size() + " bioassays (those on "
        //                                + originalPlatform.getShortName() + ")" );
        //            }

        if (matrix.columns() < bioAssaysToUse.size()) {
            // having > is okay, there can be extra.
            throw new IllegalStateException("Matrix from APT had the wrong number of colummns: expected "
                    + bioAssaysToUse.size() + ", got " + matrix.columns());
        }

        AffyPowerToolsProbesetSummarize.log.info("Read " + matrix.rows() + " x " + matrix.columns()
                + ", matching with " + bioAssaysToUse.size() + " samples on " + originalPlatform);

        BioAssayDimension bad = BioAssayDimension.Factory.newInstance();
        bad.setName("For " + ee.getShortName() + " on " + targetPlatform);
        bad.setDescription("Generated from output of apt-probeset-summarize");

        /*
         * Add them ... note we haven't switched platforms yet (and might not do that)
         */

        // this is to help us match results to bioassays
        Map<String, BioAssay> bmap = new HashMap<>();
        for (BioAssay bioAssay : bioAssaysToUse) {
            if (bmap.containsKey(bioAssay.getAccession().getAccession())
                    || bmap.containsKey(bioAssay.getName())) {
                // defensive.
                throw new IllegalStateException("Name or accesion was duplicated for : " + bioAssay);
            }
            bmap.put(bioAssay.getAccession().getAccession(), bioAssay);
            bmap.put(bioAssay.getName(), bioAssay);
        }

        AffyPowerToolsProbesetSummarize.log.info(
                "Will attempt to match " + bioAssaysToUse.size() + " bioAssays in data set to apt output");

        AffyPowerToolsProbesetSummarize.log.debug(
                "Will match result data file columns to bioassays referred to by any of the following strings:\n"
                        + StringUtils.join(bmap.keySet(), "\n"));

        List<String> columnsToKeep = new ArrayList<>();
        for (int i = 0; i < matrix.columns(); i++) {
            String sampleName = matrix.getColName(i);

            BioAssay assay = AffyPowerToolsProbesetSummarize.matchBioAssayToCelFileName(bmap, sampleName);

            if (assay == null) {
                /*
                 * This is okay, if we have extras
                 */
                if (matrix.columns() == bioAssaysToUse.size()) {
                    throw new IllegalStateException(
                            "No bioassay could be matched to CEL file identified by " + sampleName);
                }
                AffyPowerToolsProbesetSummarize.log.warn("No bioassay found yet for " + sampleName);
                continue;
            }

            AffyPowerToolsProbesetSummarize.log.info("Matching CEL sample " + sampleName + " to bioassay "
                    + assay + " [" + assay.getAccession().getAccession() + "]");

            columnsToKeep.add(sampleName);
            bad.getBioAssays().add(assay);
        }

        if (bad.getBioAssays().size() != bioAssaysToUse.size()) {
            //noinspection unchecked
            Collection<BioAssay> missing = CollectionUtils.subtract(bioAssaysToUse, bad.getBioAssays());
            throw new IllegalStateException(
                    "Failed to find a data column for every bioassay on the given platform " + targetPlatform
                            + "; missing:\n" + StringUtils.join(missing, "\n"));
        }

        if (columnsToKeep.size() < matrix.columns()) {
            matrix = matrix.subsetColumns(columnsToKeep);
        }

        if (quantitationType == null) {
            quantitationType = AffyPowerToolsProbesetSummarize.makeAffyQuantitationType();
        }
        return this.convertDesignElementDataVectors(ee, bad, targetPlatform, matrix);
    }
}