Example usage for java.util Set removeAll

List of usage examples for java.util Set removeAll

Introduction

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

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes from this set all of its elements that are contained in the specified collection (optional operation).

Usage

From source file:com.ephesoft.dcma.da.dao.hibernate.BatchInstanceDaoImpl.java

/**
 * This API fetches batch instance on the basis of user name and the roles defined for that user name in the batch class.
 * //from   w  ww. j a  v a  2  s. c  o m
 * @param userRoles
 * @param batchInstanceIdentifier
 * @param currentUserName
 * @param ephesoftUser
 * @return
 */
@Override
public BatchInstance getBatchInstanceByUserRole(final Set<String> userRoles, String batchInstanceIdentifier,
        String currentUserName, EphesoftUser ephesoftUser) {

    BatchInstance batchInstances = null;

    Set<String> batchClassIdentifiers = null;

    switch (ephesoftUser) {
    case NORMAL_USER:
        batchClassIdentifiers = batchClassGroupsDao.getBatchClassIdentifierForUserRoles(userRoles);
        Set<String> batchInstanceIdentifiers = batchInstanceGroupsDao
                .getBatchInstanceIdentifierForUserRoles(userRoles);
        Set<String> batchInstanceIdentifierSet = batchInstanceGroupsDao
                .getBatchInstanceIdentifiersExceptUserRoles(userRoles);
        batchInstanceIdentifierSet.removeAll(batchInstanceIdentifiers);
        if ((null != batchClassIdentifiers && batchClassIdentifiers.size() > 0)
                || (null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0)) {
            EphesoftCriteria criteria = criteria();
            criteria.add(Restrictions.or(Restrictions.isNull(CURRENT_USER),
                    Restrictions.eq(CURRENT_USER, currentUserName)));
            criteria.add(Restrictions.eq(IS_REMOTE, false));
            criteria.add(Restrictions.eq(BATCH_INSTANCE_IDENTIFIER, batchInstanceIdentifier));
            batchInstances = findSingle(criteria);

            String batchClassId = batchInstances.getBatchClass().getBatchClassID().getID();
            boolean isValid = true;
            boolean notInValidity = checkNotInBatchInstanceId(batchInstanceIdentifier,
                    batchInstanceIdentifierSet);
            boolean batchClassValidity = checkBatchClassId(batchClassIdentifiers, batchClassId);
            boolean inValididty = checkValidBatchId(batchInstanceIdentifier, batchInstanceIdentifiers);
            if (null != batchClassIdentifiers && batchClassIdentifiers.size() > 0
                    && null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0
                    && null != batchInstanceIdentifierSet && batchInstanceIdentifierSet.size() > 0) {
                isValid = notInValidity && (batchClassValidity || inValididty);
            } else if (null != batchClassIdentifiers && batchClassIdentifiers.size() > 0
                    && null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0) {
                isValid = batchClassValidity || inValididty;
            } else if (null != batchClassIdentifiers && batchClassIdentifiers.size() > 0
                    && null != batchInstanceIdentifierSet && batchInstanceIdentifierSet.size() > 0) {
                isValid = notInValidity && batchClassValidity;
            } else if (null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0
                    && null != batchInstanceIdentifierSet && batchInstanceIdentifierSet.size() > 0) {
                isValid = notInValidity && inValididty;
            } else if (null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0) {
                isValid = inValididty;
            } else if (null != batchClassIdentifiers && batchClassIdentifiers.size() > 0) {
                isValid = batchClassValidity;
            }
            if (!isValid) {
                batchInstances = null;
            }
        }
        break;
    default:
        batchClassIdentifiers = batchClassGroupsDao.getBatchClassIdentifierForUserRoles(userRoles);
        if (null != batchClassIdentifiers && batchClassIdentifiers.size() > 0) {
            EphesoftCriteria criteria = criteria();
            criteria.add(Restrictions.or(Restrictions.isNull(CURRENT_USER),
                    Restrictions.eq(CURRENT_USER, currentUserName)));
            criteria.add(Restrictions.eq(IS_REMOTE, false));
            criteria.add(Restrictions.eq(BATCH_INSTANCE_IDENTIFIER, batchInstanceIdentifier));
            criteria.createAlias(BATCH_CLASS, BATCH_CLASS);
            criteria.add(Restrictions.in(BATCH_CLASS_IDENTIFIER, batchClassIdentifiers));

            batchInstances = findSingle(criteria);
        }
        break;
    }
    return batchInstances;
}

