Example usage for java.util Set containsAll

List of usage examples for java.util Set containsAll

Introduction

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

Prototype

boolean containsAll(Collection<?> c);

Source Link

Document

Returns true if this set contains all of the elements of the specified collection.

Usage

From source file:org.mitre.mpf.wfm.service.PipelineServiceImpl.java

private void validateMarkupPipeline(String pipelineName, List<TaskDefinitionRef> taskDefinitions,
        Set<StateDefinition> currentStates) {
    if (taskDefinitions.size() == 1) {
        // There's only one task in the pipeline, and we know it to be markup.
        boolean rValue = true;
        Set<StateDefinitionRef> requiredStates = requiredTaskStates
                .get(StringUtils.upperCase(taskDefinitions.get(0).getName()));
        if (!currentStates.containsAll(requiredStates)) {
            log.error("{}: The states for {} are not satisfied. Current: {}. Required: {}.", pipelineName,
                    taskDefinitions.get(0).getName(), currentStates, requiredStates);
            throw new InvalidTaskWfmProcessingException(new StringBuilder().append(pipelineName)
                    .append(": The states for ").append(taskDefinitions.get(0).getName())
                    .append(" are not satisfied. Current: ").append(currentStates).append(". Required: ")
                    .append(requiredStates).append(".").toString());
        }/*from www  .  j  a  v  a2 s .c  o m*/
    } else {
        log.error("{}: No tasks may follow a markup task of {}.", pipelineName,
                taskDefinitions.get(0).getName());
        throw new InvalidTaskWfmProcessingException(
                new StringBuilder().append(pipelineName).append(": No tasks may follow a markup task of ")
                        .append(taskDefinitions.get(0).getName()).append(".").toString());
    }
}

From source file:uk.ac.ebi.mdk.domain.entity.reaction.AbstractReaction.java

/**
 * Check equality of reactions based on state. Reactions are considered
 * equals if their reactants and products (coefficients and compartments)
 * are equals regardless of the side they reside on. For example A + B <-> C
 * + D is considered equals to C + D <-> A + B. The participant
 * stoichiometric coefficients and compartments are also checked.
 * <p/>//  w  ww .  j  a v  a2 s  .  co m
 * To accomplish this the reactionParticipants and copied, sorted and then a
 * hash for each side (four total) is made. Duplicate hashes are then
 * removed via the {@See Set} interface and the query (this) and the other
 * (obj) sides are tested for coefficient, compartment and finally molecule
 * similarity
 *
 * @param obj The other object to test equality with
 * @return Whether the objects are considered equals
 */
@Override
public boolean equals(Object obj) {

    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }

    if (!super.equals(obj)) {
        return false;
    }

    final AbstractReaction<P> other = (AbstractReaction<P>) obj;

    if (this.generic == false && other.generic == false) {

        map.clear();
        int queryReactantHash = getParticipantHashCode(this.reactants);
        int queryProductHash = getParticipantHashCode(this.products);
        map.clear();
        int otherReactantHash = getParticipantHashCode(other.reactants);
        int otherProductHash = getParticipantHashCode(other.products);

        /* calculate the hashes for these all the reaction sides and flattern into a hashset to test the length */
        Set hashes = new HashSet<Integer>(
                Arrays.asList(queryReactantHash, queryProductHash, otherReactantHash, otherProductHash));

        Set<P> queryReactants = new HashSet<P>(this.reactants);
        Set<P> queryProducts = new HashSet<P>(this.products);
        Set<P> otherReactants = new HashSet<P>(other.reactants);
        Set<P> otherProducts = new HashSet<P>(other.products);

        /* Check the correct number of side */
        if (hashes.size() != 2) {
            // not handling cases where reactants and products are the same.. could just be same hashcode
            if (hashes.size() == 1) {
                if (queryReactants.containsAll(otherReactants) && queryReactants.containsAll(queryProducts)
                        && queryProducts.containsAll(otherProducts)) {
                    return true;
                }
                throw new UnsupportedOperationException(
                        "Reaction.equals(): Unresolvable reaction comparision [1]\n\t" + this + "\n\t" + other);
            }
            return false;
        }

        // these are sorted so can do direct equals on the sets
        if (queryReactantHash == otherReactantHash) {
            return queryReactants.containsAll(otherReactants) && queryProducts.containsAll(otherProducts);
        } else if (queryReactantHash == otherProductHash) {
            return queryReactants.containsAll(otherProducts) && queryProducts.containsAll(otherReactants);
        } else {
            return false; // this.reac == this.prod and other.reac == other.prod... and so must be false (2x hashe values)
        }

    } else {
        LOGGER.info("Using generic comparisson");
        // XXX May be a quicker way but for not this works
        if (genericEquals(this.reactants, other.reactants) && genericEquals(this.products, other.products)) {
            return true;
        }
        if (genericEquals(this.reactants, other.products) && genericEquals(this.products, other.reactants)) {
            return true;
        }
    }

    return false;

}

