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.openid.connect.service.impl.TestMITREidDataService_1_2.java

@Test
public void testExportAuthenticationHolders() throws IOException {
    OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1",
            new ArrayList<GrantedAuthority>(), true, new HashSet<String>(), new HashSet<String>(),
            "http://foo.com", new HashSet<String>(), null);
    Authentication mockAuth1 = new UsernamePasswordAuthenticationToken("user1", "pass1",
            AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
    OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1);

    AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity();
    holder1.setId(1L);//from   w  w w.j av a 2  s  .  com
    holder1.setAuthentication(auth1);

    OAuth2Request req2 = new OAuth2Request(new HashMap<String, String>(), "client2",
            new ArrayList<GrantedAuthority>(), true, new HashSet<String>(), new HashSet<String>(),
            "http://bar.com", new HashSet<String>(), null);
    OAuth2Authentication auth2 = new OAuth2Authentication(req2, null);

    AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity();
    holder2.setId(2L);
    holder2.setAuthentication(auth2);

    List<AuthenticationHolderEntity> allAuthHolders = ImmutableList.of(holder1, holder2);

    when(clientRepository.getAllClients()).thenReturn(new HashSet<ClientDetailsEntity>());
    when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    when(wlSiteRepository.getAll()).thenReturn(new HashSet<WhitelistedSite>());
    when(blSiteRepository.getAll()).thenReturn(new HashSet<BlacklistedSite>());
    when(authHolderRepository.getAll()).thenReturn(allAuthHolders);
    when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet<OAuth2AccessTokenEntity>());
    when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet<OAuth2RefreshTokenEntity>());
    when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our holder list (this test)
    JsonArray holders = config.get(MITREidDataService.AUTHENTICATIONHOLDERS).getAsJsonArray();

    assertThat(holders.size(), is(2));
    // check for both of our clients in turn
    Set<AuthenticationHolderEntity> checked = new HashSet<>();
    for (JsonElement e : holders) {
        assertThat(e.isJsonObject(), is(true));
        JsonObject holder = e.getAsJsonObject();

        AuthenticationHolderEntity compare = null;
        if (holder.get("id").getAsLong() == holder1.getId()) {
            compare = holder1;
        } else if (holder.get("id").getAsLong() == holder2.getId()) {
            compare = holder2;
        }

        if (compare == null) {
            fail("Could not find matching authentication holder id: " + holder.get("id").getAsString());
        } else {
            assertTrue(holder.get("clientId").getAsString().equals(compare.getClientId()));
            assertTrue(holder.get("approved").getAsBoolean() == compare.isApproved());
            assertTrue(holder.get("redirectUri").getAsString().equals(compare.getRedirectUri()));
            if (compare.getUserAuth() != null) {
                assertTrue(holder.get("savedUserAuthentication").isJsonObject());
                JsonObject savedAuth = holder.get("savedUserAuthentication").getAsJsonObject();
                assertTrue(savedAuth.get("name").getAsString().equals(compare.getUserAuth().getName()));
                assertTrue(savedAuth.get("authenticated").getAsBoolean() == compare.getUserAuth()
                        .isAuthenticated());
                assertTrue(savedAuth.get("sourceClass").getAsString()
                        .equals(compare.getUserAuth().getSourceClass()));
            }
            checked.add(compare);
        }
    }
    // make sure all of our clients were found
    assertThat(checked.containsAll(allAuthHolders), is(true));
}

From source file:org.openconcerto.sql.model.graph.DatabaseGraph.java

/**
 * Construit la carte des tables/*from  w  w w. j a va  2 s  .c om*/
 * 
 * @param toRefreshSpec the roots and tables to refresh.
 * @return roots and tables loaded from file.
 * @throws SQLException if an error occurs.
 */
