Example usage for java.util Set stream

List of usage examples for java.util Set stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:io.gravitee.repository.redis.management.internal.impl.ApplicationRedisRepositoryImpl.java

@Override
public Set<RedisApplication> findByName(final String partialName) {

    List<String> matchedNames = redisTemplate.execute(new RedisCallback<List<String>>() {
        @Override/*from   ww w.  j  a v a2s.c  o  m*/
        public List<String> doInRedis(RedisConnection redisConnection) throws DataAccessException {
            ScanOptions options = ScanOptions.scanOptions()
                    .match(REDIS_KEY + ":search-by:name:*" + partialName.toUpperCase() + "*").build();
            Cursor<byte[]> cursor = redisConnection.scan(options);
            List<String> result = new ArrayList<>();
            if (cursor != null) {
                while (cursor.hasNext()) {
                    result.add(new String(cursor.next()));
                }
            }
            return result;
        }
    });

    if (matchedNames == null || matchedNames.isEmpty()) {
        return Collections.emptySet();
    }
    Set<Object> applicationIds = new HashSet<>();
    matchedNames.forEach(matchedName -> applicationIds.addAll(redisTemplate.opsForSet().members(matchedName)));

    return find(applicationIds.stream().map(Object::toString).collect(Collectors.toList()));
}

From source file:natalia.dymnikova.cluster.scheduler.impl.RolesChecker.java

private List<Set<ScannedGenericBeanDefinition>> scan(final String basePackage, final List<TypeFilter> filters) {
    final ArrayList<Set<ScannedGenericBeanDefinition>> sets = new ArrayList<>(filters.size());

    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false, scannerEnvironment);/*  ww  w  .  j a v a2  s .co m*/

    scanner.setResourceLoader(resourcePatternResolver);
    scanner.setMetadataReaderFactory(metadataReaderFactory);

    for (final TypeFilter filter : filters) {
        scanner.resetFilters(false);
        scanner.addIncludeFilter(new CompositeFilter(new AnnotationTypeFilter(Component.class), filter));

        final Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);

        final Set<ScannedGenericBeanDefinition> collect = candidateComponents.stream()
                .map(bd -> (ScannedGenericBeanDefinition) bd).collect(toSet());

        sets.add(collect);
    }

    scanner.clearCache();

    return sets;
}

From source file:alfio.manager.user.UserManager.java

private boolean checkRole(User user, Set<Role> expectedRoles) {
    Set<String> roleNames = expectedRoles.stream().map(Role::getRoleName).collect(Collectors.toSet());
    return authorityRepository.checkRole(user.getUsername(), roleNames);
}

From source file:com.thinkbiganalytics.metadata.rest.model.feed.FeedLineage.java

@JsonIgnore
private void serialize(Feed feed) {

    if (feed.getDependentFeeds() != null) {
        Set<String> ids = new HashSet<>();
        Set<Feed> dependentFeeds = new HashSet<>(feed.getDependentFeeds());
        feed.setDependentFeeds(null);/*from   w ww. j a v a  2s .c o m*/
        dependentFeeds.stream().forEach(depFeed -> {
            feedMap.put(depFeed.getId(), depFeed);
            ids.add(depFeed.getId());

            if (depFeed.getDependentFeeds() != null) {
                serialize(depFeed);
            }
        });

        feed.setDependentFeedIds(ids);
    }
    if (feed.getUsedByFeeds() != null) {
        Set<String> ids = new HashSet<>();
        Set<Feed> usedByFeeds = new HashSet<>(feed.getUsedByFeeds());
        feed.getUsedByFeeds().clear();
        usedByFeeds.stream().forEach(depFeed -> {
            feedMap.put(depFeed.getId(), depFeed);
            ids.add(depFeed.getId());
            if (depFeed.getUsedByFeeds() != null) {
                serialize(depFeed);
            }
        });
        feed.setUsedByFeedIds(ids);
    }

    if (feed.getSources() != null) {
        feed.getSources().forEach(feedSource -> {
            Datasource ds = serializeDatasource(feedSource.getDatasource());
            feedSource.setDatasource(null);
            if (StringUtils.isBlank(feedSource.getDatasourceId())) {
                feedSource.setDatasourceId(ds != null ? ds.getId() : null);
            }
        });
    }
    if (feed.getDestinations() != null) {
        feed.getDestinations().forEach(feedDestination -> {
            Datasource ds = serializeDatasource(feedDestination.getDatasource());
            feedDestination.setDatasource(null);
            if (StringUtils.isBlank(feedDestination.getDatasourceId())) {
                feedDestination.setDatasourceId(ds != null ? ds.getId() : null);
            }
        });
    }
    feedMap.put(feed.getId(), feed);
}

From source file:de.ks.flatadocdb.metamodel.Parser.java