From source file:org.cloudfoundry.identity.uaa.oauth.UserManagedAuthzApprovalHandler.java

@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {

    String flag = authorizationRequest.getApprovalParameters().get(approvalParameter);
    boolean userApproval = flag != null && flag.toLowerCase().equals("true");

    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up user approved authorizations for ");
        builder.append("client_id=").append(authorizationRequest.getClientId());
        builder.append(" and username=").append(userAuthentication.getName());
        logger.debug(builder.toString());
    }//from   w  w w .  jav  a 2s .  co  m

    Collection<String> requestedScopes = authorizationRequest.getScope();

    // Factor in auto approved scopes
    Set<String> autoApprovedScopes = new HashSet<>();
    BaseClientDetails client = (BaseClientDetails) clientDetailsService
            .retrieve(authorizationRequest.getClientId());
    if (client != null && requestedScopes != null) {
        autoApprovedScopes.addAll(client.getAutoApproveScopes());
        autoApprovedScopes = UaaTokenUtils.retainAutoApprovedScopes(requestedScopes, autoApprovedScopes);
    }
    //translate scope to user scopes - including wild cards

    if (userApproval) {
        // Store the scopes that have been approved / denied
        Date expiry = computeExpiry();

        // Get the approved scopes, calculate the denied scope
        Map<String, String> approvalParameters = authorizationRequest.getApprovalParameters();
        Set<String> approvedScopes = new HashSet<>();
        approvedScopes.addAll(autoApprovedScopes);
        boolean foundUserApprovalParameter = false;
        for (String approvalParameter : approvalParameters.keySet()) {
            if (approvalParameter.startsWith(SCOPE_PREFIX)) {
                approvedScopes.add(approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length()));
                foundUserApprovalParameter = true;
            }
        }

        if (foundUserApprovalParameter) {
            authorizationRequest.setScope(approvedScopes);

            for (String requestedScope : requestedScopes) {
                if (approvedScopes.contains(requestedScope)) {
                    Approval approval = new Approval().setUserId(getUserId(userAuthentication))
                            .setClientId(authorizationRequest.getClientId()).setScope(requestedScope)
                            .setExpiresAt(expiry).setStatus(APPROVED);
                    approvalStore.addApproval(approval);
                } else {
                    Approval approval = new Approval().setUserId(getUserId(userAuthentication))
                            .setClientId(authorizationRequest.getClientId()).setScope(requestedScope)
                            .setExpiresAt(expiry).setStatus(DENIED);
                    approvalStore.addApproval(approval);
                }
            }

        } else { // Deny all except auto approved scopes
            authorizationRequest.setScope(autoApprovedScopes);

            for (String requestedScope : requestedScopes) {
                if (!autoApprovedScopes.contains(requestedScope)) {
                    Approval approval = new Approval().setUserId(getUserId(userAuthentication))
                            .setClientId(authorizationRequest.getClientId()).setScope(requestedScope)
                            .setExpiresAt(expiry).setStatus(DENIED);
                    approvalStore.addApproval(approval);
                }
            }
        }

        if (userAuthentication.isAuthenticated()) {
            return true;
        }

    } else {
        // Find the stored approvals for that user and client
        List<Approval> userApprovals = approvalStore.getApprovals(getUserId(userAuthentication),
                authorizationRequest.getClientId());

        // Look at the scopes and see if they have expired
        Set<String> validUserApprovedScopes = new HashSet<>();
        Set<String> approvedScopes = new HashSet<>();
        approvedScopes.addAll(autoApprovedScopes);
        validUserApprovedScopes.addAll(autoApprovedScopes);
        Date today = new Date();
        for (Approval approval : userApprovals) {
            if (approval.getExpiresAt().after(today)) {
                validUserApprovedScopes.add(approval.getScope());
                if (approval.getStatus() == APPROVED) {
                    approvedScopes.add(approval.getScope());
                }
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes);
        }

        // If the requested scopes have already been acted upon by the user,
        // this request is approved
        if (validUserApprovedScopes.containsAll(requestedScopes) && userAuthentication.isAuthenticated()) {
            approvedScopes = UaaTokenUtils.retainAutoApprovedScopes(requestedScopes, approvedScopes);
            // Set only the scopes that have been approved by the user
            authorizationRequest.setScope(approvedScopes);
            return true;
        }
    }

    return false;
}

From source file:tajo.worker.TestWorker.java

