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:com.linkedin.pinot.common.partition.PartitionAssignmentGeneratorTest.java

private void verifyPartitionAssignmentFromIdealState(TableConfig tableConfig, IdealState idealState,
        int numPartitions) {
    TestPartitionAssignmentGenerator partitionAssignmentGenerator = new TestPartitionAssignmentGenerator(
            _mockHelixManager);/*from  w  w w . j av a  2 s  . c  o m*/
    PartitionAssignment partitionAssignmentFromIdealState = partitionAssignmentGenerator
            .getPartitionAssignmentFromIdealState(tableConfig, idealState);
    Assert.assertEquals(tableConfig.getTableName(), partitionAssignmentFromIdealState.getTableName());
    Assert.assertEquals(partitionAssignmentFromIdealState.getNumPartitions(), numPartitions);
    // check that latest segments are honoring partition assignment
    Map<String, LLCSegmentName> partitionIdToLatestLLCSegment = partitionAssignmentGenerator
            .getPartitionToLatestSegments(idealState);
    for (Map.Entry<String, LLCSegmentName> entry : partitionIdToLatestLLCSegment.entrySet()) {
        Set<String> idealStateInstances = idealState.getInstanceStateMap(entry.getValue().getSegmentName())
                .keySet();
        List<String> partitionAssignmentInstances = partitionAssignmentFromIdealState
                .getInstancesListForPartition(entry.getKey());
        Assert.assertEquals(idealStateInstances.size(), partitionAssignmentInstances.size());
        Assert.assertTrue(idealStateInstances.containsAll(partitionAssignmentInstances));
    }
}

From source file:it.cnr.icar.eric.server.plugin.RequestInterceptorManager.java

private List<RequestInterceptor> getApplicablePlugins(ServerRequestContext context) throws RegistryException {
    List<RequestInterceptor> applicablePlugins = new ArrayList<RequestInterceptor>();

    try {//  w w w .jav  a 2 s .c o  m
        if (getInterceptors().size() > 0) {
            @SuppressWarnings({ "static-access", "unused" })
            String requestAction = bu.getActionFromRequest(context.getCurrentRegistryRequest());

            //Get roles associated with user associated with this RequestContext
            Set<?> subjectRoles = ServerCache.getInstance().getRoles(context);

            //Now get those RequestInterceptors whose roles are a proper subset of subjectRoles
            Iterator<RequestInterceptor> iter = getInterceptors().iterator();
            while (iter.hasNext()) {
                RequestInterceptor interceptor = iter.next();
                Set<?> interceptorRoles = interceptor.getRoles();
                @SuppressWarnings("unused")
                Set<?> interceptorActions = interceptor.getActions();
                if ((subjectRoles.containsAll(interceptorRoles))) {
                    applicablePlugins.add(interceptor);
                }
            }
        }
    } catch (JAXRException e) {
        throw new RegistryException(e);
    }

    return applicablePlugins;
}

From source file:org.slc.sli.api.security.context.ContextValidator.java

/**
* Validates entities, based upon entity definition and entity ids to validate.
*
* @param def - Definition of entities to validate
* @param ids - Collection of ids of entities to validate
* @param isTransitive - Determines whether validation is through another entity type
*
* @throws APIAccessDeniedException - When entities cannot be accessed
*//*www  . jav a  2  s.co  m*/
public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive)
        throws APIAccessDeniedException {
    LOG.debug(">>>ContextValidator.validateContextToEntities()");
    LOG.debug("  def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE));
    LOG.debug("  ids: {}", (ids == null) ? "null" : ids.toArray().toString());

    LOG.debug("  isTransitive" + isTransitive);

    IContextValidator validator = findValidator(def.getType(), isTransitive);
    LOG.debug("  loaded validator: "
            + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE));

    if (validator != null) {
        NeutralQuery getIdsQuery = new NeutralQuery(
                new NeutralCriteria("_id", "in", new ArrayList<String>(ids)));
        LOG.debug("  getIdsQuery: " + getIdsQuery.toString());

        Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(),
                getIdsQuery);
        LOG.debug("  entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE));

        Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids);
        LOG.debug("  idsToValidate: " + idsToValidate.toString());

        Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator);
        LOG.debug("  validatedIds: " + validatedIds.toString());

        if (!validatedIds.containsAll(idsToValidate)) {
            LOG.debug("    ...APIAccessDeniedException");
            throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate);
        }
    } else {
        throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive,
                def.getType(), ids);
    }
}

From source file:org.ut.biolab.medsavant.server.serverapi.UserManager.java