private synchronized Map<String, Set<String>> mapTables(final ToRefreshSpec toRefreshSpec) throws SQLException {
    assert Thread.holdsLock(this.base.getTreeMutex()) : "Cannot graph a changing object";
    Map<String, Set<String>> res = new TablesMap();

    final Set<SQLTable> currentTables = this.getAllTables();
    final ToRefreshActual toRefresh = toRefreshSpec.getActual(this.base, currentTables);
    // clear graph and add tables (vertices)
    {
        final Set<SQLTable> newTablesInScope = toRefresh.getNewTablesInScope();
        final Set<SQLTable> oldTablesInScope = toRefresh.getOldTablesInScope();
        // refresh all ?
        final boolean clearGraph = oldTablesInScope.equals(currentTables);

        // clear cache
        synchronized (this) {
            if (clearGraph) {
                this.foreignLink.clear();
                this.foreignLinks.clear();
            } else {
                for (final Iterator<Entry<List<SQLField>, Link>> iter = this.foreignLink.entrySet()
                        .iterator(); iter.hasNext();) {
                    final Entry<List<SQLField>, Link> e = iter.next();
                    // don't use e.getValue() since it can be null
                    final SQLTable linkTable = e.getKey().get(0).getTable();
                    if (oldTablesInScope.contains(linkTable))
                        iter.remove();
                }
                for (final Iterator<Entry<SQLTable, Set<Link>>> iter = this.foreignLinks.entrySet()
                        .iterator(); iter.hasNext();) {
                    final Entry<SQLTable, Set<Link>> e = iter.next();
                    final SQLTable linkTable = e.getKey().getTable();
                    if (oldTablesInScope.contains(linkTable))
                        iter.remove();
                }
            }
        }

        if (clearGraph) {
            this.getGraphP().removeAllVertices(oldTablesInScope);
            assert this.getGraphP().vertexSet().size() == 0 && this.getGraphP().edgeSet().size() == 0;
        } else {
            // Removing a vertex also removes edges, so check that we also refresh referent
            // tables otherwise they won't have any foreign links anymore which is wrong if
            // removedTable was just renamed
            // Also the cache is only cleared for tables in scope, meaning that the cache for
            // those referent tables will be incoherent with the actual graph
            final Collection<SQLTable> removedTables = org.openconcerto.utils.CollectionUtils
                    .subtract(oldTablesInScope, newTablesInScope);
            for (final SQLTable removedTable : removedTables) {
                final Set<SQLTable> referentTables = getReferentTables(removedTable);
                // MAYBE add option to refresh needed tables instead of failing
                if (!oldTablesInScope.containsAll(referentTables)) {
                    throw new IllegalStateException(
                            removedTable + " has been removed but some of its referents won't be refreshed : "
                                    + org.openconcerto.utils.CollectionUtils.subtract(referentTables,
                                            oldTablesInScope));
                }
            }
            this.getGraphP().removeAllVertices(removedTables);

            // remove links that will be refreshed.
            final Set<Link> linksToRemove = new HashSet<Link>();
            for (final SQLTable t : org.openconcerto.utils.CollectionUtils.intersection(oldTablesInScope,
                    newTablesInScope)) {
                linksToRemove.addAll(this.getGraphP().outgoingEdgesOf(t));
            }
            this.getGraphP().removeAllEdges(linksToRemove);
        }

        // add new tables (and existing but it's OK graph vertices is a set)
        Graphs.addAllVertices(this.getGraphP(), newTablesInScope);
    }
    final TablesMap fromXML = toRefresh.getFromXML();
    final TablesMap fromJDBC = toRefresh.getFromJDBC();
    if (fromXML.size() > 0) {
        final DBItemFileCache dir = this.getFileCache();
        try {
            if (dir != null) {
                Log.get().config("for mapping " + this + " trying xmls in " + dir);
                final long t1 = System.currentTimeMillis();
                res = this.mapFromXML(fromXML);
                // remove what was loaded
                fromXML.removeAll(res);
                final long t2 = System.currentTimeMillis();
                Log.get().config("XML took " + (t2 - t1) + "ms for mapping the graph of " + this.base.getName()
                        + "." + res);
            }
        } catch (Exception e) {
            SQLBase.logCacheError(dir, e);
            this.deleteGraphFiles();
        }
        // add to JDBC what wasn't loaded
        fromJDBC.merge(fromXML);
    }
    if (!fromJDBC.isEmpty()) {
        final long t1 = System.currentTimeMillis();
        for (final Entry<String, Set<String>> e : fromJDBC.entrySet()) {
            final String rootName = e.getKey();
            final Set<String> tableNames = e.getValue();
            final DBRoot r = this.base.getRoot(rootName);
            // first try to map the whole root at once
            if (!this.map(r, tableNames)) {
                // if this isn't supported use standard JDBC
                for (final String table : tableNames) {
                    this.map(r, table, null);
                }
            }
            this.save(r);
        }
        final long t2 = System.currentTimeMillis();
        Log.get()
                .config("JDBC took " + (t2 - t1) + "ms for mapping the graph of " + this.base + "." + fromJDBC);
    }
    return res;
}

