Example usage for java.util Collection removeAll

List of usage examples for java.util Collection removeAll

Introduction

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

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes all of this collection's elements that are also contained in the specified collection (optional operation).

Usage

From source file:com.blazebit.security.impl.interceptor.ChangeInterceptor.java

/**
 * /*from   w  w w  .  j a  va  2 s  .  co  m*/
 */
@Override
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
    if (!EntityFeatures.isInterceptorActive()) {
        super.onCollectionUpdate(collection, key);
        return;
    }
    if (collection instanceof PersistentCollection) {
        PersistentCollection newValuesCollection = (PersistentCollection) collection;
        Object entity = newValuesCollection.getOwner();
        if (AnnotationUtils.findAnnotation(entity.getClass(), EntityResourceType.class) == null) {
            super.onCollectionUpdate(collection, key);
            return;
        }
        // copy new values and old values
        @SuppressWarnings({ "unchecked", "rawtypes" })
        Collection<?> newValues = new HashSet((Collection<?>) newValuesCollection.getValue());
        @SuppressWarnings({ "unchecked", "rawtypes" })
        Set<?> oldValues = new HashSet(((Map<?, ?>) newValuesCollection.getStoredSnapshot()).keySet());

        String fieldName = StringUtils.replace(newValuesCollection.getRole(), entity.getClass().getName() + ".",
                "");
        UserContext userContext = BeanProvider.getContextualReference(UserContext.class);
        ActionFactory actionFactory = BeanProvider.getContextualReference(ActionFactory.class);
        EntityResourceFactory resourceFactory = BeanProvider
                .getContextualReference(EntityResourceFactory.class);
        PermissionService permissionService = BeanProvider.getContextualReference(PermissionService.class);

        // find all objects that were added
        boolean isGrantedToAdd = true;
        boolean isGrantedToRemove = true;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        Set<?> retained = new HashSet(oldValues);
        retained.retainAll(newValues);

        oldValues.removeAll(retained);
        // if there is a difference between oldValues and newValues
        if (!oldValues.isEmpty()) {
            // if something remained
            isGrantedToRemove = permissionService.isGranted(actionFactory.createAction(Action.REMOVE),
                    resourceFactory.createResource(entity, fieldName));
        }
        newValues.removeAll(retained);
        if (!newValues.isEmpty()) {
            isGrantedToAdd = permissionService.isGranted(actionFactory.createAction(Action.ADD),
                    resourceFactory.createResource(entity, fieldName));
        }

        if (!isGrantedToAdd) {
            throw new PermissionActionException("Element cannot be added to entity " + entity + "'s collection "
                    + fieldName + " by " + userContext.getUser());
        } else {
            if (!isGrantedToRemove) {
                throw new PermissionActionException("Element cannot be removed from entity " + entity
                        + "'s collection " + fieldName + " by " + userContext.getUser());
            } else {
                super.onCollectionUpdate(collection, key);
                return;
            }
        }
    } else {
        // not a persistent collection?
    }
}

From source file:org.alfresco.repo.cache.TransactionalCache.java

