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.fao.geonet.services.main.Info.java

private List getUsers(ServiceContext context, UserSession us, Dbms dbms) throws SQLException {
    if (!us.isAuthenticated())
        return new ArrayList<Element>();

    int id = Integer.parseInt(us.getUserId());

    if (us.getProfile().equals(Geonet.Profile.ADMINISTRATOR))
        return dbms.select("SELECT * FROM Users").getChildren();

    if (!us.getProfile().equals(Geonet.Profile.USER_ADMIN))
        return dbms.select("SELECT * FROM Users WHERE id=?", id).getChildren();

    //--- we have a user admin

    Set<String> hsMyGroups = getUserGroups(dbms, id);

    Set profileSet = context.getProfileManager().getProfilesSet(us.getProfile());

    //--- retrieve all users

    Element elUsers = dbms.select("SELECT * FROM Users ORDER BY username");

    //--- now filter them

    ArrayList<Element> alToRemove = new ArrayList<Element>();

    for (Object o : elUsers.getChildren()) {
        Element elRec = (Element) o;

        String userId = elRec.getChildText("id");
        String profile = elRec.getChildText("profile");

        if (!profileSet.contains(profile))
            alToRemove.add(elRec);/*  w  w  w .jav  a 2 s .c om*/

        else if (!hsMyGroups.containsAll(getUserGroups(dbms, Integer.parseInt(userId))))
            alToRemove.add(elRec);
    }

    //--- remove unwanted users

    for (int i = 0; i < alToRemove.size(); i++)
        alToRemove.get(i).detach();

    //--- return result

    return elUsers.getChildren();
}

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

protected void checkRemoveLabelsFromNode(Map<NodeId, Set<String>> removeLabelsFromNode) throws IOException {
    // check all labels being added existed
    Set<String> knownLabels = labelCollections.keySet();
    for (Entry<NodeId, Set<String>> entry : removeLabelsFromNode.entrySet()) {
        NodeId nodeId = entry.getKey();/*w  ww.  ja  v  a  2  s  .c o m*/
        Set<String> labels = entry.getValue();

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

        Set<String> originalLabels = null;

        boolean nodeExisted = false;
        if (WILDCARD_PORT != nodeId.getPort()) {
            Node nm = getNMInNodeSet(nodeId);
            if (nm != null) {
                originalLabels = nm.labels;
                nodeExisted = true;
            }
        } else {
            Host host = nodeCollections.get(nodeId.getHost());
            if (null != host) {
                originalLabels = host.labels;
                nodeExisted = true;
            }
        }

        if (!nodeExisted) {
            String msg = "Try to remove labels from NM=" + nodeId + ", but the NM doesn't existed";
            LOG.error(msg);
            throw new IOException(msg);
        }

        // the labels will never be null
        if (labels.isEmpty()) {
            continue;
        }

        // originalLabels may be null,
        // because when a Node is created, Node.labels can be null.
        if (originalLabels == null || !originalLabels.containsAll(labels)) {
            String msg = "Try to remove labels = [" + StringUtils.join(labels, ",")
                    + "], but not all labels contained by NM=" + nodeId;
            LOG.error(msg);
            throw new IOException(msg);
        }
    }
}

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

@SuppressWarnings("unchecked")
protected boolean areBudgetRatesOutOfSyncWithInsttituteRatesForRateAudit(List instituteRates,
        List budgetRates) {//from   w w w.  j av  a 2 s. c  om
    Set<String> instituteRateKeys = storeAllKeysWithRate((List<AbstractInstituteRate>) instituteRates);
    Set<String> budgetRateKeys = storeAllKeysWithRate((List<AbstractInstituteRate>) budgetRates);

    return !instituteRateKeys.containsAll(budgetRateKeys);
}

From source file:org.mitre.oauth2.service.impl.DefaultOAuth2ProviderTokenService.java