From source file:com.hortonworks.streamline.streams.catalog.service.StreamCatalogService.java

private void validateEdge(TopologyEdge edge) {
    TopologySource source = getTopologySource(edge.getTopologyId(), edge.getFromId(), edge.getVersionId());
    TopologyProcessor processor = getTopologyProcessor(edge.getTopologyId(), edge.getFromId(),
            edge.getVersionId());// ww  w .j a v  a  2s.  c  o m
    if ((source == null || !source.getTopologyId().equals(edge.getTopologyId()))
            && (processor == null || !processor.getTopologyId().equals(edge.getTopologyId()))) {
        throw new IllegalArgumentException("Invalid source for edge " + edge);
    }
    TopologyOutputComponent outputComponent = source != null ? source : processor;
    processor = getTopologyProcessor(edge.getTopologyId(), edge.getToId(), edge.getVersionId());
    TopologySink sink = getTopologySink(edge.getTopologyId(), edge.getToId(), edge.getVersionId());
    if ((processor == null || !processor.getTopologyId().equals(edge.getTopologyId()))
            && (sink == null || !sink.getTopologyId().equals(edge.getTopologyId()))) {
        throw new IllegalArgumentException("Invalid destination for edge " + edge);
    }

    Set<Long> outputStreamIds = new HashSet<>();
    if (outputComponent.getOutputStreamIds() != null) {
        outputStreamIds.addAll(outputComponent.getOutputStreamIds());
    } else if (outputComponent.getOutputStreams() != null) {
        outputStreamIds.addAll(Collections2.transform(outputComponent.getOutputStreams(),
                new Function<TopologyStream, Long>() {
                    @Override
                    public Long apply(TopologyStream input) {
                        return input.getId();
                    }
                }));
    }

    Collection<Long> edgeStreamIds = Collections2.transform(edge.getStreamGroupings(),
            new Function<StreamGrouping, Long>() {
                public Long apply(StreamGrouping streamGrouping) {
                    return streamGrouping.getStreamId();
                }
            });
    if (!outputStreamIds.containsAll(edgeStreamIds)) {
        throw new IllegalArgumentException(
                "Edge stream Ids " + edgeStreamIds + " must be a subset of outputStreamIds " + outputStreamIds);
    }
    // check the fields specified in the fields grouping is a subset of the stream fields
    for (StreamGrouping streamGrouping : edge.getStreamGroupings()) {
        List<String> fields;
        if ((fields = streamGrouping.getFields()) != null) {
            Set<String> schemaFieldPatterns = getFieldPatterns(
                    getStreamInfo(edge.getTopologyId(), streamGrouping.getStreamId(), edge.getVersionId())
                            .getFields());
            fields.forEach(field -> {
                schemaFieldPatterns.stream().filter(pat -> field.matches(pat)).findAny()
                        .orElseThrow(() -> new IllegalArgumentException("Fields in the grouping " + fields
                                + " must be a subset the stream fields " + schemaFieldPatterns));
            });
        }
    }
}

From source file:org.mitre.openid.connect.service.impl.TestMITREidDataService_1_3.java

