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:org.sardineproject.sbyod.rest.AppWebUser.java

/**
 * Ask if a user with userIp has a access to the service with serviceId.
 *
 * @param userIp_ the IP address of the user
 * @param serviceId_ the ID of the service
 * @return PRECONDITION_FAILED if some parameter was wrong
 *          "enabled : false" if service is disabled
 *          "enabled : true" if service is enabled
 *//*ww w.j a v  a  2  s  .  c  o m*/
@GET
@Path("/{userIp}/service/{serviceId}")
public Response getUserServices(@PathParam("userIp") String userIp_,
        @PathParam("serviceId") String serviceId_) {
    log.debug("AppWebUser: Getting rules for userIp = {} and serviceId = {}", userIp_, serviceId_);

    if (userIp_ == null || serviceId_ == null)
        return Response.status(Response.Status.PRECONDITION_FAILED).build();

    Set<Host> users;
    ServiceId serviceId;
    try {
        users = get(HostService.class).getHostsByIp(Ip4Address.valueOf(userIp_));
        serviceId = ServiceId.serviceId(serviceId_);
    } catch (Exception e) {
        return Response.status(Response.Status.PRECONDITION_FAILED).build();
    }

    // get all connections a user has activated
    Set<Connection> connections = Sets.newHashSet();
    users.forEach(u -> connections.addAll(get(ConnectionStore.class).getConnections(u)));

    // check if the connections contain a service with given service id
    if (connections.stream().map(Connection::getService).map(Service::id).collect(Collectors.toSet())
            .contains(serviceId)) {
        return Response.ok(ENABLED_TRUE).build();
    }
    return Response.ok(ENABLED_FALSE).build();
}

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

public Pair<String, CompletableFuture<List<DeviceCommand>>> sendSubscribeRequest(final Set<String> devices,
        final Set<String> names, final Date timestamp, final BiConsumer<DeviceCommand, String> callback)
        throws InterruptedException {

    final String subscriptionId = UUID.randomUUID().toString();
    Collection<CompletableFuture<Collection<DeviceCommand>>> futures = devices.stream()
            .map(device -> new CommandSubscribeRequest(subscriptionId, device, names, timestamp))
            .map(subscribeRequest -> {
                CompletableFuture<Collection<DeviceCommand>> future = new CompletableFuture<>();
                Consumer<Response> responseConsumer = response -> {
                    String resAction = response.getBody().getAction();
                    if (resAction.equals(Action.COMMAND_SUBSCRIBE_RESPONSE.name())) {
                        future.complete(response.getBody().cast(CommandSubscribeResponse.class).getCommands());
                    } else if (resAction.equals(Action.COMMAND_EVENT.name())) {
                        callback.accept(response.getBody().cast(CommandEvent.class).getCommand(),
                                subscriptionId);
                    } else {
                        logger.warn("Unknown action received from backend {}", resAction);
                    }/*from   w  w w .j av a 2 s .  c o m*/
                };
                Request request = Request.newBuilder().withBody(subscribeRequest)
                        .withPartitionKey(subscribeRequest.getDevice()).withSingleReply(false).build();
                rpcClient.call(request, responseConsumer);
                return future;
            }).collect(Collectors.toList());

    CompletableFuture<List<DeviceCommand>> future = CompletableFuture
            .allOf(futures.toArray(new CompletableFuture[futures.size()])).thenApply(v -> futures.stream()
                    .map(CompletableFuture::join).flatMap(Collection::stream).collect(Collectors.toList()));
    return Pair.of(subscriptionId, future);
}

From source file:com.netflix.spinnaker.orca.libdiffs.LibraryDiffTool.java