@Override
public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest)
        throws AuthenticationException {

    OAuth2RefreshTokenEntity refreshToken = clearExpiredRefreshToken(
            tokenRepository.getRefreshTokenByValue(refreshTokenValue));

    if (refreshToken == null) {
        throw new InvalidTokenException("Invalid refresh token: " + refreshTokenValue);
    }//from  ww  w .  j a  v a  2s  .c o  m

    ClientDetailsEntity client = refreshToken.getClient();

    AuthenticationHolderEntity authHolder = refreshToken.getAuthenticationHolder();

    // make sure that the client requesting the token is the one who owns the refresh token
    ClientDetailsEntity requestingClient = clientDetailsService.loadClientByClientId(authRequest.getClientId());
    if (!client.getClientId().equals(requestingClient.getClientId())) {
        tokenRepository.removeRefreshToken(refreshToken);
        throw new InvalidClientException("Client does not own the presented refresh token");
    }

    //Make sure this client allows access token refreshing
    if (!client.isAllowRefresh()) {
        throw new InvalidClientException("Client does not allow refreshing access token!");
    }

    // clear out any access tokens
    if (client.isClearAccessTokensOnRefresh()) {
        tokenRepository.clearAccessTokensForRefreshToken(refreshToken);
    }

    if (refreshToken.isExpired()) {
        tokenRepository.removeRefreshToken(refreshToken);
        throw new InvalidTokenException("Expired refresh token: " + refreshTokenValue);
    }

    OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();

    // get the stored scopes from the authentication holder's authorization request; these are the scopes associated with the refresh token
    Set<String> refreshScopesRequested = new HashSet<>(
            refreshToken.getAuthenticationHolder().getAuthentication().getOAuth2Request().getScope());
    Set<SystemScope> refreshScopes = scopeService.fromStrings(refreshScopesRequested);
    // remove any of the special system scopes
    refreshScopes = scopeService.removeReservedScopes(refreshScopes);

    Set<String> scopeRequested = authRequest.getScope() == null ? new HashSet<String>()
            : new HashSet<>(authRequest.getScope());
    Set<SystemScope> scope = scopeService.fromStrings(scopeRequested);

    // remove any of the special system scopes
    scope = scopeService.removeReservedScopes(scope);

    if (scope != null && !scope.isEmpty()) {
        // ensure a proper subset of scopes
        if (refreshScopes != null && refreshScopes.containsAll(scope)) {
            // set the scope of the new access token if requested
            token.setScope(scopeService.toStrings(scope));
        } else {
            String errorMsg = "Up-scoping is not allowed.";
            logger.error(errorMsg);
            throw new InvalidScopeException(errorMsg);
        }
    } else {
        // otherwise inherit the scope of the refresh token (if it's there -- this can return a null scope set)
        token.setScope(scopeService.toStrings(refreshScopes));
    }

    token.setClient(client);

    if (client.getAccessTokenValiditySeconds() != null) {
        Date expiration = new Date(
                System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L));
        token.setExpiration(expiration);
    }

    if (client.isReuseRefreshToken()) {
        // if the client re-uses refresh tokens, do that
        token.setRefreshToken(refreshToken);
    } else {
        // otherwise, make a new refresh token
        OAuth2RefreshTokenEntity newRefresh = createRefreshToken(client, authHolder);
        token.setRefreshToken(newRefresh);

        // clean up the old refresh token
        tokenRepository.removeRefreshToken(refreshToken);
    }

    token.setAuthenticationHolder(authHolder);

    tokenEnhancer.enhance(token, authHolder.getAuthentication());

    tokenRepository.saveAccessToken(token);

    return token;

}

From source file:org.apache.lens.cli.TestLensQueryCommands.java