@Test
public void testExportAccessTokens() throws IOException, ParseException {
    String expiration1 = "2014-09-10T22:49:44.090+0000";
    Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);

    ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
    when(mockedClient1.getClientId()).thenReturn("mocked_client_1");

    AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
    when(mockedAuthHolder1.getId()).thenReturn(1L);

    OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity();
    token1.setId(1L);// w  w w. ja  va  2 s  .c  o  m
    token1.setClient(mockedClient1);
    token1.setExpiration(expirationDate1);
    token1.setJwt(JWTParser.parse(
            "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"));
    token1.setAuthenticationHolder(mockedAuthHolder1);
    token1.setScope(ImmutableSet.of("id-token"));
    token1.setTokenType("Bearer");

    String expiration2 = "2015-01-07T18:31:50.079+0000";
    Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);

    ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
    when(mockedClient2.getClientId()).thenReturn("mocked_client_2");

    AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
    when(mockedAuthHolder2.getId()).thenReturn(2L);

    OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class);
    when(mockRefreshToken2.getId()).thenReturn(1L);

    OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity();
    token2.setId(2L);
    token2.setClient(mockedClient2);
    token2.setExpiration(expirationDate2);
    token2.setJwt(JWTParser.parse(
            "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"));
    token2.setAuthenticationHolder(mockedAuthHolder2);
    token2.setRefreshToken(mockRefreshToken2);
    token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile"));
    token2.setTokenType("Bearer");

    Set<OAuth2AccessTokenEntity> allAccessTokens = ImmutableSet.of(token1, token2);

    Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet<ClientDetailsEntity>());
    Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet<WhitelistedSite>());
    Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet<BlacklistedSite>());
    Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList<AuthenticationHolderEntity>());
    Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet<OAuth2RefreshTokenEntity>());
    Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(allAccessTokens);
    Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_3), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_3).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our access token list (this test)
    JsonArray accessTokens = config.get(MITREidDataService.ACCESSTOKENS).getAsJsonArray();

    assertThat(accessTokens.size(), is(2));
    // check for both of our access tokens in turn
    Set<OAuth2AccessTokenEntity> checked = new HashSet<>();
    for (JsonElement e : accessTokens) {
        assertTrue(e.isJsonObject());
        JsonObject token = e.getAsJsonObject();

        OAuth2AccessTokenEntity compare = null;
        if (token.get("id").getAsLong() == token1.getId().longValue()) {
            compare = token1;
        } else if (token.get("id").getAsLong() == token2.getId().longValue()) {
            compare = token2;
        }

        if (compare == null) {
            fail("Could not find matching id: " + token.get("id").getAsString());
        } else {
            assertThat(token.get("id").getAsLong(), equalTo(compare.getId()));
            assertThat(token.get("clientId").getAsString(), equalTo(compare.getClient().getClientId()));
            assertThat(token.get("expiration").getAsString(),
                    equalTo(formatter.print(compare.getExpiration(), Locale.ENGLISH)));
            assertThat(token.get("value").getAsString(), equalTo(compare.getValue()));
            assertThat(token.get("type").getAsString(), equalTo(compare.getTokenType()));
            assertThat(token.get("authenticationHolderId").getAsLong(),
                    equalTo(compare.getAuthenticationHolder().getId()));
            assertTrue(token.get("scope").isJsonArray());
            assertThat(jsonArrayToStringSet(token.getAsJsonArray("scope")), equalTo(compare.getScope()));
            if (token.get("refreshTokenId").isJsonNull()) {
                assertNull(compare.getRefreshToken());
            } else {
                assertThat(token.get("refreshTokenId").getAsLong(), equalTo(compare.getRefreshToken().getId()));
            }
            checked.add(compare);
        }
    }
    // make sure all of our access tokens were found
    assertThat(checked.containsAll(allAccessTokens), is(true));
}

From source file:org.apache.hadoop.hbase.coordination.ZKSplitLogManagerCoordination.java

/**
 * It removes recovering regions under /hbase/recovering-regions/[encoded region name] so that the
 * region server hosting the region can allow reads to the recovered region
 * @param recoveredServerNameSet servers which are just recovered
 * @param isMetaRecovery whether current recovery is for the meta region on
 *          <code>serverNames</code>
 *///www. j a v  a  2s  .com