public LibraryDiffs calculateLibraryDiffs(List<Library> sourceLibs, List<Library> targetLibs) {
    LibraryDiffs libraryDiffs = new LibraryDiffs();
    libraryDiffs.setTotalLibraries(targetLibs != null ? targetLibs.size() : 0);

    BiFunction<Library, String, Diff> buildDiff = (Library library, String display) -> {
        Diff diff = new Diff();
        diff.setLibrary(includeLibraryDetails ? library : null);
        diff.setDisplayDiff(display);/*ww  w . j a v a  2s .c  om*/
        return diff;
    };

    try {
        if (!targetLibs.isEmpty() && !sourceLibs.isEmpty()) {
            Set<Library> uniqueCurrentList = new HashSet<>(targetLibs);
            Map<String, List<Library>> duplicatesMap = filterValues(
                    targetLibs.stream().collect(groupingBy(Library::getName)), it -> it.size() > 1);
            sourceLibs.forEach((Library oldLib) -> {
                if (!duplicatesMap.keySet().contains(oldLib.getName())) {
                    Library currentLib = uniqueCurrentList.stream()
                            .filter(it -> it.getName().equals(oldLib.getName())).findFirst().orElse(null);
                    if (currentLib != null) {
                        if (isEmpty(currentLib.getVersion()) || isEmpty(oldLib.getVersion())) {
                            libraryDiffs.getUnknown().add(buildDiff.apply(oldLib, oldLib.getName()));
                        } else if (currentLib.getVersion() != null && oldLib.getVersion() != null) {
                            int comparison = comparableLooseVersion.compare(currentLib.getVersion(),
                                    oldLib.getVersion());
                            if (comparison == 1) {
                                libraryDiffs.getUpgraded().add(buildDiff.apply(oldLib, format("%s: %s -> %s",
                                        oldLib.getName(), oldLib.getVersion(), currentLib.getVersion())));
                            }
                            if (comparison == -1) {
                                libraryDiffs.getDowngraded().add(buildDiff.apply(oldLib, format("%s: %s -> %s",
                                        oldLib.getName(), oldLib.getVersion(), currentLib.getVersion())));
                            }
                        }
                    } else {
                        libraryDiffs.getRemoved().add(buildDiff.apply(oldLib,
                                format("%s: %s", oldLib.getName(), oldLib.getVersion())));
                    }
                }
            });

            uniqueCurrentList.stream().filter(it -> !sourceLibs.contains(it))
                    .forEach(newLib -> libraryDiffs.getAdded().add(
                            buildDiff.apply(newLib, format("%s: %s", newLib.getName(), newLib.getVersion()))));

            duplicatesMap.forEach((key, value) -> {
                Library currentLib = targetLibs.stream().filter(it -> it.getName().equals(key)).findFirst()
                        .orElse(null);
                if (currentLib != null) {
                    boolean valid = value.stream().map(Library::getVersion).filter(Objects::nonNull)
                            .collect(groupingBy(Function.identity())).keySet().size() > 1;
                    if (valid) {
                        String displayDiff = format("%s: %s", currentLib.getName(),
                                value.stream().map(Library::getVersion).collect(joining(", ")));
                        libraryDiffs.getDuplicates().add(buildDiff.apply(currentLib, displayDiff));
                    }
                }
            });

            libraryDiffs
                    .setHasDiff(!libraryDiffs.getDowngraded().isEmpty() || !libraryDiffs.getUpgraded().isEmpty()
                            || !libraryDiffs.getAdded().isEmpty() || !libraryDiffs.getRemoved().isEmpty());
        }

        return libraryDiffs;
    } catch (Exception e) {
        throw new RuntimeException("Exception occurred while calculating library diffs", e);
    }
}

From source file:io.bifroest.commons.boot.BootLoaderNG.java

/**
 * Calculates the systems boot order. This is an iterative process: At
 * first, from a list with all available systems, all systems with no
 * dependencies are removed. This is repeated until the list is empty. If
 * there are systems still remaining, there is a dependency misconfiguration
 * and a CircularDependencyException is raised.
 *
 * @return A list with systems ordered by boot priority. The first element
 * needs to start first, the second after and so on.
 * @throws CircularDependencyException If two or more systems are
 * misconfigured, a circular dependency can occur. This happens e.g. if
 * system A depends on system B and system B also requires system A. This
 * cannot be resolved and an exception is thrown.
 *//*from   www  . j  a  v  a2  s  .  c  o m*/
private List<Subsystem<E>> getBootOrder() throws CircularDependencyException {
    HashMap<String, Subsystem<E>> bootSystems = new HashMap<>();
    HashMap<String, List<String>> systemDependencies = new HashMap<>();
    List<Subsystem<E>> result = new ArrayList<>();

    // shuffle systems to boot, so no one can forget system dependencies
    Collections.shuffle(this.systemsToBoot);

    this.systemsToBoot.stream().forEach((system) -> {
        bootSystems.put(system.getSystemIdentifier(), system);
        systemDependencies.put(system.getSystemIdentifier(), system.getRequiredSystems().stream()
                .filter(dep -> !dep.equals(system.getSystemIdentifier())).collect(Collectors.toList()));
    });
    // while there are dependencies to solve
    while (!systemDependencies.isEmpty()) {
        // Get all nodes without any dependency            
        Set<String> keys = systemDependencies.keySet();
        List<String> resolved = new ArrayList<>();
        keys.stream().forEach((key) -> {
            log.trace("Trying to resolve {}", key);
            Collection<String> dependencies = systemDependencies.get(key);
            log.trace("Found dependencies: {}", dependencies);
            if (dependencies == null || dependencies.isEmpty()) {
                log.trace("Marking {} as resolved", key);
                resolved.add(key);
            }
        });
        // if resolved is empty, we have a loop in the graph            
        if (resolved.isEmpty()) {
            String msg = "Loop in graph! This should not happen. Check your dependencies! Remaining systems: "
                    + keys.toString();
            throw new CircularDependencyException(msg, systemDependencies);
        }

        // remove systemsToBoot found from dependency graph
        resolved.stream().forEach((systemIdentifier) -> {
            systemDependencies.remove(systemIdentifier);
            result.add(bootSystems.get(systemIdentifier));
        });

        // remove dependencies
        Set<String> systemDependenciesKeys = systemDependencies.keySet();
        systemDependenciesKeys.stream().map((key) -> systemDependencies.get(key)).forEach((values) -> {
            resolved.stream().forEach((resolvedValue) -> {
                values.removeIf(v -> v.equals(resolvedValue));
            });
        });
    }
    return result;
}