private Map<Field, PropertyPersister> resolvePropertyPersisters(Set<Field> allFields) {
    HashMap<Field, PropertyPersister> retval = new HashMap<>();
    Set<Field> fields = allFields.stream().filter(f -> f.isAnnotationPresent(Property.class))
            .collect(Collectors.toSet());
    for (Field field : fields) {
        Property annotation = field.getAnnotation(Property.class);
        Class<? extends PropertyPersister> persisterClass = annotation.value();
        PropertyPersister instance = getInstance(persisterClass);
        retval.put(field, instance);/*from  www .java  2 s  . c om*/
    }
    return retval;
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateJWTTokenServices.java

private OAuth2Request getOAuth2Request(@NotNull final JwtClaims claims)
        throws MalformedClaimException, InvalidTokenException {
    final String clientId = claims.getClaimValue("client_id", String.class);
    @SuppressWarnings("unchecked")
    final Set<String> scopes = Sets.newHashSet(claims.getClaimValue("scope", Collection.class));

    final Set<SimpleGrantedAuthority> authorities = scopes.stream().map(scope -> {
        if (scope.startsWith(GENIE_SCOPE_PREFIX)) {
            scope = scope.substring(GENIE_SCOPE_PREFIX_LENGTH);
        }/*from   www.  ja  va  2 s .co  m*/

        return new SimpleGrantedAuthority(ROLE + scope.toUpperCase());
    }).collect(Collectors.toSet());

    if (authorities.isEmpty()) {
        throw new InvalidTokenException("No scopes found. Unable to authorize");
    }

    // Assume a user is a subset of admin so always grant admin user the role user as well
    if (authorities.contains(ADMIN)) {
        authorities.add(USER);
    }

    return new OAuth2Request(null, clientId, authorities, true, scopes, null, null, null, null);
}

From source file:com.olacabs.fabric.compute.builder.impl.JarScanner.java

private List<ScanResult> scanForSources(ClassLoader classLoader, URL[] downloadedUrls) throws Exception {
    Reflections reflections = new Reflections(new ConfigurationBuilder().addClassLoader(classLoader)
            .addScanners(new SubTypesScanner(), new TypeAnnotationsScanner()).addUrls(downloadedUrls));
    Set<Class<?>> sources = Sets.intersection(reflections.getTypesAnnotatedWith(Source.class),
            reflections.getSubTypesOf(PipelineSource.class));
    return sources.stream().map(source -> {
        Source sourceInfo = source.getAnnotation(Source.class);
        ComponentMetadata metadata = ComponentMetadata.builder().type(ComponentType.SOURCE)
                .namespace(sourceInfo.namespace()).name(sourceInfo.name()).version(sourceInfo.version())
                .description(sourceInfo.description()).cpu(sourceInfo.cpu()).memory(sourceInfo.memory())
                .requiredProperties(ImmutableList.copyOf(sourceInfo.requiredProperties()))
                .optionalProperties(ImmutableList.copyOf(sourceInfo.optionalProperties())).build();

        return ScanResult.builder().metadata(metadata).componentClass(source).build();

    }).collect(Collectors.toCollection(ArrayList::new));
}

From source file:integr.org.pgptool.gui.encryption.EncryptionDecryptionTests.java

private PasswordDeterminedForKey buildPasswordDeterminedForKey(String encryptedFile, String keyName,
        String password) {/*from  w  w w . j a va2s. c om*/
    Set<String> decryptionKeys = encryptionService.findKeyIdsForDecryption(encryptedFile);
    Key key = keys.get(keyName);
    Optional<String> requestedKeyId = decryptionKeys.stream()
            .filter(x -> key.getKeyData().isHasAlternativeId(x)).findFirst();
    assertTrue(requestedKeyId.isPresent());
    return new PasswordDeterminedForKey(requestedKeyId.get(), key, password);
}

From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticle.java

private Set<RunRightFastHealthCheck> oDatabaseDocumentTxHealthChecks() {
    ServiceUtils.awaitRunning(service);/*from  ww w . j a  v  a  2s.  c om*/
    return service.getDatabaseNames().stream().map(name -> {
        final ODatabaseDocumentTxSupplier oDatabaseDocumentTxSupplier = service
                .getODatabaseDocumentTxSupplier(name).get();
        final ODatabaseDocumentTxHealthCheckBuilder healthcheckBuilder = ODatabaseDocumentTxHealthCheck
                .builder().oDatabaseDocumentTxSupplier(oDatabaseDocumentTxSupplier).databaseName(name);
        final Set<Class<? extends DocumentObject>> classes = databaseClassesForHealthCheck.get(name);
        if (CollectionUtils.isNotEmpty(classes)) {
            classes.stream().forEach(healthcheckBuilder::documentObject);
        } else {
            warning.log("oDatabaseDocumentTxHealthChecks", () -> {
                return Json.createObjectBuilder().add("database", name)
                        .add("message", "No OrientDB classes are configured for the healthcheck").build();
            });
        }
        return healthcheckBuilder.build();
    }).map(healthcheck -> {
        return RunRightFastHealthCheck.builder().config(
                healthCheckConfigBuilder().name("EmbeddedOrientDBServiceHealthCheck").severity(FATAL).build())
                .healthCheck(healthcheck).build();
    }).collect(Collectors.toSet());
}

From source file:nu.yona.server.goals.service.ActivityCategoryService.java

private void addOrUpdateNewActivityCategories(Set<ActivityCategoryDto> activityCategoryDtos,
        Set<ActivityCategory> activityCategoriesInRepository) {
    Map<UUID, ActivityCategory> activityCategoriesInRepositoryMap = activityCategoriesInRepository.stream()
            .collect(Collectors.toMap(ActivityCategory::getId, ac -> ac));

    activityCategoryDtos.stream()/*from  w  w w  .  j a  va2 s  .c  o m*/
            .forEach(a -> addOrUpdateNewActivityCategory(a, activityCategoriesInRepositoryMap));
}