@Override
public void removeRecoveringRegions(final Set<String> recoveredServerNameSet, Boolean isMetaRecovery)
        throws IOException {
    final String metaEncodeRegionName = HRegionInfo.FIRST_META_REGIONINFO.getEncodedName();
    int count = 0;
    try {
        List<String> tasks = ZKUtil.listChildrenNoWatch(watcher, watcher.splitLogZNode);
        if (tasks != null) {
            int listSize = tasks.size();
            for (int i = 0; i < listSize; i++) {
                if (!ZKSplitLog.isRescanNode(tasks.get(i))) {
                    count++;
                }
            }
        }
        if (count == 0 && this.details.getMaster().isInitialized()
                && !this.details.getMaster().getServerManager().areDeadServersInProgress()) {
            // No splitting work items left
            ZKSplitLog.deleteRecoveringRegionZNodes(watcher, null);
            // reset lastRecoveringNodeCreationTime because we cleared all recovering znodes at
            // this point.
            lastRecoveringNodeCreationTime = Long.MAX_VALUE;
        } else if (!recoveredServerNameSet.isEmpty()) {
            // Remove recovering regions which don't have any RS associated with it
            List<String> regions = ZKUtil.listChildrenNoWatch(watcher, watcher.recoveringRegionsZNode);
            if (regions != null) {
                int listSize = regions.size();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Processing recovering " + regions + " and servers " + recoveredServerNameSet
                            + ", isMetaRecovery=" + isMetaRecovery);
                }
                for (int i = 0; i < listSize; i++) {
                    String region = regions.get(i);
                    if (isMetaRecovery != null) {
                        if ((isMetaRecovery && !region.equalsIgnoreCase(metaEncodeRegionName))
                                || (!isMetaRecovery && region.equalsIgnoreCase(metaEncodeRegionName))) {
                            // skip non-meta regions when recovering the meta region or
                            // skip the meta region when recovering user regions
                            continue;
                        }
                    }
                    String nodePath = ZKUtil.joinZNode(watcher.recoveringRegionsZNode, region);
                    List<String> failedServers = ZKUtil.listChildrenNoWatch(watcher, nodePath);
                    if (failedServers == null || failedServers.isEmpty()) {
                        ZKUtil.deleteNode(watcher, nodePath);
                        continue;
                    }
                    if (recoveredServerNameSet.containsAll(failedServers)) {
                        ZKUtil.deleteNodeRecursively(watcher, nodePath);
                    } else {
                        int tmpFailedServerSize = failedServers.size();
                        for (int j = 0; j < tmpFailedServerSize; j++) {
                            String failedServer = failedServers.get(j);
                            if (recoveredServerNameSet.contains(failedServer)) {
                                String tmpPath = ZKUtil.joinZNode(nodePath, failedServer);
                                ZKUtil.deleteNode(watcher, tmpPath);
                            }
                        }
                    }
                }
            }
        }
    } catch (KeeperException ke) {
        LOG.warn("removeRecoveringRegionsFromZK got zookeeper exception. Will retry", ke);
        throw new IOException(ke);
    }
}

From source file:com.facebook.presto.tests.AbstractTestQueries.java

@Test
public void testShowTables() throws Exception {
    Set<String> expectedTables = ImmutableSet.copyOf(transform(TpchTable.getTables(), tableNameGetter()));

    MaterializedResult result = computeActual("SHOW TABLES");
    Set<String> tableNames = ImmutableSet.copyOf(transform(result.getMaterializedRows(), onlyColumnGetter()));
    assertTrue(tableNames.containsAll(expectedTables));
}

From source file:org.mitre.openid.connect.service.impl.TestMITREidDataService_1_3.java