From source file:com.almende.eve.agent.MeetingAgent.java

/**
 * update the activity for meeting agent.
 * //  w  ww  .j a v  a2s.  c o m
 * @param updatedActivity
 *            the updated activity
 * @return the activity
 * @throws Exception
 *             the exception
 */
public Activity updateActivity(@Name("activity") final Activity updatedActivity) throws Exception {
    Activity activity = getState().get("activity", Activity.class);
    if (activity == null) {
        activity = new Activity();
    }

    final Set<String> prevAttendees = getAgents(activity);

    // if no updated timestamp is provided, set the timestamp to now
    if (updatedActivity.withStatus().getUpdated() == null) {
        updatedActivity.withStatus().setUpdated(DateTime.now().toString());
    }

    // synchronize with the stored activity
    activity = Activity.sync(activity, updatedActivity);

    // ensure the url of the meeting agent is filled in
    final URI myUrl = getFirstUrl("http");
    activity.setAgent(myUrl);

    // create duration when missing
    Long duration = activity.withConstraints().withTime().getDuration();
    if (duration == null) {
        duration = Duration.standardHours(1).getMillis(); // 1 hour in ms
        activity.withConstraints().withTime().setDuration(duration);
    }

    // remove calendar events from removed attendees
    final Set<String> currentAttendees = getAgents(activity);
    final Set<String> removedAttendees = new TreeSet<String>(prevAttendees);
    removedAttendees.removeAll(currentAttendees);
    for (final String attendee : removedAttendees) {
        clearAttendee(attendee);
    }

    getState().put("activity", activity);

    // update all attendees, start timer to regularly check
    update();

    return getState().get("activity", Activity.class);
}

From source file:com.ephesoft.dcma.da.dao.hibernate.BatchInstanceDaoImpl.java

/**
 * Gets the batch instance list filtered as per the arguments supplied.
 * //from   w  w w .  ja v a  2s . c  om
 * @param batchInstStatusList List<{@link BatchInstanceStatus}>
 * @param batchPriorities the priority list of the batches
 * @param isCurrUsrNotReq true if the current user can be anyone. False if current user cannot be null.
 * @param currentUser {@link String}
 * @param userRoles Set<{@link String}>
 * @param ephesoftUser {@link EphesoftUser}
 * @param searchString the searchString on which batch instances have to be fetched
 * @return List<BatchInstance> returns the batch instance list filtered as per the information passed as arguments
 */