/**
 * The keys returned are a union of the set of keys in the current transaction and
 * those in the backing cache.//from ww w . j ava2  s. c  o  m
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public Collection<K> getKeys() {
    Collection<Serializable> keys = null;
    // in-txn layering
    if (AlfrescoTransactionSupport.getTransactionId() != null) {
        keys = new HashSet<Serializable>(23);
        TransactionData txnData = getTransactionData();
        if (!txnData.isClearOn) {
            // the backing cache is not due for a clear
            Collection<K> backingKeys = (Collection<K>) sharedCache.getKeys();
            Collection<Serializable> backingCacheKeys = new HashSet<Serializable>(backingKeys.size());
            for (K backingKey : backingKeys) {
                backingCacheKeys.add(getTenantAwareCacheKey(backingKey));
            }
            keys.addAll(backingCacheKeys);
        }
        // add keys
        keys.addAll(txnData.updatedItemsCache.keySet());
        // remove keys
        keys.removeAll(txnData.removedItemsCache);
    } else {
        // no transaction, so just use the backing cache
        keys = (Collection) sharedCache.getKeys();
    }

    Collection<K> cacheKeys = new HashSet<K>(keys.size());
    String currentCacheRegion = TenantUtil.getCurrentDomain();

    for (Serializable key : keys) {
        if (key instanceof CacheRegionKey) {
            CacheRegionKey cacheRegionKey = (CacheRegionKey) key;
            if (currentCacheRegion.equals(cacheRegionKey.getCacheRegion())) {
                cacheKeys.add((K) cacheRegionKey.getCacheKey());
            }
        } else {
            cacheKeys.add((K) key);
        }
    }
    // done
    return cacheKeys;
}

From source file:org.slc.sli.api.service.BasicService.java

@Override
public Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery) {
    boolean isSelf = isSelf(neutralQuery);
    boolean noDataInDB = true;
    Map<String, UserContext> entityContexts = null;

    injectSecurity(neutralQuery);//from  w w w. ja v a 2 s .c  om

    boolean findSpecial = userHasMultipleContextsOrDifferingRights() && (!EntityNames.isPublic(defn.getType()));
    Collection<Entity> entities = new HashSet<Entity>();
    if (findSpecial) {
        entities = getResponseEntities(neutralQuery, isSelf);
        entityContexts = getEntityContexts();
    } else {
        entities = (Collection<Entity>) repo.findAll(collectionName, neutralQuery);

        if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) {
            entityContexts = getEntityContextMap(entities, true);
        }
    }

    //entities wihout bodies are considered deleted
    Collection<Entity> bodylessEntities = new HashSet<Entity>();
    for (Entity ent : entities) {
        if (ent.getBody() == null || ent.getBody().size() == 0) {
            bodylessEntities.add(ent);
        }
    }
    entities.removeAll(bodylessEntities);

    noDataInDB = entities.isEmpty();

    List<EntityBody> results = new ArrayList<EntityBody>();

    for (Entity entity : entities) {
        UserContext context = getEntityContext(entity.getEntityId(), entityContexts);

        try {
            Collection<GrantedAuthority> auths = null;
            if (!findSpecial) {
                auths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true);
                rightAccessValidator.checkAccess(true, isSelf, entity, defn.getType(), auths);
                rightAccessValidator.checkFieldAccess(neutralQuery, entity, defn.getType(), auths);
            } else {
                auths = getEntityAuthorities(entity.getEntityId());
            }

            results.add(entityRightsFilter.makeEntityBody(entity, treatments, defn, isSelf, auths, context));
        } catch (AccessDeniedException aex) {
            if (entities.size() == 1) {
                throw aex;
            } else {
                LOG.error(aex.getMessage());
            }
        }

    }

    if (results.isEmpty()) {
        validateQuery(neutralQuery, isSelf);
        return noEntitiesFound(noDataInDB);
    }

    return results;
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentController.java

/**
 * Get the expression experiment value objects for the expression experiments.
 *
 * @param  taxon      can be null//w w  w .  j a v a 2s . co m
 * @param  limit      limit
 * @param  eeIds      ee ids
 * @param  showPublic show public
 * @return            Collection<ExpressionExperimentValueObject>
 */
