Example usage for java.util Collection retainAll

List of usage examples for java.util Collection retainAll

Introduction

In this page you can find the example usage for java.util Collection retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this collection that are contained in the specified collection (optional operation).

Usage

From source file:org.architecturerules.services.CyclicRedundancyServiceImpl.java

/**
 * <p>Check all the packages in all of the source directories and search for any cyclic redundancy</p>
 *///w  w w  .  jav  a  2 s.c o m
public void performCyclicRedundancyCheck() {

    configuration.onCyclicDependencyTestBegin();
    log.info("cyclic redundancy check requested");

    final Collection<JavaPackage> packages = getPackages();

    /**
     *  TODO: report classes involved
     *  Report on which class is causing the cyclic redundancy.
     *  The information is all available from within the JavaPackage
     *  class.
     */

    /**
     * Holds any cycles that are found. The structure of this Map is
     * <JavaPackage, Set> where the first String is the name of the package,
     * and the Set contains JavaPackge of packages that are in a cycle with
     * the named package.
     */
    final Map<JavaPackage, Set<JavaPackage>> cycles = new HashMap<JavaPackage, Set<JavaPackage>>();

    for (final JavaPackage javaPackage : packages) {

        final Collection<JavaPackage> afferents = javaPackage.getAfferents();
        final Collection<JavaPackage> efferents = javaPackage.getEfferents();

        /**
         * afferents Collection is no longer a reference to the afferents,
         * but now a Collection of packages involved in a cyclic dependency
         * with the javaPackage. By calling retainAll the afferents
         * Collection now contains only those javaPackages that were in both
         * the efferents and afferents Collections. And by definition, when
         * a package is both uses the given package, and used by the given
         * package, a cyclic dependency exists.
         */
        afferents.retainAll(efferents);

        final boolean cyclesFound = afferents.size() > 0;

        if (cyclesFound) {

            addCycle(cycles, javaPackage, afferents);
        }
    }

    if (!cycles.isEmpty()) {

        final CyclicRedundancyException cyclicRedundancyException = buildCyclicRedundancyException(cycles);
        throw cyclicRedundancyException;
    }

    configuration.onCyclicDependencyTestEnd();
}

From source file:ubic.gemma.genome.gene.service.GeneSetServiceImpl.java

/**
 * Returns all the gene sets user can see, with optional restrictions based on taxon and whether the set is public
 * or private//ww w.j  a v  a  2s .c  om
 * 
 * @param privateOnly only return private sets owned by the user or private sets shared with the user
 * @param taxonId if non-null, restrict the groups by ones which have genes in the given taxon (can be null)
 * @param sharedPublicOnly if true, the only public sets returned will be those that are owned by the user or have
 *        been shared with the user. If param privateOnly is true, this will have no effect.
 * @return
 */
@Override
public Collection<GeneSet> getUsersGeneGroups(boolean privateOnly, Long taxonId, boolean sharedPublicOnly) {

    Taxon tax = null;
    if (taxonId != null) {
        tax = taxonService.load(taxonId);
        if (tax == null) {
            throw new IllegalArgumentException("No such taxon with id=" + taxonId);
        }
    }

    Collection<GeneSet> geneSets = new LinkedList<GeneSet>();

    if (privateOnly) {
        // gets all groups user can see (includes: owned by user, shared with user & public)
        geneSets = loadAll(tax);

        // this filtering is to filter out public sets
        try {
            if (!geneSets.isEmpty()) {
                geneSets.retainAll(securityService.choosePrivate(geneSets));
            }
        } catch (AccessDeniedException e) {
            // okay, they just aren't allowed to see those.
        }
    } else if (sharedPublicOnly) {
        // gets all groups shared with the user and all groups owned by the user, except public ones
        geneSets = loadMySharedGeneSets(tax);
    } else {
        geneSets = loadAll(tax);
    }

    return geneSets;
}

From source file:org.apache.openjpa.kernel.AttachStrategy.java

/**
 * Replace the contents of <code>toc</code> with the contents of
 * <code>frmc</code>. Neither collection is null.
 *//*from  w  w  w. j a va2  s.  c  om*/
