Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

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

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

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

Usage

From source file:org.jenkins.plugins.lockableresources.LockableResourcesManager.java

/**
 * Checks if there are enough resources available to satisfy the requirements specified
 * within requiredResources and returns the necessary available resources.
 * If not enough resources are available, returns null.
 *///from ww  w  . j a v  a2s . co  m
public synchronized Set<LockableResource> checkResourcesAvailability(
        List<LockableResourcesStruct> requiredResourcesList, @Nullable PrintStream logger,
        @Nullable List<String> lockedResourcesAboutToBeUnlocked) {

    List<LockableResourcesCandidatesStruct> requiredResourcesCandidatesList = new ArrayList<>();

    // Build possible resources for each requirement
    for (LockableResourcesStruct requiredResources : requiredResourcesList) {
        // get possible resources
        int requiredAmount = 0; // 0 means all
        List<LockableResource> candidates = new ArrayList<>();
        if (requiredResources.label != null && requiredResources.label.isEmpty()) {
            candidates.addAll(requiredResources.required);
        } else {
            candidates.addAll(getResourcesWithLabel(requiredResources.label, null));
            if (requiredResources.requiredNumber != null) {
                try {
                    requiredAmount = Integer.parseInt(requiredResources.requiredNumber);
                } catch (NumberFormatException e) {
                    requiredAmount = 0;
                }
            }
        }

        if (requiredAmount == 0) {
            requiredAmount = candidates.size();
        }

        requiredResourcesCandidatesList.add(new LockableResourcesCandidatesStruct(candidates, requiredAmount));
    }

    // Process freed resources
    int totalSelected = 0;

    for (LockableResourcesCandidatesStruct requiredResources : requiredResourcesCandidatesList) {
        // start with an empty set of selected resources
        List<LockableResource> selected = new ArrayList<LockableResource>();

        // some resources might be already locked, but will be freed.
        // Determine if these resources can be reused
        if (lockedResourcesAboutToBeUnlocked != null) {
            for (LockableResource candidate : requiredResources.candidates) {
                if (selected.size() >= requiredResources.requiredAmount) {
                    break;
                }
                if (lockedResourcesAboutToBeUnlocked.contains(candidate.getName())) {
                    selected.add(candidate);
                }
            }
        }

        totalSelected += selected.size();
        requiredResources.selected = selected;
    }

    // if none of the currently locked resources can be reused,
    // this context is not suitable to be continued with
    if (lockedResourcesAboutToBeUnlocked != null && totalSelected == 0) {
        return null;
    }

    // Find remaining resources
    Set<LockableResource> allSelected = new HashSet<>();

    for (LockableResourcesCandidatesStruct requiredResources : requiredResourcesCandidatesList) {
        List<LockableResource> candidates = requiredResources.candidates;
        List<LockableResource> selected = requiredResources.selected;
        int requiredAmount = requiredResources.requiredAmount;

        // Try and re-use as many previously selected resources first
        List<LockableResource> alreadySelectedCandidates = new ArrayList<>(candidates);
        alreadySelectedCandidates.retainAll(allSelected);
        for (LockableResource rs : alreadySelectedCandidates) {
            if (selected.size() >= requiredAmount) {
                break;
            }
            if (!rs.isReserved() && !rs.isLocked()) {
                selected.add(rs);
            }
        }

        candidates.removeAll(alreadySelectedCandidates);
        for (LockableResource rs : candidates) {
            if (selected.size() >= requiredAmount) {
                break;
            }
            if (!rs.isReserved() && !rs.isLocked()) {
                selected.add(rs);
            }
        }

        if (selected.size() < requiredAmount) {
            if (logger != null) {
                logger.println("Found " + selected.size()
                        + " available resource(s). Waiting for correct amount: " + requiredAmount + ".");
            }
            return null;
        }

        allSelected.addAll(selected);
    }

    return allSelected;
}

From source file:opennlp.tools.apps.object_dedup.SimilarityAccessorBase.java