public boolean checkAllRoles(String sessID, Set<UserRole> roles)
        throws RemoteException, SQLException, SessionExpiredException {
    if (roles.isEmpty()) {
        throw new IllegalArgumentException("Can't check empty role");
    }/*from   www.j  a va  2 s  .  c o m*/

    Set<UserRole> assignedRoles = getRolesForUser(sessID,
            SessionManager.getInstance().getUserForSession(sessID));
    return !assignedRoles.isEmpty() && assignedRoles.containsAll(roles);
}

From source file:com.xtructure.xneat.genetics.UTestGeneMap.java

public void toArrayReturnsExpectedArray() {
    NodeGene node0 = new NodeGeneImpl(0, NodeType.INPUT, NODE_CONFIGURATION);
    NodeGene node1 = new NodeGeneImpl(1, NodeType.OUTPUT, NODE_CONFIGURATION);
    LinkGene link0 = new LinkGeneImpl(0, node0.getId(), node1.getId(), LINK_CONFIGURATION);
    Set<Gene> genesList = new SetBuilder<Gene>().add(node0, node1, link0).newImmutableInstance();
    GeneMap geneMap = new GeneMap(//
            Arrays.asList(node0, node1), //
            Arrays.asList(link0));
    Object[] genes = geneMap.toArray();
    assertThat("", //
            genesList.containsAll(Arrays.asList(genes)), isTrue());
    assertThat("", //
            Arrays.asList(genes).containsAll(genesList), isTrue());
    genes = geneMap.toArray(new Gene[0]);
    assertThat("", //
            genesList.containsAll(Arrays.asList(genes)), isTrue());
    assertThat("", //
            Arrays.asList(genes).containsAll(genesList), isTrue());
}

From source file:au.org.ala.delta.model.DiffUtils.java

private static boolean doCompareMultiStateOrInteger(Set<Integer> attr1Values, Set<Integer> attr2Values,
        boolean attr1Unknown, boolean attr2Unknown, boolean attr1Inapplicable, boolean attr2Inapplicable,
        boolean matchUnknowns, boolean matchInapplicables, MatchType matchType) {

    // If both attributes are unknown or inapplicable this is considered a
    // match. Otherwise, the return value depends on setting for
    // matchInapplicable or matchUnknown.
    if ((attr1Unknown || attr1Inapplicable) && (attr2Unknown || attr2Inapplicable)) {
        return true;
    }//from  w w w .ja  va  2 s.c om

    if ((attr1Unknown && attr1Inapplicable) || (attr2Unknown && attr2Inapplicable)) {
        return matchInapplicables;
    }

    if ((attr1Unknown && !attr1Inapplicable) || (attr2Unknown && !attr2Inapplicable)) {
        return matchUnknowns;
    }

    boolean match = false;

    switch (matchType) {
    case EXACT:
        match = attr1Values.equals(attr2Values);
        break;
    case SUBSET:
        // is the first a subset of the second
        match = attr2Values.containsAll(attr1Values);
        break;
    case OVERLAP:
        for (int stateVal : attr1Values) {
            if (attr2Values.contains(stateVal)) {
                match = true;
                break;
            }
        }
        break;
    default:
        throw new RuntimeException(String.format("Unrecognized match type %s", matchType.toString()));
    }

    return match;
}

From source file:org.springframework.security.oauth2.provider.approval.ApprovalStoreUserApprovalHandler.java

public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    String clientId = authorizationRequest.getClientId();
    Collection<String> requestedScopes = authorizationRequest.getScope();
    Set<String> approvedScopes = new HashSet<String>();
    Set<String> validUserApprovedScopes = new HashSet<String>();

    if (clientDetailsService != null) {
        try {//from w  w  w .ja  v a2  s . c om
            ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
            for (String scope : requestedScopes) {
                if (client.isAutoApprove(scope) || client.isAutoApprove("all")) {
                    approvedScopes.add(scope);
                }
            }
            if (approvedScopes.containsAll(requestedScopes)) {
                authorizationRequest.setApproved(true);
                return authorizationRequest;
            }
        } catch (ClientRegistrationException e) {
            logger.warn("Client registration problem prevent autoapproval check for client=" + clientId);
        }
    }

    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up user approved authorizations for ");
        builder.append("client_id=" + clientId);
        builder.append(" and username=" + userAuthentication.getName());
        logger.debug(builder.toString());
    }

    // Find the stored approvals for that user and client
    Collection<Approval> userApprovals = approvalStore.getApprovals(userAuthentication.getName(), clientId);

    // Look at the scopes and see if they have expired
    Date today = new Date();
    for (Approval approval : userApprovals) {
        if (approval.getExpiresAt().after(today)) {
            validUserApprovedScopes.add(approval.getScope());
            if (approval.getStatus() == ApprovalStatus.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)) {
        approvedScopes.retainAll(requestedScopes);
        // Set only the scopes that have been approved by the user
        authorizationRequest.setScope(approvedScopes);
        authorizationRequest.setApproved(true);
    }

    return authorizationRequest;

}