@Test
public void testProxyLensQuery() throws Exception {
    LensClient client = new LensClient();
    QueryHandle handle = client.executeQueryAsynch("cube select id,name from test_dim", "proxyTestQuery",
            new LensConf());
    client.getStatement().waitForQueryToComplete(handle);
    LensQuery query = client.getQueryDetails(handle);
    ProxyLensQuery proxyQuery = new ProxyLensQuery(client.getStatement(), handle);
    Assert.assertEquals(query.getStatus().successful(), proxyQuery.getStatus().successful());
    Assert.assertEquals(query.getSubmissionTime(), proxyQuery.getSubmissionTime());
    Assert.assertEquals(query.getFinishTime(), proxyQuery.getFinishTime());

    //Check is any new getters are added to LensQuery. If yes, ProxyLensQuery should be updated too
    Set<String> lensQueryMethods = new HashSet<String>();
    for (Method m : query.getClass().getDeclaredMethods()) {
        if (Modifier.isPublic(m.getModifiers()) && !m.getName().startsWith("hash")
                && !m.getName().startsWith("equals")) {
            lensQueryMethods.add(m.getName());
        }//  ww  w .j  av a2s  .  co m
    }

    Set<String> proxyLensQueryMethods = new HashSet<String>();
    for (Method m : proxyQuery.getClass().getDeclaredMethods()) {
        if (Modifier.isPublic(m.getModifiers())) {
            proxyLensQueryMethods.add(m.getName());
        }
    }

    log.info("Methods in LensQuery: " + lensQueryMethods + "\nMethods in ProxyLensQuery: "
            + proxyLensQueryMethods);
    assertTrue(lensQueryMethods.containsAll(proxyLensQueryMethods),
            "Methods in LensQuery and ProxyLensQuery do not match");

    //Check equals and hashCode override
    ProxyLensQuery proxyQuery2 = new ProxyLensQuery(client.getStatement(), handle);
    Assert.assertEquals(proxyQuery, proxyQuery2);
    Assert.assertEquals(proxyQuery, query);
    Assert.assertEquals(proxyQuery.hashCode(), proxyQuery2.hashCode());
    Assert.assertEquals(proxyQuery.hashCode(), query.hashCode());

    client.closeConnection();
}

From source file:org.codehaus.groovy.grails.web.mapping.DefaultUrlMappingsHolder.java

/**
 * Performs a match uses reverse mappings to looks up a mapping from the
 * controller, action and params. This is refactored to use a list of mappings
 * identified by only controller and action and then matches the mapping to select
 * the mapping that best matches the params (most possible matches).
 *
 *
 * @param controller The controller name
 * @param action The action name/*  w w w.  j a v  a 2  s. c  om*/
 * @param httpMethod The HTTP method
 * @param version
 * @param params The params  @return A UrlMapping instance or null
 */
@SuppressWarnings("unchecked")
protected UrlMapping lookupMapping(String controller, String action, String namespace, String pluginName,
        String httpMethod, String version, Map params) {
    final UrlMappingsListKey lookupKey = new UrlMappingsListKey(controller, action, namespace, pluginName,
            httpMethod, version);
    SortedSet mappingKeysSet = mappingsListLookup.get(lookupKey);

    final String actionName = lookupKey.action;
    boolean secondAttempt = false;
    final boolean isIndexAction = GrailsControllerClass.INDEX_ACTION.equals(actionName);
    if (null == mappingKeysSet) {
        lookupKey.httpMethod = UrlMapping.ANY_HTTP_METHOD;
        mappingKeysSet = mappingsListLookup.get(lookupKey);
    }
    if (null == mappingKeysSet && actionName != null) {
        lookupKey.action = null;

        mappingKeysSet = mappingsListLookup.get(lookupKey);
        secondAttempt = true;
    }
    if (null == mappingKeysSet)
        return null;

    Set<String> lookupParams = new HashSet<String>(params.keySet());
    if (secondAttempt) {
        lookupParams.removeAll(DEFAULT_ACTION_PARAMS);
        lookupParams.addAll(DEFAULT_ACTION_PARAMS);
    }

    UrlMappingKey[] mappingKeys = (UrlMappingKey[]) mappingKeysSet
            .toArray(new UrlMappingKey[mappingKeysSet.size()]);
    for (int i = mappingKeys.length; i > 0; i--) {
        UrlMappingKey mappingKey = mappingKeys[i - 1];
        if (lookupParams.containsAll(mappingKey.paramNames)) {
            final UrlMapping mapping = mappingsLookup.get(mappingKey);
            if (canInferAction(actionName, secondAttempt, isIndexAction, mapping)) {
                return mapping;
            }
            if (!secondAttempt) {
                return mapping;
            }
        }
    }
    return null;
}

From source file:org.apache.falcon.resource.AbstractEntityManager.java