public boolean applyBothSidesRule(String name1, String name2) {
    List<String> name1Tokens = TextProcessor.fastTokenize(name1.toLowerCase(), false);
    List<String> name2Tokens = TextProcessor.fastTokenize(name2.toLowerCase(), false);
    // get unique names
    List<String> name1TokensC = new ArrayList<String>(name1Tokens),
            name2TokensC = new ArrayList<String>(name2Tokens);
    ;//from w w  w  . j ava  2 s . co  m
    name1TokensC.removeAll(name2Tokens);
    name2TokensC.removeAll(name1Tokens);
    // get all unique names
    name1TokensC.addAll(name2TokensC);

    name1TokensC.retainAll(namesBothSides);
    if (name1TokensC.size() > 0)
        return false;
    else
        return true;
}

From source file:ubc.pavlab.aspiredb.server.dao.VariantDaoBaseImpl.java

private List<Long> getFilteredIds(Set<AspireDbFilterConfig> filters) {
    Iterator<AspireDbFilterConfig> iterator = filters.iterator();
    AspireDbFilterConfig filterConfig = iterator.next();
    // First iteration
    List<Long> variantIds = findIds(filterConfig);

    while (iterator.hasNext()) {
        filterConfig = iterator.next();/*from  w  ww. j a va2 s .c  o  m*/
        List<Long> ids = findIds(filterConfig);

        // intersect results
        variantIds.retainAll(ids);

        // if size is 0 -> stop
        if (variantIds.isEmpty()) {
            break;
        }
    }
    return variantIds;
}

From source file:com.thinkbiganalytics.ingest.TableMergeSyncSupport.java

/**
 * Returns the list of columns that are common to both the source and target tables.
 *
 * <p>The column names are quoted and escaped for use in a SQL query.</p>
 *
 * @param sourceSchema  the name of the source table schema or database
 * @param sourceTable   the name of the source table
 * @param targetSchema  the name of the target table schema or database
 * @param targetTable   the name of the target table
 * @param partitionSpec the partition specifications, or {@code null} if none
 * @return the columns for a SELECT statement
 *///  www.j  a va2s  . com
protected String[] getSelectFields(@Nonnull final String sourceSchema, @Nonnull final String sourceTable,
        @Nonnull final String targetSchema, @Nonnull final String targetTable,
        @Nullable final PartitionSpec partitionSpec) {
    List<String> srcFields = resolveTableSchema(sourceSchema, sourceTable);
    List<String> destFields = resolveTableSchema(targetSchema, targetTable);

    // Find common fields
    destFields.retainAll(srcFields);

    // Eliminate any partition columns
    if (partitionSpec != null) {
        destFields.removeAll(partitionSpec.getKeyNames());
    }
    String[] fields = destFields.toArray(new String[0]);
    for (int i = 0; i < fields.length; i++) {
        fields[i] = HiveUtils.quoteIdentifier(fields[i]);
    }
    return fields;
}

From source file:opennlp.tools.apps.object_dedup.SimilarityAccessorBase.java

public Boolean applyBothSidesRuleEvent(String name1, String name2) {
    List<String> name1Tokens = TextProcessor.fastTokenize(name1.toLowerCase(), false);
    List<String> name2Tokens = TextProcessor.fastTokenize(name2.toLowerCase(), false);
    // get unique names
    List<String> name1TokensC = new ArrayList<String>(name1Tokens),
            name2TokensC = new ArrayList<String>(name2Tokens);
    ;/*  w  w  w. j a  va2  s  .  co m*/
    name1TokensC.removeAll(name2Tokens);
    name2TokensC.removeAll(name1Tokens);
    // get all unique names
    name1TokensC.addAll(name2TokensC);

    name1TokensC.retainAll(namesBothSides);
    name1Tokens.retainAll(name2Tokens);

    if ((name1TokensC.size() > 0 && name1Tokens.size() < 3)
            || (name1TokensC.size() > 1 && name1Tokens.size() < 5)) { // 'mens == men; case !(name1TokensC.size()==2 && (name1TokensC.get(0).indexOf(name1TokensC.get(1))>-1 ||
                                                                                                                              // name1TokensC.get(1).indexOf(name1TokensC.get(0))>-1 ))){
        LOG.info("Found required common word present on one side and not on the other: "
                + name1TokensC.toString()
                + " and less than 3 keywords overlap (or >1 common words and less than 5 overl");
        return false;
    } else
        return true;
}

