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:com.olacabs.fabric.compute.builder.impl.JarScanner.java

private List<ScanResult> scanForProcessors(ClassLoader classLoader, URL[] downloadedUrls) throws Exception {
    Reflections reflections = new Reflections(new ConfigurationBuilder().addClassLoader(classLoader)
            .addScanners(new SubTypesScanner(), new TypeAnnotationsScanner()).addUrls(downloadedUrls));
    Set<Class<?>> processors = Sets.intersection(reflections.getTypesAnnotatedWith(Processor.class),
            reflections.getSubTypesOf(ProcessorBase.class));

    return processors.stream().map(processor -> {
        Processor processorInfo = processor.getAnnotation(Processor.class);
        ComponentMetadata metadata = ComponentMetadata.builder().type(ComponentType.PROCESSOR)
                .namespace(processorInfo.namespace()).name(processorInfo.name())
                .version(processorInfo.version()).description(processorInfo.description())
                .cpu(processorInfo.cpu()).memory(processorInfo.memory())
                .processorType(processorInfo.processorType())
                .requiredProperties(ImmutableList.copyOf(processorInfo.requiredProperties()))
                .optionalProperties(ImmutableList.copyOf(processorInfo.optionalProperties())).build();

        return ScanResult.builder().metadata(metadata).componentClass(processor).build();
    }).collect(Collectors.toCollection(ArrayList::new));
}

From source file:com.devicehive.service.DeviceNotificationService.java

@SuppressWarnings("unchecked")
public CompletableFuture<List<DeviceNotification>> find(Set<String> guids, Set<String> names, Date timestampSt,
        Date timestampEnd) {//from   w w  w  . jav a 2  s. co m
    List<CompletableFuture<Response>> futures = guids.stream().map(guid -> {
        NotificationSearchRequest searchRequest = new NotificationSearchRequest();
        searchRequest.setGuid(guid);
        searchRequest.setNames(names);
        searchRequest.setTimestampStart(timestampSt);
        searchRequest.setTimestampEnd(timestampEnd);
        return searchRequest;
    }).map(searchRequest -> {
        CompletableFuture<Response> future = new CompletableFuture<>();
        rpcClient.call(
                Request.newBuilder().withBody(searchRequest).withPartitionKey(searchRequest.getGuid()).build(),
                new ResponseConsumer(future));
        return future;
    }).collect(Collectors.toList());

    // List<CompletableFuture<Response>> => CompletableFuture<List<DeviceNotification>>
    return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
            .thenApply(v -> futures.stream().map(CompletableFuture::join) // List<CompletableFuture<Response>> => CompletableFuture<List<Response>>
                    .map(r -> r.getBody().cast(NotificationSearchResponse.class).getNotifications()) // CompletableFuture<List<Response>> => CompletableFuture<List<List<DeviceNotification>>>
                    .flatMap(Collection::stream) // CompletableFuture<List<List<DeviceNotification>>> => CompletableFuture<List<DeviceNotification>>
                    .collect(Collectors.toList()));
}

From source file:alfio.manager.EventStatisticsManager.java

public List<EventStatistic> getAllEventsWithStatisticsFilteredBy(String username, Predicate<Event> predicate) {
    List<Event> events = getAllEvents(username).stream().filter(predicate).collect(toList());
    Map<Integer, Event> mappedEvent = events.stream()
            .collect(Collectors.toMap(Event::getId, Function.identity()));
    if (!mappedEvent.isEmpty()) {
        boolean isOwner = userManager.isOwner(userManager.findUserByUsername(username));
        Set<Integer> ids = mappedEvent.keySet();
        Stream<EventStatisticView> stats = isOwner ? eventRepository.findStatisticsFor(ids).stream()
                : ids.stream().map(EventStatisticView::empty);
        return stats.map(stat -> {
            Event event = mappedEvent.get(stat.getEventId());
            return new EventStatistic(event, stat, displayStatisticsForEvent(event));
        }).sorted().collect(Collectors.toList());
    } else {/* w w w . j  a v a  2 s  .  c  om*/
        return Collections.emptyList();
    }
}

From source file:com.haulmont.cuba.gui.app.security.user.browse.UserBrowser.java

public void resetRememberMe(Set<User> users) {
    List<UUID> usersForModify = users.stream().map(BaseUuidEntity::getId).collect(Collectors.toList());

    userManagementService.resetRememberMeTokens(usersForModify);

    showNotification(getMessage("resetRememberMeCompleted"), NotificationType.HUMANIZED);
}

From source file:org.artifactory.ui.rest.service.admin.configuration.repositories.replication.TestLocalReplicationService.java