protected Set<String> getColosFromExpression(String coloExpr, String type, String entity) {
    Set<String> colos;
    final Set<String> applicableColos = getApplicableColos(type, entity);
    if (coloExpr == null || coloExpr.equals("*") || coloExpr.isEmpty()) {
        colos = applicableColos;//from w w  w  .ja  va2 s  . co m
    } else {
        colos = new HashSet<String>(Arrays.asList(coloExpr.split(",")));
        if (!applicableColos.containsAll(colos)) {
            throw FalconWebException.newException("Given colos not applicable for entity operation",
                    Response.Status.BAD_REQUEST);
        }
    }
    return colos;
}

From source file:org.grails.web.mapping.DefaultUrlMappingsHolder.java

/**
 * Performs a match uses reverse mappings to looks up a mapping from the
 * controller, action and params. This is refactored to use a list of mappings
 * identified by only controller and action and then matches the mapping to select
 * the mapping that best matches the params (most possible matches).
 *
 *
 * @param controller The controller name
 * @param action The action name//  w w  w .ja v a  2 s.c  o  m
 * @param httpMethod The HTTP method
 * @param version
 * @param params The params  @return A UrlMapping instance or null
 */
@SuppressWarnings("unchecked")
protected UrlMapping lookupMapping(String controller, String action, String namespace, String pluginName,
        String httpMethod, String version, Map params) {
    final UrlMappingsListKey lookupKey = new UrlMappingsListKey(controller, action, namespace, pluginName,
            httpMethod, version);
    Collection mappingKeysSet = mappingsListLookup.get(lookupKey);

    final String actionName = lookupKey.action;
    boolean secondAttempt = false;
    final boolean isIndexAction = GrailsControllerClass.INDEX_ACTION.equals(actionName);
    if (null == mappingKeysSet) {
        lookupKey.httpMethod = UrlMapping.ANY_HTTP_METHOD;
        mappingKeysSet = mappingsListLookup.get(lookupKey);
    }
    if (null == mappingKeysSet && actionName != null) {
        lookupKey.action = null;

        mappingKeysSet = mappingsListLookup.get(lookupKey);
        secondAttempt = true;
    }
    if (null == mappingKeysSet)
        return null;

    Set<String> lookupParams = new HashSet<String>(params.keySet());
    if (secondAttempt) {
        lookupParams.removeAll(DEFAULT_ACTION_PARAMS);
        lookupParams.addAll(DEFAULT_ACTION_PARAMS);
    }

    UrlMappingKey[] mappingKeys = (UrlMappingKey[]) mappingKeysSet
            .toArray(new UrlMappingKey[mappingKeysSet.size()]);
    for (int i = mappingKeys.length; i > 0; i--) {
        UrlMappingKey mappingKey = mappingKeys[i - 1];
        if (lookupParams.containsAll(mappingKey.paramNames)) {
            final UrlMapping mapping = mappingsLookup.get(mappingKey);
            if (canInferAction(actionName, secondAttempt, isIndexAction, mapping)) {
                return mapping;
            }
            if (!secondAttempt) {
                return mapping;
            }
        }
    }
    return null;
}

From source file:ome.adapters.pojos.itests.PojosServiceTest.java

@Test
public void test_duplicate_links_again() throws Exception {

    String string = "duplinksagain" + System.currentTimeMillis();

    Dataset d = new Dataset();
    d.setName(string);/*from w  w w  . j a  va 2  s.com*/

    Project p = new Project();
    p.setName(string);

    d.linkProject(p);
    d = iPojos.createDataObject(d, null);
    Set orig_ids = new HashSet(d.collectProjectLinks(new IdBlock()));

    DatasetData dd = new DatasetData(d);
    Dataset toSend = dd.asDataset();

    Dataset updated = iPojos.updateDataObject(toSend, null);

    Set updt_ids = new HashSet(updated.collectProjectLinks(new IdBlock()));

    if (log.isDebugEnabled()) {
        log.debug(orig_ids);
        log.debug(updt_ids);
    }

    assertTrue(updt_ids.containsAll(orig_ids));
    assertTrue(orig_ids.containsAll(updt_ids));

}