@Test
public void testExportClients() throws IOException {
    ClientDetailsEntity client1 = new ClientDetailsEntity();
    client1.setId(1L);/*from   w w w. java2 s.  c o  m*/
    client1.setAccessTokenValiditySeconds(3600);
    client1.setClientId("client1");
    client1.setClientSecret("clientsecret1");
    client1.setRedirectUris(ImmutableSet.of("http://foo.com/"));
    client1.setScope(ImmutableSet.of("foo", "bar", "baz", "dolphin"));
    client1.setGrantTypes(ImmutableSet.of("implicit", "authorization_code",
            "urn:ietf:params:oauth:grant_type:redelegate", "refresh_token"));
    client1.setAllowIntrospection(true);

    ClientDetailsEntity client2 = new ClientDetailsEntity();
    client2.setId(2L);
    client2.setAccessTokenValiditySeconds(3600);
    client2.setClientId("client2");
    client2.setClientSecret("clientsecret2");
    client2.setRedirectUris(ImmutableSet.of("http://bar.baz.com/"));
    client2.setScope(ImmutableSet.of("foo", "dolphin", "electric-wombat"));
    client2.setGrantTypes(ImmutableSet.of("client_credentials", "urn:ietf:params:oauth:grant_type:redelegate"));
    client2.setAllowIntrospection(false);
    client2.setCodeChallengeMethod(PKCEAlgorithm.S256);

    Set<ClientDetailsEntity> allClients = ImmutableSet.of(client1, client2);

    Mockito.when(clientRepository.getAllClients()).thenReturn(allClients);
    Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet<WhitelistedSite>());
    Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet<BlacklistedSite>());
    Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList<AuthenticationHolderEntity>());
    Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet<OAuth2AccessTokenEntity>());
    Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet<OAuth2RefreshTokenEntity>());
    Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_3), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_3).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our client list (this test)
    JsonArray clients = config.get(MITREidDataService.CLIENTS).getAsJsonArray();

    assertThat(clients.size(), is(2));
    // check for both of our clients in turn
    Set<ClientDetailsEntity> checked = new HashSet<>();
    for (JsonElement e : clients) {
        assertThat(e.isJsonObject(), is(true));
        JsonObject client = e.getAsJsonObject();

        ClientDetailsEntity compare = null;
        if (client.get("clientId").getAsString().equals(client1.getClientId())) {
            compare = client1;
        } else if (client.get("clientId").getAsString().equals(client2.getClientId())) {
            compare = client2;
        }

        if (compare == null) {
            fail("Could not find matching clientId: " + client.get("clientId").getAsString());
        } else {
            assertThat(client.get("clientId").getAsString(), equalTo(compare.getClientId()));
            assertThat(client.get("secret").getAsString(), equalTo(compare.getClientSecret()));
            assertThat(client.get("accessTokenValiditySeconds").getAsInt(),
                    equalTo(compare.getAccessTokenValiditySeconds()));
            assertThat(client.get("allowIntrospection").getAsBoolean(),
                    equalTo(compare.isAllowIntrospection()));
            assertThat(jsonArrayToStringSet(client.get("redirectUris").getAsJsonArray()),
                    equalTo(compare.getRedirectUris()));
            assertThat(jsonArrayToStringSet(client.get("scope").getAsJsonArray()), equalTo(compare.getScope()));
            assertThat(jsonArrayToStringSet(client.get("grantTypes").getAsJsonArray()),
                    equalTo(compare.getGrantTypes()));
            assertThat((client.has("codeChallengeMethod") && !client.get("codeChallengeMethod").isJsonNull())
                    ? PKCEAlgorithm.parse(client.get("codeChallengeMethod").getAsString())
                    : null, equalTo(compare.getCodeChallengeMethod()));
            checked.add(compare);
        }
    }
    // make sure all of our clients were found
    assertThat(checked.containsAll(allClients), is(true));
}

From source file:com.facebook.presto.tests.AbstractTestQueries.java

@Test
public void testShowTablesFrom() throws Exception {
    Set<String> expectedTables = ImmutableSet.copyOf(transform(TpchTable.getTables(), tableNameGetter()));

    String catalog = getSession().getCatalog().get();
    String schema = getSession().getSchema().get();

    MaterializedResult result = computeActual("SHOW TABLES FROM " + schema);
    Set<String> tableNames = ImmutableSet.copyOf(transform(result.getMaterializedRows(), onlyColumnGetter()));
    assertTrue(tableNames.containsAll(expectedTables));

    result = computeActual("SHOW TABLES FROM " + catalog + "." + schema);
    tableNames = ImmutableSet.copyOf(transform(result.getMaterializedRows(), onlyColumnGetter()));
    assertTrue(tableNames.containsAll(expectedTables));

    try {/* w  ww  .  j a v  a2 s.com*/
        computeActual("SHOW TABLES FROM UNKNOWN");
        fail("Showing tables in an unknown schema should fail");
    } catch (SemanticException e) {
        assertEquals(e.getCode(), MISSING_SCHEMA);
    } catch (RuntimeException e) {
        assertEquals(e.getMessage(), "line 1:1: Schema 'unknown' does not exist");
    }
}