@Override
public void execute(ArtifactoryRestRequest<LocalRepositoryConfigModel> request, RestResponse response) {
    String replicationUrl = request.getQueryParamByKey(REPLICATION_URL_PARAM);
    LocalRepositoryConfigModel model = request.getImodel();
    if (model == null) {
        response.error("No repository configuration given to test replication with.")
                .responseCode(SC_BAD_REQUEST);
        return;/*from  www .ja v  a  2 s .c o  m*/
    } else if (StringUtils.isBlank(replicationUrl)) {
        response.error("No url given to identify which replication target to test")
                .responseCode(SC_BAD_REQUEST);
        return;
    }
    try {
        setFakeCronExpForTestIfNeeded(model);
        LocalRepoDescriptor repo = model.toDescriptor(repoValidator, repoDescriptorBuilder);
        Set<LocalReplicationDescriptor> replications = model.getReplicationDescriptors(replicationValidator,
                replicationDescriptorBuilder);
        int activeReplications = (int) replications.stream().filter(LocalReplicationDescriptor::isEnabled)
                .count();
        BiOptional
                .of(replications.stream().filter(replication -> replicationUrl.equals(replication.getUrl()))
                        .findFirst())
                .ifNotPresent(() -> response.error(
                        "No replication configuration exists for this repo  and url '" + replicationUrl + "'"))
                .ifPresent(
                        replication -> testReplicationTarget(repo, replication, response, activeReplications));
    } catch (RepoConfigException rce) {
        log.debug("Error testing local replication: ", rce);
        response.error(rce.getMessage()).responseCode(rce.getStatusCode());
    }
}

From source file:com.vsct.dt.strowgr.admin.gui.mapping.json.EntryPointMappingJson.java

@JsonCreator
public EntryPointMappingJson(@JsonProperty("haproxy") String haproxy, @JsonProperty("hapUser") String hapUser,
        @JsonProperty("hapVersion") String hapVersion, @JsonProperty("bindingId") int bindingId,
        @JsonProperty("frontends") Set<EntryPointFrontendMappingJson> frontends,
        @JsonProperty("backends") Set<EntryPointBackendMappingJson> backends,
        @JsonProperty("context") Map<String, String> context) {
    super(haproxy, hapUser, hapVersion, bindingId,
            frontends.stream().map(identity()).collect(Collectors.toSet()),
            backends.stream().map(identity()).collect(Collectors.toSet()), context);
}

From source file:org.ng200.openolympus.Application.java

private void reportMissingLocalisationKey(final String code) {
    try {/*  w ww .j  a  v a 2s.c om*/
        if (code.isEmpty() || Character.isUpperCase(code.charAt(0))) {
            return;
        }
        final File file = new File(new File(StorageSpace.STORAGE_PREFIX), "missingLocalisation.txt");
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        final Set<String> s = new TreeSet<>(Arrays.asList(FileUtils.readFileToString(file).split("\n")));
        s.add(code);
        FileUtils.writeStringToFile(file, s.stream().collect(Collectors.joining("\n")));
    } catch (final IOException e) {
        Application.logger.error("Couldn't add to missing key repo: {}", e);
    }
}

From source file:com.nike.cerberus.server.config.guice.CmsGuiceModule.java

@Provides
@Singleton/*w ww  . ja v a  2  s.  com*/
@Named("authProtectedEndpoints")
public List<Endpoint<?>> authProtectedEndpoints(@Named("appEndpoints") Set<Endpoint<?>> endpoints) {
    return endpoints.stream()
            .filter(i -> !(i instanceof HealthCheckEndpoint || i instanceof AuthenticateUser
                    || i instanceof MfaCheck || i instanceof AuthenticateIamRole
                    || i instanceof AuthenticateIamPrincipal))
            .collect(Collectors.toList());
}

From source file:com.vsct.dt.strowgr.admin.repository.consul.mapping.json.CommittingConfigurationJson.java

@JsonCreator
public CommittingConfigurationJson(@JsonProperty("correlationId") String correlationId,
        @JsonProperty("haproxy") String haproxy, @JsonProperty("haproxyVersion") String haproxyVersion,
        @JsonProperty("bindingId") int bindingId, @JsonProperty("hapUser") String hapUser,
        @JsonProperty("frontends") Set<EntryPointFrontendMappingJson> frontends,
        @JsonProperty("backends") Set<EntryPointBackendMappingJson> backends,
        @JsonProperty("context") Map<String, String> context) {
    super(haproxy, hapUser, haproxyVersion, bindingId,
            frontends.stream().map(identity()).collect(Collectors.toSet()),
            backends.stream().map(identity()).collect(Collectors.toSet()), context);
    this.correlationId = correlationId;
}

From source file:ai.grakn.engine.backgroundtasks.distributed.Scheduler.java

/**
 * Get all recurring tasks from the graph and schedule them
 *///from  w w  w.ja  v a 2 s.  c o  m
private void restartRecurringTasks() {
    Set<Pair<String, TaskState>> tasks = stateStorage.getTasks(null, null, null, 0, 0, true);
    tasks.stream().filter(p -> p.getValue().status() != STOPPED).forEach(p -> {
        // Not sure what is the right format for "no configuration", but somehow the configuration
        // here for a postprocessing task is "null": if we say that the configuration of a task
        // is a JSONObject, then an empty configuration ought to be {}
        String config = p.getValue().configuration() == null ? "{}" : p.getValue().configuration().toString();
        scheduleTask(p.getKey(), config, p.getValue());
    });
    LOG.debug("Scheduler restarted " + tasks.size() + " recurring tasks");
}