private Collection<ExpressionExperimentDetailsValueObject> getFilteredExpressionExperimentValueObjects(
        Taxon taxon, List<Long> eeIds, Integer limit, boolean showPublic) {

    Collection<ExpressionExperimentDetailsValueObject> vos = expressionExperimentService
            .loadDetailsValueObjects("curationDetails.lastUpdated", limit > 0, eeIds, taxon, Math.abs(limit),
                    0);
    // Hide public data sets if desired.
    if (!vos.isEmpty() && !showPublic) {
        Collection<ExpressionExperimentDetailsValueObject> publicEEs = securityService.choosePublic(vos);
        vos.removeAll(publicEEs);
    }

    return vos;
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentController.java

/**
 * Filter based on criteria of which events etc. the data sets have.
 *
 * @param  eeValObjectCol ee vos/*  ww w .ja  va2  s .  com*/
 * @param  filter         filter
 * @return                filtered vos
 */
private Collection<ExpressionExperimentDetailsValueObject> applyFilter(
        Collection<ExpressionExperimentDetailsValueObject> eeValObjectCol, Integer filter) {
    List<ExpressionExperimentDetailsValueObject> filtered = new ArrayList<>();
    Collection<ExpressionExperiment> eesToKeep = null;
    List<ExpressionExperimentDetailsValueObject> eeVOsToKeep = null;

    switch (filter) {
    case 1: // eligible for diff and don't have it.
        eesToKeep = expressionExperimentService.load(EntityUtils.getIds(eeValObjectCol));
        auditEventService.retainLackingEvent(eesToKeep, DifferentialExpressionAnalysisEvent.class);
        eesToKeep.removeAll(expressionExperimentService.loadLackingFactors());
        break;
    case 2: // need coexp
        eesToKeep = expressionExperimentService.load(EntityUtils.getIds(eeValObjectCol));
        auditEventService.retainLackingEvent(eesToKeep, LinkAnalysisEvent.class);
        break;
    case 3:
        eesToKeep = expressionExperimentService.load(EntityUtils.getIds(eeValObjectCol));
        auditEventService.retainHavingEvent(eesToKeep, DifferentialExpressionAnalysisEvent.class);
        break;
    case 4:
        eesToKeep = expressionExperimentService.load(EntityUtils.getIds(eeValObjectCol));
        auditEventService.retainHavingEvent(eesToKeep, LinkAnalysisEvent.class);
        break;
    case 5:
        // FIXME this can now be delegated to the DAO layer
        eeVOsToKeep = this.returnTroubled(eeValObjectCol, true);
        break;
    case 6:
        eesToKeep = expressionExperimentService.loadLackingFactors();
        break;
    case 7:
        eesToKeep = expressionExperimentService.loadLackingTags();
        break;
    case 8: // needs batch info
        eesToKeep = expressionExperimentService.load(EntityUtils.getIds(eeValObjectCol));
        auditEventService.retainLackingEvent(eesToKeep, BatchInformationFetchingEvent.class);
        auditEventService.retainLackingEvent(eesToKeep, FailedBatchInformationMissingEvent.class);
        break;
    case 9:
        eesToKeep = expressionExperimentService.load(EntityUtils.getIds(eeValObjectCol));
        auditEventService.retainHavingEvent(eesToKeep, BatchInformationFetchingEvent.class);
        break;
    case 10:
        eesToKeep = expressionExperimentService.load(EntityUtils.getIds(eeValObjectCol));
        auditEventService.retainLackingEvent(eesToKeep, PCAAnalysisEvent.class);
        break;
    case 11:
        eesToKeep = expressionExperimentService.load(EntityUtils.getIds(eeValObjectCol));
        auditEventService.retainHavingEvent(eesToKeep, PCAAnalysisEvent.class);
        break;
    case 12:
        // FIXME this can now be delegated to the DAO layer
        eeVOsToKeep = this.returnNeedsAttention(eeValObjectCol);
        break;
    case 13:
        // FIXME this can now be delegated to the DAO layer
        eeVOsToKeep = this.returnTroubled(eeValObjectCol, false);
        break;
    default:
        throw new IllegalArgumentException("Unknown filter: " + filter);

    }

    assert eesToKeep == null || eesToKeep.size() <= eeValObjectCol.size();

    // get corresponding value objects from collection param
    if (eesToKeep != null) {
        if (eesToKeep.isEmpty()) {
            return filtered;
        }
        // Map<Long, ExpressionExperiment> idMap = EntityUtils.getIdMap( eesToKeep );
        Collection<Long> ids = EntityUtils.getIds(eesToKeep);
        for (ExpressionExperimentDetailsValueObject eevo : eeValObjectCol) {
            if (ids.contains(eevo.getId())) {
                filtered.add(eevo);
            }
        }
        return filtered;

    }
    if (eeVOsToKeep != null) {
        return eeVOsToKeep;
    }

    return eeValObjectCol;
}

From source file:uk.ac.ebi.intact.editor.controller.curate.AnnotatedObjectController.java

public void replaceOrCreateAlias(String alias, String aliasMI, String name, Collection<Alias> aliases) {
    if (name == null) {
        throw new IllegalArgumentException("Impossible to replace or create aliases if the name is not set.");
    }//from ww  w . j  av a  2  s.  com

    // modify if exists
    Collection<Alias> existingAliases = AliasUtils.collectAllAliasesHavingType(aliases, aliasMI, alias);
    Alias existingAlias = !existingAliases.isEmpty() ? existingAliases.iterator().next() : null;
    // update if existing
    if (existingAlias instanceof AbstractIntactAlias) {
        AbstractIntactAlias intactAlias = (AbstractIntactAlias) existingAlias;
        intactAlias.setName(name);
    }
    // create if not exists
    else {
        aliases.removeAll(existingAliases);
        aliases.add(newAlias(alias, aliasMI, name));
    }
    setUnsavedChanges(true);
}

From source file:services.SimulationService.java

public void cleanAwareObjects(Collection<SWGObject> newAwareObjects) {
    Collection<SWGObject> cleanUpObjects = new ArrayList<SWGObject>();
    for (Iterator<SWGObject> it = newAwareObjects.iterator(); it.hasNext();) {
        SWGObject obj = it.next();/*from www.j a v a  2 s .c  o m*/
        SWGObject objInList = NGECore.getInstance().objectService.getObject(obj.getObjectID());
        if (objInList == null)
            cleanUpObjects.add(obj);
    }
    newAwareObjects.removeAll(cleanUpObjects);
}

From source file:com.globalsight.everest.usermgr.UserManagerLocal.java

/**
 * @seeUserManager.removeRateFromRole(Rate, Activity, String, String)
 *//* w w  w  .j  a va2  s  .c  o m*/
public void removeRateFromRole(Rate p_rate, Activity p_activity, String p_sourceLocale, String p_targetLocale)
        throws RemoteException, UserManagerException {
    ContainerRole cr = getContainerRole(p_activity, p_sourceLocale, p_targetLocale);

    if (cr != null) {
        List<Rate> removedRate = new ArrayList<Rate>();
        Collection rs = cr.getRates();
        for (Object o : rs) {
            Rate r = (Rate) o;
            if (r.getId() == p_rate.getId()) {
                removedRate.add(r);
            }
        }

        rs.removeAll(removedRate);
        HibernateUtil.saveOrUpdate(cr);
        //            removeRateFromRole(p_rate, cr);
    }
}

From source file:org.apache.stratos.manager.persistence.RegistryBasedPersistenceManager.java

public Collection<Service> traverseAndGetDeloyedServices(String resourcePath)
        throws PersistenceManagerException {

    if (log.isDebugEnabled()) {
        log.debug("Root resource path: " + resourcePath);
    }//from   w w w  .j  ava 2s .c  om

    Object resourceObj;

    try {
        resourceObj = RegistryManager.getInstance().retrieve(resourcePath);

    } catch (RegistryException e) {
        throw new PersistenceManagerException(e);
    }

    Collection<Service> services = new ArrayList<Service>();

    if (resourceObj == null) {
        // there is no resource at the given path
        return null;

    } else if (resourceObj instanceof String[]) {

        // get the paths for all Service instances
        String[] serviceResourcePaths = (String[]) resourceObj;
        if (log.isDebugEnabled()) {
            for (String retrievedResourcePath : serviceResourcePaths) {
                log.debug("Retrieved resource sub-path " + retrievedResourcePath);
            }
        }

        // traverse the paths recursively
        for (String serviceResourcePath : serviceResourcePaths) {

            if (log.isDebugEnabled()) {
                log.debug("Traversing resource path " + serviceResourcePath);
            }

            services.addAll(traverseAndGetDeloyedServices(serviceResourcePath));
        }

    } else {
        // De-serialize
        Object serviceObj;

        try {
            serviceObj = Deserializer.deserializeFromByteArray((byte[]) resourceObj);

        } catch (Exception e) {
            // issue might be de-serializing only this object, therefore log and continue without throwing
            log.error("Error while de-serializing the object retrieved from " + resourcePath, e);
            return null;
        }

        if (serviceObj != null && serviceObj instanceof Service) {

            Service deserilizedService = (Service) serviceObj;
            if (log.isDebugEnabled()) {
                log.debug("Successfully de-serialized Service: " + deserilizedService.toString());
            }

            services.add(deserilizedService);

        }
    }

    // remove any nulls
    services.removeAll(Collections.singleton(null));
    return services;
}

From source file:org.apache.cassandra.service.StorageService.java

private Multimap<Range, InetAddress> getChangedRangesForLeaving(String table, InetAddress endpoint) {
    // First get all ranges the leaving endpoint is responsible for
    Collection<Range> ranges = getRangesForEndpoint(table, endpoint);

    if (logger_.isDebugEnabled())
        logger_.debug("Node " + endpoint + " ranges [" + StringUtils.join(ranges, ", ") + "]");

    Map<Range, List<InetAddress>> currentReplicaEndpoints = new HashMap<Range, List<InetAddress>>();

    // Find (for each range) all nodes that store replicas for these ranges as well
    for (Range range : ranges)
        currentReplicaEndpoints.put(range, Table.open(table).getReplicationStrategy()
                .calculateNaturalEndpoints(range.right, tokenMetadata_));

    TokenMetadata temp = tokenMetadata_.cloneAfterAllLeft();

    // endpoint might or might not be 'leaving'. If it was not leaving (that is, removetoken
    // command was used), it is still present in temp and must be removed.
    if (temp.isMember(endpoint))
        temp.removeEndpoint(endpoint);/*from   w  ww  . j  ava  2 s  .c o  m*/

    Multimap<Range, InetAddress> changedRanges = HashMultimap.create();

    // Go through the ranges and for each range check who will be
    // storing replicas for these ranges when the leaving endpoint
    // is gone. Whoever is present in newReplicaEndpoints list, but
    // not in the currentReplicaEndpoints list, will be needing the
    // range.
    for (Range range : ranges) {
        Collection<InetAddress> newReplicaEndpoints = Table.open(table).getReplicationStrategy()
                .calculateNaturalEndpoints(range.right, temp);
        newReplicaEndpoints.removeAll(currentReplicaEndpoints.get(range));
        if (logger_.isDebugEnabled())
            if (newReplicaEndpoints.isEmpty())
                logger_.debug("Range " + range + " already in all replicas");
            else
                logger_.debug("Range " + range + " will be responsibility of "
                        + StringUtils.join(newReplicaEndpoints, ", "));
        changedRanges.putAll(range, newReplicaEndpoints);
    }

    return changedRanges;
}