From source file:com.thinkbiganalytics.security.rest.controller.AccessControlController.java

@GET
@Path("{name}/allowed")
@Produces(MediaType.APPLICATION_JSON)// w  w  w.  j  a  v a2  s . c o  m
@ApiOperation("Gets the list of allowed actions for a principal.")
@ApiResponses({ @ApiResponse(code = 200, message = "Returns the actions.", response = ActionGroup.class),
        @ApiResponse(code = 404, message = "The given name was not found.", response = RestResponseStatus.class) })
public ActionGroup getAllowedActions(@PathParam("name") String moduleName,
        @QueryParam("user") Set<String> userNames, @QueryParam("group") Set<String> groupNames) {

    Set<? extends Principal> users = Arrays.stream(this.actionsTransform.asUserPrincipals(userNames))
            .collect(Collectors.toSet());
    Set<? extends Principal> groups = Arrays.stream(this.actionsTransform.asGroupPrincipals(groupNames))
            .collect(Collectors.toSet());
    Principal[] principals = Stream.concat(users.stream(), groups.stream()).toArray(Principal[]::new);

    // Retrieve the allowed actions by executing the query as the specified user/groups 
    return metadata.read(() -> {
        return actionsProvider.getAllowedActions(moduleName)
                .map(this.actionsTransform.toActionGroup(AllowedActions.SERVICES))
                .orElseThrow(() -> new WebApplicationException("The available service actions were not found",
                        Status.NOT_FOUND));
    }, principals);
}

From source file:com.yahoo.elide.graphql.ModelBuilder.java

/**
 * Builds a GraphQL schema.//from   w  w w. j  a v a2s. co m
 * @return The built schema.
 */
public GraphQLSchema build() {
    Set<Class<?>> allClasses = dictionary.getBindings();

    if (allClasses.isEmpty()) {
        throw new IllegalArgumentException("None of the provided classes are exported by Elide");
    }

    Set<Class<?>> rootClasses = allClasses.stream().filter(dictionary::isRoot).collect(Collectors.toSet());

    /*
     * Walk the object graph (avoiding cycles) and construct the GraphQL input object types.
     */
    dictionary.walkEntityGraph(rootClasses, this::buildInputObjectStub);
    resolveInputObjectRelationships();

    /* Construct root object */
    GraphQLObjectType.Builder root = newObject().name("__root");
    for (Class<?> clazz : rootClasses) {
        String entityName = dictionary.getJsonAliasFor(clazz);
        root.field(newFieldDefinition().name(entityName).dataFetcher(dataFetcher).argument(relationshipOpArg)
                .argument(idArgument).argument(filterArgument).argument(sortArgument)
                .argument(pageFirstArgument).argument(pageOffsetArgument)
                .argument(buildInputObjectArgument(clazz, true)).type(buildConnectionObject(clazz)));
    }

    GraphQLObjectType queryRoot = root.build();
    GraphQLObjectType mutationRoot = root.name("__mutation_root").build();

    /*
     * Walk the object graph (avoiding cycles) and construct the GraphQL output object types.
     */
    dictionary.walkEntityGraph(rootClasses, this::buildConnectionObject);

    /* Construct the schema */
    GraphQLSchema schema = GraphQLSchema.newSchema().query(queryRoot).mutation(mutationRoot)
            .build(new HashSet<>(
                    CollectionUtils.union(connectionObjectRegistry.values(), inputObjectRegistry.values())));

    return schema;
}

From source file:io.gravitee.management.service.impl.ApiKeyServiceImpl.java