From source file:ru.codeinside.gses.webui.data.ControlledTasksQuery.java

private TaskQuery createTaskQuery() {
    TaskQuery query = Flash.flash().getProcessEngine().getTaskService().createTaskQuery();
    ((TaskQueryImpl2) query).setIgnoreAssignee(false);
    List<String> resultGroups;
    if (superSupervisor) {
        if (orgGroups == null && empGroups != null) {
            resultGroups = empGroups;/*from  w  w  w . jav  a  2s  . c  o m*/
        } else if (empGroups == null && orgGroups != null) {
            resultGroups = orgGroups;
        } else if (empGroups != null && orgGroups != null) {
            orgGroups.addAll(empGroups);
            resultGroups = orgGroups;
        } else {
            resultGroups = Lists.newArrayListWithExpectedSize(0);
        }
    } else {
        resultGroups = Lists.newArrayListWithExpectedSize(controlledGroups.size());
        resultGroups.addAll(controlledGroups);
        if (orgGroups == null && empGroups != null) {
            resultGroups.retainAll(empGroups);
        } else if (empGroups == null && orgGroups != null) {
            resultGroups.retainAll(orgGroups);
        } else if (empGroups != null && orgGroups != null) {
            orgGroups.addAll(empGroups);
            resultGroups.retainAll(orgGroups);
        }
    }
    if (!resultGroups.isEmpty()) {
        query.taskCandidateGroupIn(resultGroups);
    }
    if (processInstanceId != null) {
        query.processInstanceId(processInstanceId);
    }
    if (type != null) {
        query.processVariableValueEquals(VAR_PROCEDURE_TYPE_NAME, Integer.toString(type.ordinal()));
    }
    if (!StringUtils.isEmpty(serviceId)) {
        query.processVariableValueEquals(VAR_SERVICE_ID, serviceId);
    }
    if (taskKey != null && !taskKey.isEmpty()) {
        query.taskDefinitionKey(taskKey);
    }
    if (procedureId != null && !procedureId.isEmpty()) {
        query.processVariableValueEquals(VAR_PROCEDURE_ID, procedureId);
    }
    if (declarantTypeName != null && declarantTypeValue != null) {
        query.processVariableValueEquals(declarantTypeName, declarantTypeValue);
    }
    if (requester != null && !requester.isEmpty()) {
        query.processVariableValueEquals(VAR_REQUESTER_LOGIN, requester);
    }
    if (fromDate != null) {
        query.taskCreatedAfter(DateUtils.addSeconds(fromDate, -1));
    }
    if (toDate != null) {
        query.taskCreatedBefore(DateUtils.addSeconds(toDate, 1));
    }
    if (overdue) {
        ((TaskQueryImpl2) query).setOverdue(true);
    }
    return query;
}

From source file:mp.platform.cyclone.webservices.utils.server.PaymentHelper.java

/**
 * Lists the possible transfer types for this payment
 *///  ww  w.  j  a  v a 2 s  .  c o  m
public Collection<TransferType> listPossibleTypes(final DoExternalPaymentDTO dto) {
    final String channel = channelHelper.restricted();
    if (StringUtils.isEmpty(channel)) {
        return Collections.emptyList();
    }

    final Member member = WebServiceContext.getMember();
    final ServiceClient client = WebServiceContext.getClient();

    // First, we need a list of existing TTs for the payment
    final TransferTypeQuery query = new TransferTypeQuery();
    query.setResultType(ResultType.LIST);
    query.setContext(TransactionContext.PAYMENT);
    query.setChannel(channel);
    query.setFromOwner(dto.getFrom());
    query.setToOwner(dto.getTo());
    query.setCurrency(dto.getCurrency());
    final List<TransferType> transferTypes = transferTypeService.search(query);

    // Then, restrict according to the web service client permissions
    boolean doPayment = true;
    if (member != null) {
        doPayment = member.equals(dto.getFrom());
    }
    Collection<TransferType> possibleTypes;
    if (doPayment) {
        possibleTypes = fetchService.fetch(client, ServiceClient.Relationships.DO_PAYMENT_TYPES)
                .getDoPaymentTypes();
    } else {
        possibleTypes = fetchService.fetch(client, ServiceClient.Relationships.RECEIVE_PAYMENT_TYPES)
                .getReceivePaymentTypes();
    }
    transferTypes.retainAll(possibleTypes);

    return transferTypes;
}