private void replaceCollection(AttachManager manager, Collection frmc, Collection toc, OpenJPAStateManager sm,
        FieldMetaData fmd) {
    // if frmc collection is empty, just clear toc
    if (frmc.isEmpty()) {
        if (!toc.isEmpty())
            toc.clear();
        return;
    }

    // if this is a pc collection, attach all instances
    boolean pc = fmd.getElement().isDeclaredTypePC();
    if (pc)
        frmc = attachCollection(manager, frmc, sm, fmd);

    // remove all elements from the toc collection that aren't in frmc
    toc.retainAll(frmc);

    // now add all elements that are in frmc but not toc
    if (frmc.size() != toc.size()) {
        for (Iterator i = frmc.iterator(); i.hasNext();) {
            Object ob = i.next();
            if (!toc.contains(ob))
                toc.add(ob);
        }
    }
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.SAML2SSOAuthenticator.java

/**
 * Provision/Create user on the server(SP) and update roles accordingly
 *
 * @param username//from www  . j a  v a 2 s .c  o  m
 * @param realm
 * @param xmlObject
 * @throws UserStoreException
 * @throws SAML2SSOAuthenticatorException
 */
private void provisionUser(String username, UserRealm realm, XMLObject xmlObject)
        throws UserStoreException, SAML2SSOAuthenticatorException {
    AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance();
    AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration
            .getAuthenticatorConfig(AUTHENTICATOR_NAME);

    if (authenticatorConfig != null) {
        Map<String, String> configParameters = authenticatorConfig.getParameters();

        boolean isJITProvisioningEnabled = false;
        if (configParameters
                .containsKey(SAML2SSOAuthenticatorBEConstants.PropertyConfig.JIT_USER_PROVISIONING_ENABLED)) {
            isJITProvisioningEnabled = Boolean.parseBoolean(configParameters
                    .get(SAML2SSOAuthenticatorBEConstants.PropertyConfig.JIT_USER_PROVISIONING_ENABLED));
        }

        if (isJITProvisioningEnabled) {
            String userstoreDomain = null;
            if (configParameters.containsKey(
                    SAML2SSOAuthenticatorBEConstants.PropertyConfig.PROVISIONING_DEFAULT_USERSTORE)) {
                userstoreDomain = configParameters
                        .get(SAML2SSOAuthenticatorBEConstants.PropertyConfig.PROVISIONING_DEFAULT_USERSTORE);
            }

            UserStoreManager userstore = null;

            // TODO : Get userstore from asserstion
            // TODO : remove user store domain name from username

            if (userstoreDomain != null && !userstoreDomain.isEmpty()) {
                userstore = realm.getUserStoreManager().getSecondaryUserStoreManager(userstoreDomain);
            }

            // If default user store is invalid or not specified use primary user store
            if (userstore == null) {
                userstore = realm.getUserStoreManager();
            }

            String[] newRoles = getRoles(xmlObject);
            // Load default role if asserstion didnt specify roles
            if (newRoles == null || newRoles.length == 0) {
                if (configParameters.containsKey(
                        SAML2SSOAuthenticatorBEConstants.PropertyConfig.PROVISIONING_DEFAULT_ROLE)) {
                    newRoles = new String[] { configParameters
                            .get(SAML2SSOAuthenticatorBEConstants.PropertyConfig.PROVISIONING_DEFAULT_ROLE) };
                }
            }
            if (newRoles == null) {
                newRoles = new String[] {};
            }

            if (log.isDebugEnabled()) {
                log.debug("User " + username + " contains roles : " + Arrays.toString(newRoles)
                        + " as per response and (default role) config");
            }

            // addingRoles = newRoles AND allExistingRoles
            Collection<String> addingRoles = new ArrayList<String>();
            Collections.addAll(addingRoles, newRoles);
            Collection<String> allExistingRoles = Arrays.asList(userstore.getRoleNames());
            addingRoles.retainAll(allExistingRoles);

            if (userstore.isExistingUser(username)) {
                // Update user
                Collection<String> currentRolesList = Arrays.asList(userstore.getRoleListOfUser(username));
                // addingRoles = (newRoles AND existingRoles) - currentRolesList)
                addingRoles.removeAll(currentRolesList);

                Collection<String> deletingRoles = new ArrayList<String>();
                deletingRoles.addAll(currentRolesList);
                // deletingRoles = currentRolesList - newRoles
                deletingRoles.removeAll(Arrays.asList(newRoles));

                // Exclude Internal/everyonerole from deleting role since its cannot be deleted
                deletingRoles.remove(realm.getRealmConfiguration().getEveryOneRoleName());

                // Check for case whether superadmin login
                if (userstore.getRealmConfiguration().isPrimary()
                        && username.equals(realm.getRealmConfiguration().getAdminUserName())) {
                    boolean isSuperAdminRoleRequired = false;
                    if (configParameters.containsKey(
                            SAML2SSOAuthenticatorBEConstants.PropertyConfig.IS_SUPER_ADMIN_ROLE_REQUIRED)) {
                        isSuperAdminRoleRequired = Boolean.parseBoolean(configParameters.get(
                                SAML2SSOAuthenticatorBEConstants.PropertyConfig.IS_SUPER_ADMIN_ROLE_REQUIRED));
                    }

                    // Whether superadmin login without superadmin role is permitted
                    if (!isSuperAdminRoleRequired
                            && deletingRoles.contains(realm.getRealmConfiguration().getAdminRoleName())) {
                        // Avoid removing superadmin role from superadmin user.
                        deletingRoles.remove(realm.getRealmConfiguration().getAdminRoleName());
                        log.warn(
                                "Proceeding with allowing super admin to be logged in, eventhough response doesn't include superadmin role assiged for the superadmin user.");
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug("Deleting roles : " + Arrays.toString(deletingRoles.toArray(new String[0]))
                            + " and Adding roles : " + Arrays.toString(addingRoles.toArray(new String[0])));
                }
                userstore.updateRoleListOfUser(username, deletingRoles.toArray(new String[0]),
                        addingRoles.toArray(new String[0]));
                if (log.isDebugEnabled()) {
                    log.debug("User: " + username + " is updated via SAML authenticator with roles : "
                            + Arrays.toString(newRoles));
                }
            } else {
                userstore.addUser(username, generatePassword(username), addingRoles.toArray(new String[0]),
                        null, null);
                if (log.isDebugEnabled()) {
                    log.debug("User: " + username + " is provisioned via SAML authenticator with roles : "
                            + Arrays.toString(addingRoles.toArray(new String[0])));
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("User provisioning diabled");
            }
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Cannot find authenticator config for authenticator : " + AUTHENTICATOR_NAME);
        }
        throw new SAML2SSOAuthenticatorException(
                "Cannot find authenticator config for authenticator : " + AUTHENTICATOR_NAME);
    }
}

From source file:ubic.gemma.ontology.providers.GeneOntologyServiceImpl.java

@Override
public Collection<OntologyTerm> computeOverlap(Collection<OntologyTerm> masterOntos,
        Collection<OntologyTerm> comparisonOntos) {
    Collection<OntologyTerm> overlapTerms = new HashSet<OntologyTerm>(masterOntos);
    overlapTerms.retainAll(comparisonOntos);

    return overlapTerms;
}

From source file:org.openmrs.module.providermanagement.api.impl.ProviderSuggestionServiceImpl.java

private List<Person> suggestSupervisionForProviderHelper(Person provider, SupervisionSuggestionType type)
        throws PersonIsNotProviderException, SuggestionEvaluationException {

    if (provider == null) {
        throw new APIException("Provider cannot be null");
    }//from www  .  j a  v  a  2 s  . co m

    // fail if the person is not a provider
    if (!Context.getService(ProviderManagementService.class).isProvider(provider)) {
        throw new PersonIsNotProviderException(provider + " is not a provider");
    }

    // first, get all the roles for this provider
    List<ProviderRole> roles = Context.getService(ProviderManagementService.class).getProviderRoles(provider);

    // if the provider has no roles, return null
    if (roles == null || roles.size() == 0) {
        return null;
    }

    // now get all the roles that this provider can supervise or be supervisors by (depending on type)
    List<ProviderRole> validRoles;

    if (type.equals(SupervisionSuggestionType.SUPERVISEE_SUGGESTION)) {
        validRoles = Context.getService(ProviderManagementService.class)
                .getProviderRolesThatProviderCanSupervise(provider);
    } else {
        validRoles = Context.getService(ProviderManagementService.class)
                .getProviderRolesThatCanSuperviseThisProvider(provider);
    }

    // get any suggestions based on the provider roles
    Set<SupervisionSuggestion> suggestions = new HashSet<SupervisionSuggestion>();
    for (ProviderRole role : roles) {
        List<SupervisionSuggestion> s = getSupervisionSuggestionsByProviderRoleAndSuggestionType(role, type);
        if (s != null && s.size() > 0) {
            suggestions.addAll(s);
        }
    }

    // if there are no suggestions, or no valid roles, just return null
    if (suggestions.size() == 0 || validRoles == null || validRoles.size() == 0) {
        return null;
    }

    // otherwise, get all the providers that match the suggestion rules
    Collection<Person> suggestedProviders = new HashSet<Person>();
    for (SupervisionSuggestion suggestion : suggestions) {
        try {
            SuggestionEvaluator evaluator = suggestion.instantiateEvaluator();
            Set<Person> p = evaluator.evaluate(suggestion, provider);
            if (p != null) {
                // note that we are doing union, not intersection, here if there are multiple rules
                suggestedProviders.addAll(p);
            }
        } catch (Exception e) {
            throw new SuggestionEvaluationException("Unable to evaluate suggestion " + suggestion, e);
        }
    }

    // only keep providers that are valid for this provider to supervise or be supervised by
    suggestedProviders.retainAll(
            Context.getService(ProviderManagementService.class).getProvidersAsPersonsByRoles(validRoles));

    // finally, remove any providers that this provider is already supervising or being supervised by
    if (type.equals(SupervisionSuggestionType.SUPERVISEE_SUGGESTION)) {
        suggestedProviders.removeAll(Context.getService(ProviderManagementService.class)
                .getSuperviseesForSupervisor(provider, new Date()));
    } else {
        suggestedProviders.removeAll(Context.getService(ProviderManagementService.class)
                .getSupervisorsForProvider(provider, new Date()));
    }

    // return the result set
    return new ArrayList<Person>(suggestedProviders);
}

From source file:org.squashtest.tm.service.internal.testcase.CustomTestCaseModificationServiceImpl.java

@Override
public Collection<Long> findBindedMilestonesIdForMassModif(List<Long> testCaseIds) {

    Collection<Milestone> milestones = null;

    for (Long testCaseId : testCaseIds) {
        Set<Milestone> mil = testCaseDao.findById(testCaseId).getMilestones();
        if (milestones != null) {
            //keep only milestone that in ALL selected tc
            milestones.retainAll(mil);
        } else {/*from w w  w.j av  a2 s  .c  o m*/
            //populate the collection for the first time
            milestones = new ArrayList<>(mil);
        }
    }
    filterLockedAndPlannedStatus(milestones);

    return CollectionUtils.collect(milestones, new Transformer() {

        @Override
        public Object transform(Object milestone) {

            return ((Milestone) milestone).getId();
        }
    });
}

From source file:org.squashtest.tm.service.internal.testcase.CustomTestCaseModificationServiceImpl.java

@Override
public Collection<Milestone> findAssociableMilestonesForMassModif(List<Long> testCaseIds) {

    Collection<Milestone> milestones = null;

    for (Long testCaseId : testCaseIds) {
        List<Milestone> mil = testCaseDao.findById(testCaseId).getProject().getMilestones();
        if (milestones != null) {
            //keep only milestone that in ALL selected tc
            milestones.retainAll(mil);
        } else {//from   www . j  av a  2s . c  o m
            //populate the collection for the first time
            milestones = new ArrayList<>(mil);
        }
    }
    filterLockedAndPlannedStatus(milestones);
    return milestones;
}

From source file:org.openmrs.module.providermanagement.api.impl.ProviderSuggestionServiceImpl.java

@Override
@Transactional(readOnly = true)//w  ww . j av a 2 s . com
public List<Person> suggestProvidersForPatient(Patient patient, RelationshipType relationshipType)
        throws InvalidRelationshipTypeException, SuggestionEvaluationException {

    if (patient == null) {
        throw new APIException("Patient cannot be null");
    }

    if (relationshipType == null) {
        throw new APIException("Relationship type cannot be null");
    }

    if (!Context.getService(ProviderManagementService.class).getAllProviderRoleRelationshipTypes(false)
            .contains(relationshipType)) {
        throw new InvalidRelationshipTypeException("Invalid relationship type: " + relationshipType
                + " is not a valid provider relationship type");
    }

    // first, see if there are any suggestion rules if not, just return null
    List<ProviderSuggestion> suggestions = getProviderSuggestionsByRelationshipType(relationshipType);
    if (suggestions == null || suggestions.size() == 0) {
        return null;
    }

    // otherwise, get all the providers that match the suggestion rules
    Collection<Person> suggestedProviders = new HashSet<Person>();
    for (ProviderSuggestion suggestion : suggestions) {
        try {
            SuggestionEvaluator evaluator = suggestion.instantiateEvaluator();
            Set<Person> p = evaluator.evaluate(suggestion, patient, relationshipType);
            if (p != null) {
                // note that we are doing union, not intersection, here if there are multiple rules
                suggestedProviders.addAll(p);
            }
        } catch (Exception e) {
            throw new SuggestionEvaluationException("Unable to evaluate suggestion " + suggestion, e);
        }
    }

    // only keep those providers that are valid (ie, support the specified relationship type
    // TODO: might want to test the performance of this
    suggestedProviders.retainAll(Context.getService(ProviderManagementService.class)
            .getProvidersAsPersonsByRelationshipType(relationshipType));

    // finally, remove any providers that are already assigned to this patient
    suggestedProviders.removeAll(Context.getService(ProviderManagementService.class)
            .getProvidersAsPersonsForPatient(patient, relationshipType, new Date()));

    return new ArrayList<Person>(suggestedProviders);
}

From source file:edu.purdue.cc.bionet.ui.DistributionAnalysisDisplayPanel.java

public void deselectOutliers() {
    Iterator<TreeNode> moleculeIterator = this.selectorTree
            .checkedDescendantIterator(this.selectorTree.getRoot(), MOLECULE);

    while (moleculeIterator.hasNext()) {
        DefaultMutableTreeNode moleculeNode = (DefaultMutableTreeNode) moleculeIterator.next();
        Molecule molecule = (Molecule) moleculeNode.getUserObject();

        Iterator<TreeNode> experimentIterator = this.selectorTree.checkedDescendantIterator(moleculeNode,
                EXPERIMENT);// w  w  w  .  j  a va 2  s  .  c  om
        while (experimentIterator.hasNext()) {
            DefaultMutableTreeNode experimentNode = (DefaultMutableTreeNode) experimentIterator.next();

            Iterator<TreeNode> sampleIterator = this.selectorTree.checkedDescendantIterator(experimentNode,
                    SAMPLE);
            TreeSet<Sample> sampleSet = new TreeSet<Sample>();
            while (sampleIterator.hasNext()) {
                DefaultMutableTreeNode sampleNode = (DefaultMutableTreeNode) sampleIterator.next();
                sampleSet.add((Sample) sampleNode.getUserObject());
            }

            for (SampleGroup group : this.getSampleGroups()) {
                Collection<Sample> sampleUnion = new TreeSet<Sample>(group);
                sampleUnion.retainAll(sampleSet);
                Range range = Statistics.regularRange(molecule.getValues(sampleUnion).toDoubleArray());
                sampleIterator = this.selectorTree.checkedDescendantIterator(experimentNode, SAMPLE);

                while (sampleIterator.hasNext()) {
                    DefaultMutableTreeNode sampleNode = (DefaultMutableTreeNode) sampleIterator.next();
                    Sample sample = (Sample) sampleNode.getUserObject();
                    if (sampleUnion.contains(sample)
                            && !range.contains(molecule.getValue(sample).doubleValue()))
                        this.selectorTree.uncheck(sampleNode);
                }
            }
        }
    }
}