@Override
public List<BatchInstance> getBatchInstanceList(final List<BatchInstanceStatus> batchInstStatusList,
        final List<BatchPriority> batchPriorities, final boolean isNotCurrentUserCheckReq,
        final Set<String> userRoles, final String currentUserName, EphesoftUser ephesoftUser,
        final String searchString) {
    EphesoftCriteria criteria = criteria();

    if (null != batchInstStatusList) {
        criteria.add(Restrictions.in(STATUS, batchInstStatusList));
    }

    if (null != searchString && !searchString.isEmpty()) {
        String searchStringLocal = searchString.replaceAll("%", "\\\\%");
        Criterion nameLikeCriteria = Restrictions.like(BATCH_NAME, "%" + searchStringLocal + "%");
        Criterion idLikeCriteria = Restrictions.like(BATCH_INSTANCE_IDENTIFIER, "%" + searchStringLocal + "%");

        LogicalExpression searchCriteria = Restrictions.or(nameLikeCriteria, idLikeCriteria);
        criteria.add(searchCriteria);
    }

    if (null != batchPriorities && !(batchPriorities.isEmpty())) {
        Disjunction disjunction = Restrictions.disjunction();
        for (BatchPriority batchPriority : batchPriorities) {
            if (null != batchPriority) {
                Integer lowValue = batchPriority.getLowerLimit();
                Integer upperValue = batchPriority.getUpperLimit();
                disjunction.add(Restrictions.between(PRIORITY, lowValue, upperValue));
            } else {
                disjunction = Restrictions.disjunction();
                break;
            }
        }
        criteria.add(disjunction);
    }

    Set<String> batchClassIdentifiers = null;
    Set<String> batchInstanceIdentifiers = null;
    List<BatchInstance> batchInstanceList = null;
    switch (ephesoftUser) {
    case ADMIN_USER:
        batchClassIdentifiers = batchClassGroupsDao.getBatchClassIdentifierForUserRoles(userRoles);
        batchInstanceIdentifiers = batchInstanceGroupsDao.getBatchInstanceIdentifierForUserRoles(userRoles);
        if ((null != batchClassIdentifiers && batchClassIdentifiers.size() > 0)
                || (null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0)) {
            // Add check for null current users only.
            // Now we will count only for those current users those are null.
            if (!isNotCurrentUserCheckReq && null != currentUserName) {
                criteria.add(Restrictions.or(Restrictions.isNull(CURRENT_USER),
                        Restrictions.eq(CURRENT_USER, currentUserName)));
            }
            List<BatchInstance> batchInstances = find(criteria);

            batchInstanceList = new ArrayList<BatchInstance>();
            if (batchInstances != null && !batchInstances.isEmpty()) {
                batchInstanceList.addAll(batchInstances);
                for (BatchInstance batchInstance : batchInstances) {
                    String batchInstanceIdentifier = batchInstance.getIdentifier();
                    String batchClassIdentifier = batchInstance.getBatchClass().getBatchClassID().getID();
                    boolean isValid = true;
                    boolean batchClassValidity = checkBatchClassId(batchClassIdentifiers, batchClassIdentifier);
                    boolean inValididty = checkValidBatchId(batchInstanceIdentifier, batchInstanceIdentifiers);

                    if (null != batchClassIdentifiers && batchClassIdentifiers.size() > 0
                            && null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0) {
                        isValid = batchClassValidity || inValididty;
                    } else if (null != batchClassIdentifiers && batchClassIdentifiers.size() > 0) {
                        isValid = batchClassValidity;
                    } else if (null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0) {
                        isValid = inValididty;
                    }
                    if (!isValid) {
                        batchInstanceList.remove(batchInstance);
                    }
                }
            }
        }
        break;
    default:
        batchClassIdentifiers = batchClassGroupsDao.getBatchClassIdentifierForUserRoles(userRoles);
        batchInstanceIdentifiers = batchInstanceGroupsDao.getBatchInstanceIdentifierForUserRoles(userRoles);

        if ((null != batchClassIdentifiers && batchClassIdentifiers.size() > 0)
                || (null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0)) {
            Set<String> batchInstanceIdentifierSet = batchInstanceGroupsDao
                    .getBatchInstanceIdentifiersExceptUserRoles(userRoles);
            batchInstanceIdentifierSet.removeAll(batchInstanceIdentifiers);
            if (!isNotCurrentUserCheckReq && null != currentUserName) {
                criteria.add(Restrictions.or(Restrictions.isNull(CURRENT_USER),
                        Restrictions.eq(CURRENT_USER, currentUserName)));
            }
            batchInstanceList = find(criteria);
            batchInstanceList = updateBatchInstanceList(batchInstanceList, batchClassIdentifiers,
                    batchInstanceIdentifiers, batchInstanceIdentifierSet, 0, batchInstanceList.size());
        }
        break;
    }
    return batchInstanceList;
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.coprincipalinvestigator.CoPIGrantCountQueryRunner.java

private void removeLowQualityNodesAndEdges(Set<Collaborator> nodes, Map<String, Activity> grantURLToVO,
        Map<String, Set<Collaborator>> grantURLToCoPIs, Set<Collaboration> edges) {

    Set<Collaborator> nodesToBeRemoved = new HashSet<Collaborator>();
    for (Map.Entry<String, Set<Collaborator>> currentGrantEntry : grantURLToCoPIs.entrySet()) {

        if (currentGrantEntry.getValue().size() > MAX_PI_PER_GRANT_ALLOWED) {

            Activity currentGrant = grantURLToVO.get(currentGrantEntry.getKey());

            Set<Collaboration> edgesToBeRemoved = new HashSet<Collaboration>();

            for (Collaboration currentEdge : edges) {
                Set<Activity> currentCollaboratorGrants = currentEdge.getCollaborationActivities();

                if (currentCollaboratorGrants.contains(currentGrant)) {
                    currentCollaboratorGrants.remove(currentGrant);
                    if (currentCollaboratorGrants.isEmpty()) {
                        edgesToBeRemoved.add(currentEdge);
                    }//w w w.jav  a  2 s  . c  o  m
                }
            }

            edges.removeAll(edgesToBeRemoved);

            for (Collaborator currentCoPI : currentGrantEntry.getValue()) {
                currentCoPI.getCollaboratorActivities().remove(currentGrant);
                if (currentCoPI.getCollaboratorActivities().isEmpty()) {
                    nodesToBeRemoved.add(currentCoPI);
                }
            }
        }
    }
    nodes.removeAll(nodesToBeRemoved);

}

From source file:edu.jhuapl.openessence.datasource.jdbc.entry.JdbcOeDataEntrySource.java

/**
 * Inserts a parent record into the database
 *
 * @param tableAwareQueryRecord Record to add at the parent table level
 * @param ignoreSpecialSql      the flag to ignore specialSql definitions in the groovy def file. In general, set
 *                              false during add* and set true during update*
 * @param FK_VAL_MAP            map that enables passing the parent's pk values as fk's to the children
 * @return The primary keys with values for an inserted "parent" record. Null is returned for children records.
 * @throws OeDataSourceAccessException if error occurs at database level
 * @throws OeDataSourceException       if error occurs
 *///from  w  w  w.j  av a 2s.  com
private Map<String, Object> addQueryRecord(TableAwareQueryRecord tableAwareQueryRecord,
        boolean ignoreSpecialSql, Map<String, Object> FK_VAL_MAP)
        throws OeDataSourceAccessException, OeDataSourceException {

    Map<String, Dimension> editDims = tableAwareQueryRecord.getEditDimensions();
    Set<String> autoGenDimIds = this.getAutoGenMap().keySet();

    Map<String, DimensionBean> specialSqlMap = this.getSpecialSqlMap();
    Set<String> specialSqlIds = specialSqlMap.keySet();

    Map<String, Object> vals = tableAwareQueryRecord.getValues();

    Set<String> dimensionIds = editDims.keySet();

    // remove auto-generated dimensions from the dimension list we'll loop over
    dimensionIds.removeAll(autoGenDimIds);
    if (!ignoreSpecialSql) {
        // set the values of specialsqldimensions with their 'special sql'
        for (String sqlDimId : specialSqlIds) {
            vals.put(sqlDimId, specialSqlMap.get(sqlDimId).getSpecialSql());
        }
    }

    //FK-val map. Used to pass PKs to children for use as FKs
    for (String sqlDimId : FK_VAL_MAP.keySet()) {
        vals.put(sqlDimId, FK_VAL_MAP.get(sqlDimId));
    }

    String[] dimIdArray = dimensionIds.toArray(new String[dimensionIds.size()]);
    List<String> dimIdList = (Arrays.asList(dimIdArray));
    // sorting ensures consistent ordering to utilize efficiencies of PreparedStatements
    Collections.sort(dimIdList);
    return editableInsertQuery(tableAwareQueryRecord.getTableName(), ignoreSpecialSql, dimIdList, editDims,
            vals);
}

From source file:com.yahoo.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl.java

/**
 * Rank brokers by available capacity, or load percentage, based on placement strategy:
 *
 * - Available capacity for weighted random selection (weightedRandomSelection): ranks ResourceUnits units based on
 * estimation of their capacity which is basically how many bundles each ResourceUnit is able can handle with its
 * available resources (CPU, memory, network, etc);
 *
 * - Load percentage for least loaded server (leastLoadedServer): ranks ResourceUnits units based on estimation of
 * their load percentage which is basically how many percent of resource is allocated which is
 * max(resource_actually_used, resource_quota)
 *
 * If we fail to collect the Load Reports OR fail to process them for the first time, it means the leader does not
 * have enough information to make a decision so we set it to ready when we collect and process the load reports
 * successfully the first time.//from www.  ja  v a2s . co  m
 */
private synchronized void doLoadRanking() {
    ResourceUnitRanking.setCpuUsageByMsgRate(this.realtimeCpuLoadFactor);
    String hostname = pulsar.getAdvertisedAddress();
    String strategy = this.getLoadBalancerPlacementStrategy();
    log.info("doLoadRanking - load balancing strategy: {}", strategy);
    if (!currentLoadReports.isEmpty()) {
        synchronized (resourceUnitRankings) {
            Map<Long, Set<ResourceUnit>> newSortedRankings = Maps.newTreeMap();
            Map<ResourceUnit, ResourceUnitRanking> newResourceUnitRankings = new HashMap<>();

            for (Map.Entry<ResourceUnit, LoadReport> entry : currentLoadReports.entrySet()) {
                ResourceUnit resourceUnit = entry.getKey();
                LoadReport loadReport = entry.getValue();

                // calculate rankings
                Set<String> loadedBundles = loadReport.getBundles();
                Set<String> preAllocatedBundles = null;
                if (resourceUnitRankings.containsKey(resourceUnit)) {
                    preAllocatedBundles = resourceUnitRankings.get(resourceUnit).getPreAllocatedBundles();
                    preAllocatedBundles.removeAll(loadedBundles);
                } else {
                    preAllocatedBundles = new HashSet<>();
                }
                ResourceQuota allocatedQuota = getTotalAllocatedQuota(loadedBundles);
                ResourceQuota preAllocatedQuota = getTotalAllocatedQuota(preAllocatedBundles);
                ResourceUnitRanking ranking = new ResourceUnitRanking(loadReport.getSystemResourceUsage(),
                        loadedBundles, allocatedQuota, preAllocatedBundles, preAllocatedQuota);
                newResourceUnitRankings.put(resourceUnit, ranking);

                // generated sorted ranking
                double loadPercentage = ranking.getEstimatedLoadPercentage();
                long maxCapacity = ranking.estimateMaxCapacity(
                        pulsar.getLocalZkCacheService().getResourceQuotaCache().getDefaultQuota());
                long finalRank = 0;
                if (strategy.equals(LOADBALANCER_STRATEGY_LLS)) {
                    finalRank = (long) loadPercentage;
                } else {
                    double idleRatio = (100 - loadPercentage) / 100;
                    finalRank = (long) (maxCapacity * idleRatio * idleRatio);
                }

                if (!newSortedRankings.containsKey(finalRank)) {
                    newSortedRankings.put(finalRank, new HashSet<ResourceUnit>());
                }
                newSortedRankings.get(finalRank).add(entry.getKey());
                if (log.isDebugEnabled()) {
                    log.debug("Added Resource Unit [{}] with Rank [{}]", entry.getKey().getResourceId(),
                            finalRank);
                }

                // update metrics
                if (resourceUnit.getResourceId().contains(hostname)) {
                    updateLoadBalancingMetrics(hostname, finalRank, ranking);
                }
            }
            this.sortedRankings.set(newSortedRankings);
            this.resourceUnitRankings = newResourceUnitRankings;
        }
    } else {
        log.info("Leader broker[{}] No ResourceUnits to rank this run, Using Old Ranking",
                pulsar.getWebServiceAddress());
    }
}

From source file:com.ephesoft.dcma.da.dao.hibernate.BatchInstanceDaoImpl.java

@Override
public List<BatchInstance> getBatchInstancesByBatchNameOrId(final String searchString,
        final Set<String> userRoles) {
    EphesoftCriteria criteria = criteria();

    List<BatchInstance> batchInstances = new ArrayList<BatchInstance>();

    Set<String> batchClassIdentifiers = batchClassGroupsDao.getBatchClassIdentifierForUserRoles(userRoles);

    String searchStringLocal = searchString.replaceAll("%", "\\\\%");
    Criterion nameLikeCriteria = Restrictions.like(BATCH_NAME, "%" + searchStringLocal + "%");
    Criterion idLikeCriteria = Restrictions.like(BATCH_INSTANCE_IDENTIFIER, "%" + searchStringLocal + "%");

    LogicalExpression searchCriteria = Restrictions.or(nameLikeCriteria, idLikeCriteria);
    criteria.add(searchCriteria);/*  w w  w.  ja v  a 2  s.c om*/

    // Fixed for JIRA Issues - 7645,7761,7768.
    batchClassIdentifiers = batchClassGroupsDao.getBatchClassIdentifierForUserRoles(userRoles);
    Set<String> batchInstanceIdentifierSet = batchInstanceGroupsDao
            .getBatchInstanceIdentifiersExceptUserRoles(userRoles);
    Set<String> batchInstanceIdentifiers = batchInstanceGroupsDao
            .getBatchInstanceIdentifierForUserRoles(userRoles);
    batchInstanceIdentifierSet.removeAll(batchInstanceIdentifiers);

    if ((null != batchClassIdentifiers && batchClassIdentifiers.size() > 0)
            || (null != batchInstanceIdentifiers && batchInstanceIdentifiers.size() > 0)) {
        criteria.createAlias(BATCH_CLASS, BATCH_CLASS);
        // criteria.add(Restrictions.in(BATCH_CLASS_IDENTIFIER, batchClassIdentifiers));
        // Fixed for JIRA ID - 6238. Order by default is set to descending.
        Order defaultOrder = new Order(BatchInstanceProperty.ID, false);
        batchInstances = find(criteria, defaultOrder);
        if (batchInstances != null && !batchInstances.isEmpty()) {
            batchInstances = updateBatchInstanceList(batchInstances, batchClassIdentifiers,
                    batchInstanceIdentifiers, batchInstanceIdentifierSet, 0, batchInstances.size());
        }
    }
    return batchInstances;
}

From source file:de.steilerdev.myVerein.server.model.Event.java

/**
 * This function updates the list of invited user of this event
 * @param divisionRepository An active division repository used to expand the division set
 *///from w ww .j a v a  2s .  c  o m
public void updateInvitedUser(DivisionRepository divisionRepository) {
    if (invitedDivision == null || (invitedDivision = Division.getExpandedSetOfDivisions(invitedDivision,
            divisionRepository)) == null) {
        logger.error("Unable to update invited user, because invited divisions are null!");
    } else {
        logger.info("Updating invited user for event " + this);
        Set<String> oldInvitedUser = invitedUser == null ? new HashSet<>() : invitedUser.keySet();
        HashSet<String> newInvitedUser = new HashSet<>();
        invitedDivision.stream().forEach(div -> newInvitedUser.addAll(div.getMemberList()));

        if (oldInvitedUser.isEmpty() || newInvitedUser.isEmpty()) {
            logger.debug("Old set of invited user or new set of invited user is empty");
            invitedUser = new HashMap<>();
            if (oldInvitedUser.isEmpty() && !newInvitedUser.isEmpty()) {
                logger.debug("Old set of invited user is empty and new set of invited user is not empty");
                newInvitedUser.stream().forEach(userID -> invitedUser.put(userID, EventStatus.PENDING));
            } else if (newInvitedUser.isEmpty() && !oldInvitedUser.isEmpty()) {
                logger.debug("New set of invited user is empty and old set of invited user is not empty");
                oldInvitedUser.stream().forEach(userID -> invitedUser.put(userID, EventStatus.REMOVED));
                lastChanged = LocalDateTime.now();
            }
        } else {
            logger.debug("Old and new set of invited user is not empty");
            oldInvitedUser.removeAll(newInvitedUser);
            oldInvitedUser.stream().forEach(userID -> invitedUser.put(userID, EventStatus.REMOVED));
            newInvitedUser.stream().forEach(userID -> invitedUser.putIfAbsent(userID, EventStatus.PENDING));
            lastChanged = LocalDateTime.now();
        }
    }
}