From source file:org.sakaiproject.poll.service.impl.PollListManagerImpl.java

public List<Poll> findAllPollsForUserAndSitesAndPermission(String userId, String[] siteIds,
        String permissionConstant) {
    if (userId == null || permissionConstant == null) {
        throw new IllegalArgumentException("userId and permissionConstant must be set");
    }/*from  ww  w  . j  a  v  a 2  s  . co m*/
    List<Poll> polls = null;
    // get all allowed sites for this user
    List<String> allowedSites = externalLogic.getSitesForUser(userId, permissionConstant);

    if (siteIds != null && siteIds.length > 0 && !allowedSites.isEmpty()) {
        List<String> requestedSiteIds = Arrays.asList(siteIds);
        // filter down to just the requested ones
        allowedSites.retainAll(requestedSiteIds);
        if (allowedSites.isEmpty()) {
            // no sites to search so EXIT here
            return new ArrayList<Poll>();
        }
        String[] siteIdsToSearch = allowedSites.toArray(new String[allowedSites.size()]);
        Search search = new Search();
        if (siteIdsToSearch.length > 0) {
            search.addRestriction(new Restriction("siteId", siteIdsToSearch));
        }
        if (PollListManager.PERMISSION_VOTE.equals(permissionConstant)) {
            // limit to polls which are open
            Date now = new Date();
            search.addRestriction(new Restriction("voteOpen", now, Restriction.LESS));
            search.addRestriction(new Restriction("voteClose", now, Restriction.GREATER));
        } else {
            // show all polls
        }
        search.addOrder(new Order("creationDate"));
        polls = dao.findBySearch(Poll.class, search);
    }
    if (polls == null) {
        polls = new ArrayList<Poll>();
    }
    return polls;
}

From source file:org.apache.cayenne.wocompat.EOModelHelper.java

public EOModelHelper(URL modelUrl) throws Exception {

    this.modelUrl = modelUrl;
    this.dataMap = new DataMap(findModelName(modelUrl.toExternalForm()));

    // load index file
    List modelIndex = (List) loadModelIndex().get("entities");

    // load entity indices
    entityIndex = new HashMap();
    entityClassIndex = new HashMap();
    entityClientClassIndex = new HashMap();
    entityQueryIndex = new HashMap();

    Iterator it = modelIndex.iterator();
    while (it.hasNext()) {
        Map info = (Map) it.next();
        String name = (String) info.get("name");

        entityIndex.put(name, loadEntityIndex(name));
        entityQueryIndex.put(name, loadQueryIndex(name));
        entityClassIndex.put(name, info.get("className"));
        Map entityPlistMap = entityPListMap(name);

        // get client class information
        Map internalInfo = (Map) entityPlistMap.get("internalInfo");

        if (internalInfo != null) {
            String clientClassName = (String) internalInfo.get("_javaClientClassName");
            entityClientClassIndex.put(name, clientClassName);
        }//  w  w w  .  j a v a  2 s.  c o m
    }

    it = modelIndex.iterator();
    while (it.hasNext()) {
        Map info = (Map) it.next();
        String name = (String) info.get("name");
        Map entityPlistMap = entityPListMap(name);
        List classProperties = (List) entityPlistMap.get("classProperties");
        if (classProperties == null) {
            classProperties = Collections.EMPTY_LIST;
        }

        // get client class information
        Map internalInfo = (Map) entityPlistMap.get("internalInfo");

        List clientClassProperties = (internalInfo != null)
                ? (List) internalInfo.get("_clientClassPropertyNames")
                : null;

        // guard against no internal info and no client class properties
        if (clientClassProperties == null) {
            clientClassProperties = Collections.EMPTY_LIST;
        }

        // there is a bug in EOModeler it sometimes keeps outdated
        // properties in
        // the client property list. This removes them
        clientClassProperties.retainAll(classProperties);

        // remove all properties from the entity properties that are already
        // defined
        // in
        // a potential parent class.
        String parentEntity = (String) entityPlistMap.get("parent");
        while (parentEntity != null) {
            Map parentEntityPListMap = entityPListMap(parentEntity);
            List parentClassProps = (List) parentEntityPListMap.get("classProperties");
            classProperties.removeAll(parentClassProps);
            // get client class information of parent
            Map parentInternalInfo = (Map) parentEntityPListMap.get("internalInfo");

            if (parentInternalInfo != null) {
                List parentClientClassProps = (List) parentInternalInfo.get("_clientClassPropertyNames");
                clientClassProperties.removeAll(parentClientClassProps);
            }

            parentEntity = (String) parentEntityPListMap.get("parent");
        }

        // put back processed properties to the map
        entityPlistMap.put("classProperties", classProperties);
        // add client classes directly for easier access
        entityPlistMap.put("clientClassProperties", clientClassProperties);
    }
}