public void assertSubmittedAndReported(TajoMaster master, Set<QueryUnitAttemptId> submitted)
        throws InterruptedException {
    Set<QueryUnitAttemptId> reported = Sets.newHashSet();
    Collection<TaskStatusProto> list = master.getProgressQueries();
    int i = 0;//from  www .  j ava 2 s  . c  o m
    while (i < 10) { // waiting for the report messages 
        LOG.info("Waiting for receiving the report messages");
        Thread.sleep(1000);
        list = master.getProgressQueries();
        reported.clear();
        for (TaskStatusProto ips : list) {
            // Because this query is to store, it should have the statistics info 
            // of the store data. The below 'assert' examines the existence of 
            // the statistics info.
            if (ips.getStatus() == QueryStatus.QUERY_FINISHED) {
                reported.add(new QueryUnitAttemptId(ips.getId()));
            }
        }

        if (reported.containsAll(submitted)) {
            break;
        }

        i++;
    }
    LOG.info("reported: " + reported);
    LOG.info("submitted: " + submitted);
    assertTrue(reported.containsAll(submitted));
}

From source file:org.mitre.mpf.wfm.service.PipelineServiceImpl.java

private void validateDetectionPipeline(String pipelineName, List<TaskDefinitionRef> taskDefinitions,
        Set<StateDefinition> currentStates) {
    if (taskDefinitions.size() == 1) {
        // There's only one task in the pipeline, and we know it to be detection.
        boolean rValue = true;
        Set<StateDefinitionRef> requiredStates = requiredTaskStates
                .get(StringUtils.upperCase(taskDefinitions.get(0).getName()));
        if (!currentStates.containsAll(requiredStates)) {
            log.error("{}: The states for {} are not satisfied. Current: {}. Required: {}.", pipelineName,
                    taskDefinitions.get(0).getName(), currentStates, requiredStates);
            throw new InvalidTaskWfmProcessingException(new StringBuilder().append(pipelineName)
                    .append(": The states for ").append(taskDefinitions.get(0).getName())
                    .append(" are not satisfied. Current: ").append(currentStates).append(". Required: ")
                    .append(requiredStates).append(".").toString());
        }//from w  w w  .  j a v a2 s  .  c o m
    } else if (getTask(taskDefinitions.get(0)).getActions().size() > 1) {
        // There's more than one task, and the number of actions in the first task exceeds 1.
        log.error("{}: No tasks may follow the multi-detection task of {}.", pipelineName,
                taskDefinitions.get(0).getName());
        throw new InvalidTaskWfmProcessingException(new StringBuilder().append(pipelineName)
                .append(": No tasks may follow the multi-detection task of ")
                .append(taskDefinitions.get(0).getName()).append(".").toString());
    } else if (getTask(taskDefinitions.get(1)) == null) {
        // At this point, we've determined there's at least one more task. The next task name must exist.
        log.error("{}: Task with name {} does not exist.", pipelineName, taskDefinitions.get(1).getName());
        throw new InvalidTaskWfmProcessingException(
                new StringBuilder().append(pipelineName).append(": Task with name ")
                        .append(taskDefinitions.get(1).getName()).append(" does not exist.").toString());
    } else {
        currentStates.addAll(providedTaskStates.get(StringUtils.upperCase(taskDefinitions.get(0).getName())));
        ActionType nextTaskType = getTaskType(taskDefinitions.get(1));
        switch (nextTaskType) {
        case DETECTION:
            currentStates.clear(); // If the next task is detection-based, we should disregard the current states as we're downselecting.
            validateDetectionPipeline(pipelineName, taskDefinitions.subList(1, taskDefinitions.size()),
                    currentStates);
            return;
        case MARKUP:
            validateMarkupPipeline(pipelineName, taskDefinitions.subList(1, taskDefinitions.size()),
                    currentStates);
            return;
        default:
            log.error("{}: {} is a detection task and may not be followed by {}.", pipelineName,
                    taskDefinitions.get(0).getName(), taskDefinitions.get(1).getName());
            throw new InvalidTaskWfmProcessingException(new StringBuilder().append(pipelineName).append(": ")
                    .append(taskDefinitions.get(0).getName())
                    .append(" is a detection task and may not be followed by ")
                    .append(taskDefinitions.get(1).getName()).append(".").toString());
        }
    }
}

From source file:org.apache.ranger.plugin.model.validation.RangerPolicyValidator.java

/**
 * Returns the subset of hierarchies all of whose mandatory resources were found in policy's resource set.  candidate hierarchies are expected to have passed
 * <code>filterHierarchies_hierarchyHasAllPolicyResources</code> check first.
 * @param policyResources/*from w w w  .ja  v a  2s.  co  m*/
 * @param hierarchies
 * @param defHelper
 * @return
 */