From source file:org.apache.hadoop.hbase.master.SplitLogManager.java

/**
 * It removes recovering regions under /hbase/recovering-regions/[encoded region name] so that the
 * region server hosting the region can allow reads to the recovered region
 * @param serverNames servers which are just recovered
 * @param isMetaRecovery whether current recovery is for the meta region on
 *          <code>serverNames<code>
 *///w  w  w .  ja v  a 2s.  co m
private void removeRecoveringRegionsFromZK(final Set<ServerName> serverNames, Boolean isMetaRecovery) {

    if (!this.distributedLogReplay) {
        // the function is only used in WALEdit direct replay mode
        return;
    }

    final String metaEncodeRegionName = HRegionInfo.FIRST_META_REGIONINFO.getEncodedName();
    int count = 0;
    Set<String> recoveredServerNameSet = new HashSet<String>();
    if (serverNames != null) {
        for (ServerName tmpServerName : serverNames) {
            recoveredServerNameSet.add(tmpServerName.getServerName());
        }
    }

    try {
        this.recoveringRegionLock.lock();

        List<String> tasks = ZKUtil.listChildrenNoWatch(watcher, watcher.splitLogZNode);
        if (tasks != null) {
            for (String t : tasks) {
                if (!ZKSplitLog.isRescanNode(watcher, t)) {
                    count++;
                }
            }
        }
        if (count == 0 && this.master.isInitialized()
                && !this.master.getServerManager().areDeadServersInProgress()) {
            // no splitting work items left
            deleteRecoveringRegionZNodes(null);
            // reset lastRecoveringNodeCreationTime because we cleared all recovering znodes at
            // this point.
            lastRecoveringNodeCreationTime = Long.MAX_VALUE;
        } else if (!recoveredServerNameSet.isEmpty()) {
            // remove recovering regions which doesn't have any RS associated with it
            List<String> regions = ZKUtil.listChildrenNoWatch(watcher, watcher.recoveringRegionsZNode);
            if (regions != null) {
                for (String region : regions) {
                    if (isMetaRecovery != null) {
                        if ((isMetaRecovery && !region.equalsIgnoreCase(metaEncodeRegionName))
                                || (!isMetaRecovery && region.equalsIgnoreCase(metaEncodeRegionName))) {
                            // skip non-meta regions when recovering the meta region or
                            // skip the meta region when recovering user regions
                            continue;
                        }
                    }
                    String nodePath = ZKUtil.joinZNode(watcher.recoveringRegionsZNode, region);
                    List<String> failedServers = ZKUtil.listChildrenNoWatch(watcher, nodePath);
                    if (failedServers == null || failedServers.isEmpty()) {
                        ZKUtil.deleteNode(watcher, nodePath);
                        continue;
                    }
                    if (recoveredServerNameSet.containsAll(failedServers)) {
                        ZKUtil.deleteNodeRecursively(watcher, nodePath);
                    } else {
                        for (String failedServer : failedServers) {
                            if (recoveredServerNameSet.contains(failedServer)) {
                                String tmpPath = ZKUtil.joinZNode(nodePath, failedServer);
                                ZKUtil.deleteNode(watcher, tmpPath);
                            }
                        }
                    }
                }
            }
        }
    } catch (KeeperException ke) {
        LOG.warn("removeRecoveringRegionsFromZK got zookeeper exception. Will retry", ke);
        if (serverNames != null && !serverNames.isEmpty()) {
            this.failedRecoveringRegionDeletions
                    .add(new Pair<Set<ServerName>, Boolean>(serverNames, isMetaRecovery));
        }
    } finally {
        this.recoveringRegionLock.unlock();
    }
}