From source file:org.rhq.enterprise.server.resource.metadata.ResourceMetadataManagerBean.java

/**
 * Updates the database with new child subcategory definitions found in the new resource type. Any definitions
 * common to both will be merged./*from  w w  w  .ja v  a 2 s.c o  m*/
 *
 * @param newType      new resource type containing updated definitions
 * @param existingType old resource type with existing definitions
 */
private void updateChildSubCategories(ResourceType newType, ResourceType existingType) {
    // we'll do the removal of all definitions that are in the existing type but not in the new type
    // once the child resource types have had a chance to stop referencing any old subcategories

    // Easy case: If the existing type did not have any definitions, simply save the new type defs and return
    if (existingType.getChildSubCategories() == null) {
        for (ResourceSubCategory newSubCategory : newType.getChildSubCategories()) {
            log.info("Metadata update: Adding new child SubCategory [" + newSubCategory.getName()
                    + "] to ResourceType [" + existingType.getName() + "]...");
            existingType.addChildSubCategory(newSubCategory);
            entityManager.persist(newSubCategory);
        }
        return;
    }

    // Merge definitions that were already in the existing type and also in the new type
    //
    // First, put the new subcategories in a map for easier access when iterating over the existing ones
    Map<String, ResourceSubCategory> subCategoriesFromNewType = new HashMap<String, ResourceSubCategory>(
            newType.getChildSubCategories().size());
    for (ResourceSubCategory newSubCategory : newType.getChildSubCategories()) {
        subCategoriesFromNewType.put(newSubCategory.getName(), newSubCategory);
    }

    // Second, loop over the sub categories that need to be merged and update and persist them
    List<ResourceSubCategory> mergedSubCategories = new ArrayList<ResourceSubCategory>(
            existingType.getChildSubCategories());
    mergedSubCategories.retainAll(subCategoriesFromNewType.values());
    for (ResourceSubCategory existingSubCat : mergedSubCategories) {
        updateSubCategory(existingSubCat, subCategoriesFromNewType.get(existingSubCat.getName()));
        entityManager.merge(existingSubCat);
    }

    // Persist all new definitions
    List<ResourceSubCategory> newSubCategories = new ArrayList<ResourceSubCategory>(
            newType.getChildSubCategories());
    newSubCategories.removeAll(existingType.getChildSubCategories());
    for (ResourceSubCategory newSubCat : newSubCategories) {
        log.info("Metadata update: Adding new child SubCategory [" + newSubCat.getName() + "] to ResourceType ["
                + existingType.getName() + "]...");
        existingType.addChildSubCategory(newSubCat);
        entityManager.persist(newSubCat);
    }
}