@Override
public Set<ApiKeyEntity> findAll(String applicationName, String apiName) {
    try {/*w w  w  .  j  a va 2 s.  c o  m*/
        LOGGER.debug("Find all API Keys for {} - {}", applicationName, apiName);

        final Set<ApiKey> apiKeys = apiKeyRepository.findByApplicationAndApi(applicationName, apiName);

        if (apiKeys == null || apiKeys.isEmpty()) {
            return emptySet();
        }

        final Set<ApiKeyEntity> apiKeyEntities = new HashSet<>(apiKeys.size());

        apiKeyEntities.addAll(apiKeys.stream().map(ApiKeyServiceImpl::convert).collect(Collectors.toSet()));

        return apiKeyEntities;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find all API Keys for {} - {}", applicationName, apiName);
        throw new TechnicalManagementException("An error occurs while trying to find find all API Keys for "
                + applicationName + " - " + apiName, ex);
    }
}

From source file:nu.yona.server.subscriptions.service.BuddyService.java

private Set<Buddy> getBuddyEntities(Set<UUID> buddyIds) {
    return buddyIds.stream().map(this::getEntityById).collect(Collectors.toSet());
}

From source file:com.thinkbiganalytics.feedmgr.service.template.DefaultFeedManagerTemplateService.java

@Override
public List<RegisteredTemplate.Processor> getRegisteredTemplateProcessors(String templateId,
        boolean includeReusableProcessors) {
    List<RegisteredTemplate.Processor> processorProperties = new ArrayList<>();

    RegisteredTemplate template = registeredTemplateService
            .findRegisteredTemplate(new RegisteredTemplateRequest.Builder().templateId(templateId)
                    .nifiTemplateId(templateId).includeAllProperties(true).build());
    if (template != null) {
        template.initializeProcessors();
        processorProperties.addAll(template.getInputProcessors());
        processorProperties.addAll(template.getNonInputProcessors());

        if (includeReusableProcessors && template.getReusableTemplateConnections() != null
                && !template.getReusableTemplateConnections().isEmpty()) {

            //1 fetch ports in reusable templates
            Map<String, PortDTO> reusableTemplateInputPorts = new HashMap<>();
            Set<PortDTO> ports = getReusableFeedInputPorts();
            if (ports != null) {
                ports.stream().forEach(portDTO -> reusableTemplateInputPorts.put(portDTO.getName(), portDTO));
            }//  ww  w  .  j  a  v  a  2  s.c o  m

            //match to the name
            List<String> matchingPortIds = template.getReusableTemplateConnections().stream().filter(
                    conn -> reusableTemplateInputPorts.containsKey(conn.getReusableTemplateInputPortName()))
                    .map(reusableTemplateConnectionInfo -> reusableTemplateInputPorts
                            .get(reusableTemplateConnectionInfo.getReusableTemplateInputPortName()).getId())
                    .collect(Collectors.toList());

            List<RegisteredTemplate.Processor> reusableProcessors = getReusableTemplateProcessorsForInputPorts(
                    matchingPortIds);
            processorProperties.addAll(reusableProcessors);
        }
    }
    return processorProperties;

}

From source file:io.swagger.jaxrs.SynapseReader.java

@Override
public Swagger read(Set<Class<?>> classes) {

    Map<Class<?>, ReaderListener> listeners = new HashMap<>();

    classes.stream().filter(cls -> (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)))
            .forEach((cls) -> {//from   w ww . ja v  a 2 s .co  m
                try {
                    listeners.put(cls, (ReaderListener) cls.newInstance());
                } catch (InstantiationException | IllegalAccessException e) {
                    logger.error("Failed to create ReaderListener", e);
                }
            });

    listeners.values().stream().forEach((listener) -> {
        try {
            listener.beforeScan(this, getSwagger());
        } catch (Exception e) {
            logger.error(
                    "Unexpected error invoking beforeScan listener [" + listener.getClass().getName() + "]", e);
        }
    });

    // process SwaggerDefinitions first - so we get tags in desired order
    classes.stream().forEach((cls) -> {
        SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);
        if (swaggerDefinition != null) {
            readSwaggerConfig(cls, swaggerDefinition);
        }
    });

    classes.stream().forEach((cls) -> {
        read(cls, "", null, false, new HashSet<String>(), new HashSet<String>(), new HashMap<String, Tag>(),
                new ArrayList<Parameter>(), new HashSet<Class<?>>());
    });

    listeners.values().stream().forEach((listener) -> {
        try {
            listener.afterScan(this, getSwagger());
        } catch (Exception e) {
            logger.error("Unexpected error invoking afterScan listener [" + listener.getClass().getName() + "]",
                    e);
        }
    });

    return getSwagger();
}