From source file:org.mitre.openid.connect.service.impl.TestMITREidDataService_1_2.java

@Test
public void testExportAccessTokens() throws IOException, ParseException {
    String expiration1 = "2014-09-10T22:49:44.090+0000";
    Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);

    ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
    when(mockedClient1.getClientId()).thenReturn("mocked_client_1");

    AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
    when(mockedAuthHolder1.getId()).thenReturn(1L);

    OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity();
    token1.setId(1L);/* www  .ja v a  2 s.  c o  m*/
    token1.setClient(mockedClient1);
    token1.setExpiration(expirationDate1);
    token1.setJwt(JWTParser.parse(
            "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"));
    token1.setAuthenticationHolder(mockedAuthHolder1);
    token1.setScope(ImmutableSet.of("id-token"));
    token1.setTokenType("Bearer");

    String expiration2 = "2015-01-07T18:31:50.079+0000";
    Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);

    ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
    when(mockedClient2.getClientId()).thenReturn("mocked_client_2");

    AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
    when(mockedAuthHolder2.getId()).thenReturn(2L);

    OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class);
    when(mockRefreshToken2.getId()).thenReturn(1L);

    OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity();
    token2.setId(2L);
    token2.setClient(mockedClient2);
    token2.setExpiration(expirationDate2);
    token2.setJwt(JWTParser.parse(
            "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"));
    token2.setAuthenticationHolder(mockedAuthHolder2);
    token2.setIdToken(token1);
    token2.setRefreshToken(mockRefreshToken2);
    token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile"));
    token2.setTokenType("Bearer");

    Set<OAuth2AccessTokenEntity> allAccessTokens = ImmutableSet.of(token1, token2);

    Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet<ClientDetailsEntity>());
    Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet<WhitelistedSite>());
    Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet<BlacklistedSite>());
    Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList<AuthenticationHolderEntity>());
    Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet<OAuth2RefreshTokenEntity>());
    Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(allAccessTokens);
    Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our access token list (this test)
    JsonArray accessTokens = config.get(MITREidDataService.ACCESSTOKENS).getAsJsonArray();

    assertThat(accessTokens.size(), is(2));
    // check for both of our access tokens in turn
    Set<OAuth2AccessTokenEntity> checked = new HashSet<>();
    for (JsonElement e : accessTokens) {
        assertTrue(e.isJsonObject());
        JsonObject token = e.getAsJsonObject();

        OAuth2AccessTokenEntity compare = null;
        if (token.get("id").getAsLong() == token1.getId().longValue()) {
            compare = token1;
        } else if (token.get("id").getAsLong() == token2.getId().longValue()) {
            compare = token2;
        }

        if (compare == null) {
            fail("Could not find matching id: " + token.get("id").getAsString());
        } else {
            assertThat(token.get("id").getAsLong(), equalTo(compare.getId()));
            assertThat(token.get("clientId").getAsString(), equalTo(compare.getClient().getClientId()));
            assertThat(token.get("expiration").getAsString(),
                    equalTo(formatter.print(compare.getExpiration(), Locale.ENGLISH)));
            assertThat(token.get("value").getAsString(), equalTo(compare.getValue()));
            assertThat(token.get("type").getAsString(), equalTo(compare.getTokenType()));
            assertThat(token.get("authenticationHolderId").getAsLong(),
                    equalTo(compare.getAuthenticationHolder().getId()));
            assertTrue(token.get("scope").isJsonArray());
            assertThat(jsonArrayToStringSet(token.getAsJsonArray("scope")), equalTo(compare.getScope()));
            if (token.get("idTokenId").isJsonNull()) {
                assertNull(compare.getIdToken());
            } else {
                assertThat(token.get("idTokenId").getAsLong(), equalTo(compare.getIdToken().getId()));
            }
            if (token.get("refreshTokenId").isJsonNull()) {
                assertNull(compare.getIdToken());
            } else {
                assertThat(token.get("refreshTokenId").getAsLong(), equalTo(compare.getRefreshToken().getId()));
            }
            checked.add(compare);
        }
    }
    // make sure all of our access tokens were found
    assertThat(checked.containsAll(allAccessTokens), is(true));
}