From source file:com.liferay.ide.project.core.tests.UpgradeLiferayProjectsOpTests.java

@Test
public void testPossibleTargetRuntime() throws Exception {
    if (shouldSkipBundleTests())
        return;/*from   w  ww  .j a va  2 s. co m*/

    UpgradeLiferayProjectsOp op = UpgradeLiferayProjectsOp.TYPE.instantiate();

    final String originalRuntimeName = getRuntimeVersion();
    final IRuntime oldOriginalRuntime = ServerCore.findRuntime(originalRuntimeName);
    assertNotNull(oldOriginalRuntime);

    setupRuntime620();

    final String newRuntimeName = getRuntimeVersion620();
    final IRuntime newOriginalRuntime = ServerCore.findRuntime(getRuntimeVersion620());
    assertNotNull(newOriginalRuntime);

    Set<String> exceptedRuntimeNames = new HashSet<String>();
    exceptedRuntimeNames.add(originalRuntimeName);
    exceptedRuntimeNames.add(newRuntimeName);

    final Set<String> acturalRuntimeNames = op.getRuntimeName().service(PossibleValuesService.class).values();
    assertNotNull(acturalRuntimeNames);

    assertEquals(true, exceptedRuntimeNames.containsAll(acturalRuntimeNames));
    assertEquals(true, acturalRuntimeNames.containsAll(exceptedRuntimeNames));
}

From source file:com.thoughtworks.go.domain.materials.Modifications.java

public boolean shouldBeIgnoredByFilterIn(MaterialConfig materialConfig) {
    if (materialConfig.filter().shouldNeverIgnore()) {
        return false;
    }//from  w w  w  .  ja  v a2  s  .c o m
    Set<ModifiedFile> allFiles = getAllFiles(this);
    Set<ModifiedFile> ignoredFiles = new HashSet<>();

    for (ModifiedFile file : allFiles) {
        appyIgnoreFilter(materialConfig, file, ignoredFiles);
    }

    LOG.debug("Checking ignore filters for {}", materialConfig);
    LOG.debug("Ignored files: {}", ignoredFiles);
    LOG.debug("Changed files: {}", CollectionUtils.subtract(allFiles, ignoredFiles));

    if (materialConfig.isInvertFilter()) {
        // return true (ignore) if we are inverting the filter, and the ignoredFiles and allFiles are disjoint sets
        return Collections.disjoint(allFiles, ignoredFiles);
    } else {
        return ignoredFiles.containsAll(allFiles);
    }
}

From source file:org.apache.cassandra.hadoop2.multiquery.MultiQueryRecordReader.java

private List<Pair<String, DataType>> getColumnsToCheckAndTypes(Configuration conf) {
    // TODO: For now this is just token(partition key), but it could later include other columns.

    List<String> columnsForOrdering = ConfigHelper.getInputCqlQueryClusteringColumns(mConf);

    List<CqlQuerySpec> querySpecs = ConfigHelper.getInputCqlQueries(conf);
    CqlQuerySpec query = querySpecs.get(0);

    String keyspace = query.getKeyspace();
    String tableName = query.getTable();

    // Get the metadata for this table.
    TableMetadata tableMetadata = mSession.getCluster().getMetadata().getKeyspace(keyspace).getTable(tableName);

    // Get a set of all of the clustering column names.
    Set<String> clusteringColumnNames = Sets.newHashSet();
    for (ColumnMetadata columnMetadata : tableMetadata.getClusteringColumns()) {
        clusteringColumnNames.add(columnMetadata.getName());
    }/*w w  w .  jav a 2s .c om*/
    Preconditions.checkArgument(clusteringColumnNames.containsAll(columnsForOrdering));

    List<Pair<String, DataType>> columnsToCheck = Lists.newArrayList(Pair.of(mTokenColumn, DataType.bigint()));

    for (String clusteringColumn : columnsForOrdering) {
        ColumnMetadata columnMetadata = tableMetadata.getColumn(clusteringColumn);
        String name = columnMetadata.getName();
        DataType dataType = columnMetadata.getType();
        columnsToCheck.add(Pair.of(name, dataType));
    }
    return columnsToCheck;
}