Set<List<RangerResourceDef>> filterHierarchies_mandatoryResourcesSpecifiedInPolicy(Set<String> policyResources,
        Set<List<RangerResourceDef>> hierarchies, RangerServiceDefHelper defHelper) {

    // helper function skipping sanity checks of getting null arguments passed
    Set<List<RangerResourceDef>> result = new HashSet<List<RangerResourceDef>>(hierarchies.size());
    for (List<RangerResourceDef> aHierarchy : hierarchies) {
        Set<String> mandatoryResources = defHelper.getMandatoryResourceNames(aHierarchy);
        if (policyResources.containsAll(mandatoryResources)) {
            result.add(aHierarchy);
        }
    }
    return result;
}

From source file:org.apache.hadoop.hive.ql.optimizer.SimpleFetchOptimizer.java

private boolean isConvertible(FetchData fetch, Operator<?> operator, Set<Operator<?>> traversed) {
    if (operator instanceof ReduceSinkOperator || operator instanceof CommonJoinOperator
            || operator instanceof ScriptOperator) {
        return false;
    }//from   w w w.  ja v a 2s .  c  o m

    if (operator instanceof FilterOperator) {
        fetch.setFiltered(true);
    }

    if (!traversed.add(operator)) {
        return true;
    }
    if (operator.getNumChild() == 0) {
        if (operator instanceof FileSinkOperator) {
            fetch.fileSink = operator;
            return true;
        }
        return false;
    }
    for (Operator<?> child : operator.getChildOperators()) {
        if (!traversed.containsAll(child.getParentOperators())) {
            continue;
        }
        if (!isConvertible(fetch, child, traversed)) {
            return false;
        }
    }
    return true;
}

From source file:org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager.java

protected void checkAddLabelsToNode(Map<NodeId, Set<String>> addedLabelsToNode) throws IOException {
    if (null == addedLabelsToNode || addedLabelsToNode.isEmpty()) {
        return;/*from   w ww. j av a  2s  .  c  om*/
    }

    // check all labels being added existed
    Set<String> knownLabels = labelCollections.keySet();
    for (Entry<NodeId, Set<String>> entry : addedLabelsToNode.entrySet()) {
        NodeId nodeId = entry.getKey();
        Set<String> labels = entry.getValue();

        if (!knownLabels.containsAll(labels)) {
            String msg = "Not all labels being added contained by known " + "label collections, please check"
                    + ", added labels=[" + StringUtils.join(labels, ",") + "]";
            LOG.error(msg);
            throw new IOException(msg);
        }

        // In YARN-2694, we temporarily disable user add more than 1 labels on a
        // same host
        if (!labels.isEmpty()) {
            Set<String> newLabels = new HashSet<String>(getLabelsByNode(nodeId));
            newLabels.addAll(labels);
            // we don't allow number of labels on a node > 1 after added labels
            if (newLabels.size() > 1) {
                String msg = String.format("%d labels specified on host=%s after add labels to node"
                        + ", please note that we do not support specifying multiple"
                        + " labels on a single host for now.", newLabels.size(), nodeId.getHost());
                LOG.error(msg);
                throw new IOException(msg);
            }
        }
    }
}

From source file:org.jahia.services.sites.JahiaSitesService.java

public boolean updateSystemSiteLanguages(JahiaSite site, JCRSessionWrapper session) {
    if (!site.getSiteKey().equals(SYSTEM_SITE_KEY)) {
        try {/*from w  w  w . j ava2s .  c o m*/
            JahiaSite jahiaSite = getSiteByKey(JahiaSitesService.SYSTEM_SITE_KEY, session);
            // update the system site only if it does not yet contain at least one of the site languages
            Set<String> jahiaSiteLanguages = new HashSet<String>(jahiaSite.getLanguages());

            Set<String> siteLanguages = new HashSet<>(site.getLanguages());
            siteLanguages.addAll(site.getInactiveLanguages());

            if (!jahiaSiteLanguages.containsAll(siteLanguages)) {
                jahiaSiteLanguages.addAll(siteLanguages);
                jahiaSite.setLanguages(jahiaSiteLanguages);
                return true;
            }
        } catch (PathNotFoundException e) {
            logger.debug(e.getMessage(), e);
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return false;
}

From source file:org.kuali.kra.budget.rates.BudgetRatesServiceImpl.java

@SuppressWarnings("unchecked")
protected boolean areBudgetRatesOutOfSyncWithInsttituteRates(List instituteRates, List budgetRates) {
    Set<String> instituteRateKeys = storeAllKeys((List<AbstractInstituteRate>) instituteRates);
    Set<String> budgetRateKeys = storeAllKeys((List<AbstractInstituteRate>) budgetRates);

    return !instituteRateKeys.containsAll(budgetRateKeys);
}