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.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementModelTransform.java

/**
 * Transforms the specified domain objects to REST objects.
 *
 * @param domain the SLA domain object//ww w  .jav a2s.  com
 * @param feeds  the feed domain objects
 * @param deep   {@code true} to include action configurations
 * @return the SLA REST object
 */
public FeedServiceLevelAgreement toModel(ServiceLevelAgreement domain,
        Set<com.thinkbiganalytics.metadata.api.feed.Feed> feeds, boolean deep) {
    com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement slaModel = toModel(domain, deep);
    FeedServiceLevelAgreement feedServiceLevelAgreement = new FeedServiceLevelAgreement(slaModel);
    boolean canEdit = false;
    boolean canView = true;
    if (feeds != null && !feeds.isEmpty()) {
        final Set<Feed> feedModels = feeds.stream().filter(feed -> feed != null).map(model::domainToFeed)
                .collect(Collectors.toSet());
        feedServiceLevelAgreement.setFeeds(feedModels);
        if (accessController.isEntityAccessControlled()) {
            //set the flag on the sla edit to true only if the user has access to edit the feeds assigned to this sla
            canEdit = feeds.stream()
                    .allMatch(feed -> feed.getAllowedActions().hasPermission(FeedAccessControl.EDIT_DETAILS));
            //can view
            canView = feeds.stream()
                    .allMatch(feed -> feed.getAllowedActions().hasPermission(FeedAccessControl.ACCESS_FEED));
        } else {
            canEdit = this.accessController.hasPermission(AccessController.SERVICES,
                    FeedServicesAccessControl.EDIT_SERVICE_LEVEL_AGREEMENTS);
        }

    } else {
        canEdit = this.accessController.hasPermission(AccessController.SERVICES,
                FeedServicesAccessControl.EDIT_SERVICE_LEVEL_AGREEMENTS);
    }
    slaModel.setCanEdit(canEdit);
    feedServiceLevelAgreement.setCanEdit(canEdit);
    return feedServiceLevelAgreement;
}

From source file:net.solarnetwork.node.backup.s3.S3BackupService.java

private List<Backup> getAvailableBackupsInternal() {
    CachedResult<List<Backup>> cached = cachedBackupList.get();
    if (cached != null && cached.isValid()) {
        return cached.getResult();
    }//from  w w w. j  a va 2s.  c om
    S3Client client = this.s3Client;
    if (EnumSet.of(BackupStatus.Unconfigured, BackupStatus.Error).contains(status.get())) {
        return Collections.emptyList();
    }
    final String objectKeyPrefix = objectKeyForPath(META_OBJECT_KEY_PREFIX);
    try {
        Set<S3ObjectReference> objs = client.listObjects(objectKeyPrefix);
        List<Backup> result = objs.stream()
                .map(o -> new SimpleBackup(
                        identityFromBackupKey(pathWithoutPrefix(o.getKey(), objectKeyPrefix)), null, true))
                .collect(Collectors.toList());
        cachedBackupList.compareAndSet(cached,
                new CachedResult<List<Backup>>(result, cacheSeconds, TimeUnit.SECONDS));
        return result;
    } catch (RemoteServiceException | IOException e) {
        log.warn("Error listing S3 avaialble backups with prefix {}: {}", objectKeyPrefix, e.getMessage());
        return Collections.emptyList();
    }
}

From source file:com.ggvaidya.scinames.complexquery.ComplexQueryViewController.java

public void updateTableWithChanges(Project project, Set<Change> changesToDisplay, List<Dataset> datasets) {
    List<Change> changes = changesToDisplay.stream().sorted((a, b) -> a.getDataset().compareTo(b.getDataset()))
            .collect(Collectors.toList());

    NameClusterManager ncm = project.getNameClusterManager();

    // And add tablecolumns for the rest.
    dataTableView.getColumns().clear();/*from   w  w w.j a v a2  s . c o m*/
    dataTableView.getColumns().addAll(createTableColumnFromChange("id", ch -> ch.getId().toString()),
            createTableColumnFromChange("dataset", ch -> ch.getDataset().getName()),
            createTableColumnFromChange("type", ch -> ch.getType().getType()),
            createTableColumnFromChange("from", ch -> ch.getFromString()),
            createTableColumnFromChange("from_name_cluster_ids",
                    ch -> ncm.getClusters(ch.getFrom()).stream().map(cl -> cl.getId().toString())
                            .collect(Collectors.joining(" and "))),
            createTableColumnFromChange("from_name_clusters",
                    ch -> ncm.getClusters(ch.getFrom()).stream()
                            .map(cl -> cl.getNames().stream().map(n -> n.getFullName())
                                    .collect(Collectors.joining("; ")))
                            .collect(Collectors.joining(" and "))),
            createTableColumnFromChange("to", ch -> ch.getToString()),
            createTableColumnFromChange("to_name_cluster_ids",
                    ch -> ncm.getClusters(ch.getTo()).stream().map(cl -> cl.getId().toString())
                            .collect(Collectors.joining(" and "))),
            createTableColumnFromChange("to_name_clusters",
                    ch -> ncm.getClusters(ch.getTo()).stream()
                            .map(cl -> cl.getNames().stream().map(n -> n.getFullName())
                                    .collect(Collectors.joining("; ")))
                            .collect(Collectors.joining(" and "))),
            createTableColumnFromChange("filter_status",
                    ch -> project.getChangeFilter().test(ch) ? "retained" : "eliminated"),
            createTableColumnFromChange("properties",
                    ch -> ch.getProperties().entrySet().stream()
                            .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted()
                            .collect(Collectors.joining("; "))),
            createTableColumnFromChange("citations", ch -> ch.getCitationStream().map(cit -> cit.getCitation())
                    .sorted().collect(Collectors.joining("; "))));

    dataTableView.getItems().clear();
    dataTableView.getItems().addAll(changes);

    dataTableView.refresh();

    // Fill in status text field.
    statusTextField.setText(dataTableView.getItems().size() + " changes across "
            + changes.stream().map(ch -> ch.getDataset()).distinct().count() + " distinct datasets");
}

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

@Override
public Set<ApplicationEntity> findByUser(String username) {
    try {/*from ww w.  j av  a2s . c  om*/
        LOGGER.debug("Find applications for user {}", username);

        final Set<Application> applications = applicationRepository.findByUser(username, null);

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

        final Set<ApplicationEntity> applicationEntities = new HashSet<>(applications.size());

        applicationEntities
                .addAll(applications.stream().map(ApplicationServiceImpl::convert).collect(Collectors.toSet()));

        return applicationEntities;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find applications for user {}", username, ex);
        throw new TechnicalManagementException(
                "An error occurs while trying to find applications for user " + username, ex);
    }
}

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

private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource,
        Set<String> parentConsumes, Set<String> parentProduces, Map<String, Tag> parentTags,
        List<Parameter> parentParameters, Set<Class<?>> scannedResources) {
    Api api = (Api) cls.getAnnotation(Api.class);
    boolean isServiceAnnotated = (cls.getAnnotation(Service.class) != null);
    boolean isMarkedService = SynapseEndpointServiceMarker.class.isAssignableFrom(cls) && !cls.isInterface();

    Map<String, Tag> tags = new HashMap<>();
    List<SecurityRequirement> securities = new ArrayList<>();

    final List<String> consumes = new ArrayList<>();
    final List<String> produces = new ArrayList<>();
    final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class);

    /*/*from  w  w  w .j a va 2s  .  c  o  m*/
     *   Only read @Api configuration if:
     *
     *   @Api annotated AND
     *   @Path annotated AND
     *   @Api (hidden) false
     *   isSubresource false
     *
     *   OR
     *
     *   @Api annotated AND
     *   isSubresource true
     *   @Api (hidden) false
     *
     */
    final boolean readable = ((api != null && (isServiceAnnotated || isMarkedService) && !api.hidden()
            && !isSubresource) || (api != null && !api.hidden() && isSubresource)
            || (api != null && !api.hidden() && getConfig().isScanAllResources()));

    if (readable) {
        // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present
        Set<String> tagStrings = extractTags(api);
        tagStrings.stream().forEach((tagString) -> {
            Tag tag = new Tag().name(tagString);
            tags.put(tagString, tag);
        });
        tags.keySet().stream().forEach((tagName) -> {
            getSwagger().tag(tags.get(tagName));
        });

        if (api != null && !api.produces().isEmpty()) {
            produces.add(api.produces());
            //            } else if (cls.getAnnotation(Produces.class) != null) {
            //                produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value());
        }
        if (api != null && !api.consumes().isEmpty()) {
            consumes.add(api.consumes());
            //            } else if (cls.getAnnotation(Consumes.class) != null) {
            //                consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value());
        }
        if (api != null) {
            globalSchemes.addAll(parseSchemes(api.protocols()));
        }
        Authorization[] authorizations = api != null ? api.authorizations() : new Authorization[] {};

        for (Authorization auth : authorizations) {
            if (auth.value() != null && !"".equals(auth.value())) {
                SecurityRequirement security = new SecurityRequirement();
                security.setName(auth.value());
                AuthorizationScope[] scopes = auth.scopes();
                for (AuthorizationScope scope : scopes) {
                    if (scope.scope() != null && !"".equals(scope.scope())) {
                        security.addScope(scope.scope());
                    }
                }
                securities.add(security);
            }
        }
    }

    if (isSubresource) {
        if (parentTags != null) {
            tags.putAll(parentTags);
        }
    }

    if (readable || (api == null && getConfig().isScanAllResources())) {
        // merge consumes, produces

        // look for method-level annotated properties
        // handle sub-resources by looking at return type
        final List<Parameter> globalParameters = new ArrayList<>();

        // look for constructor-level annotated properties
        globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, getSwagger()));

        // look for field-level annotated properties
        globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, getSwagger()));

        // parse the method
        final Service serviceAnnotation = ReflectionUtils.getAnnotation(cls, Service.class);

        for (Method method : cls.getMethods()) {
            if (ReflectionUtils.isOverriddenMethod(method, cls)) {
                //is this a method overriden by one in a subclass?
                continue;
            }

            final RequestMapping requestMappingAnnotation = isServiceAnnotated
                    ? ReflectionUtils.getAnnotation(method, RequestMapping.class)
                    : null;
            final List<String> operationPaths = isServiceAnnotated
                    ? getPaths(serviceAnnotation, method, parentPath)
                    : isMarkedService ? getPaths(method) : null;

            Map<String, String> regexMap = new HashMap<>();

            if (operationPaths == null) {
                continue;
            }

            operationPaths.stream().map(op -> PathUtils.parsePath(op, regexMap))
                    .filter(op -> op != null && !MethodProcessor.isIgnored(op, getConfig())).forEach(op -> {
                        final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method,
                                ApiOperation.class);
                        List<String> httpMethods = extractOperationMethods(apiOperation, method,
                                SwaggerExtensions.chain());
                        if (httpMethods != null && !httpMethods.isEmpty()) {
                            httpMethods.forEach(hm -> {
                                Operation operation = null;
                                if (apiOperation != null || getConfig().isScanAllResources() || (hm != null)
                                        || requestMappingAnnotation != null || isMarkedService) {
                                    operation = MethodProcessor.parseMethod(cls, method, globalParameters,
                                            getSwagger());
                                }
                                if (operation != null) {

                                    if (parentParameters != null && !parentParameters.isEmpty()) {
                                        //add parent parameters to this Operation
                                        for (Parameter param : parentParameters) {
                                            operation.parameter(param);
                                        }
                                    }
                                    prepareOperation(operation, apiOperation, regexMap, globalSchemes);

                                    Set<String> apiConsumes = new HashSet<>(consumes);
                                    if (parentConsumes != null) {
                                        apiConsumes.addAll(parentConsumes);
                                        if (operation.getConsumes() != null) {
                                            apiConsumes.addAll(operation.getConsumes());
                                        }
                                    }

                                    Set<String> apiProduces = new HashSet<>(produces);
                                    if (parentProduces != null) {
                                        apiProduces.addAll(parentProduces);
                                        if (operation.getProduces() != null) {
                                            apiProduces.addAll(operation.getProduces());
                                        }
                                    }

                                    final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(
                                            method);
                                    if (subResource != null && !scannedResources.contains(subResource)) {
                                        scannedResources.add(subResource);
                                        read(subResource, op, hm, true, apiConsumes, apiProduces, tags,
                                                operation.getParameters(), scannedResources);

                                        // remove the sub resource so that it can visit it later in another path
                                        // but we have a room for optimization in the future to reuse the scanned result
                                        // by caching the scanned resources in the reader instance to avoid actual scanning
                                        // the the resources again
                                        scannedResources.remove(subResource);
                                    }

                                    if (apiOperation != null) {
                                        boolean hasExplicitTag = false;
                                        for (String tag : apiOperation.tags()) {
                                            if (!"".equals(tag)) {
                                                operation.tag(tag);
                                                getSwagger().tag(new Tag().name(tag));
                                            }
                                        }

                                        operation.getVendorExtensions().putAll(
                                                BaseReaderUtils.parseExtensions(apiOperation.extensions()));
                                    }

                                    if (operation.getConsumes() == null) {
                                        for (String mediaType : apiConsumes) {
                                            operation.consumes(mediaType);
                                        }
                                    }
                                    if (operation.getProduces() == null) {
                                        for (String mediaType : apiProduces) {
                                            operation.produces(mediaType);
                                        }
                                    }

                                    if (operation.getTags() == null) {
                                        for (String tagString : tags.keySet()) {
                                            operation.tag(tagString);
                                        }
                                    }
                                    // Only add global @Api securities if operation doesn't already have more specific securities
                                    if (operation.getSecurity() == null) {
                                        for (SecurityRequirement security : securities) {
                                            operation.security(security);
                                        }
                                    }

                                    Path path = getSwagger().getPath(op);
                                    if (path == null) {
                                        path = new Path();
                                        getSwagger().path(op, path);
                                    }
                                    path.set(hm, operation);

                                    readImplicitParameters(method, operation);
                                }
                            });
                        }

                    });
        }
    }

    return getSwagger();
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.jclouds.aws.AWSEC2JCloudsProviderTest.java

@Test
public void testCreateInstance() throws NumberFormatException, RunNodesException {

    Infrastructure infratructure = InfrastructureFixture.getInfrastructure("id-aws", "aws", "endPoint",
            "userName", "password");

    when(computeServiceCache.getComputeService(infratructure)).thenReturn(computeService);

    when(computeService.templateBuilder()).thenReturn(templateBuilder);

    Instance instance = InstanceFixture.getInstance("instance-id", "instance-name", "image", "2", "512", "2",
            "77.154.227.148", "1.0.0.2", "running");

    when(templateBuilder.minRam(Integer.parseInt(instance.getHardware().getMinRam())))
            .thenReturn(templateBuilder);

    when(templateBuilder.minCores(Double.parseDouble(instance.getHardware().getMinCores())))
            .thenReturn(templateBuilder);

    when(templateBuilder.imageId(instance.getImage())).thenReturn(templateBuilder);

    when(templateBuilder.build()).thenReturn(template);

    Set nodes = Sets.newHashSet();
    NodeMetadataImpl node = mock(NodeMetadataImpl.class);
    when(node.getId()).thenReturn("RegionOne/1cde5a56-27a6-46ce-bdb7-8b01b8fe2592");
    when(node.getName()).thenReturn("someName");
    Hardware hardware = mock(Hardware.class);
    when(hardware.getProcessors()).thenReturn(Lists.newArrayList());
    when(node.getHardware()).thenReturn(hardware);
    when(hardware.getType()).thenReturn(ComputeType.HARDWARE);
    when(node.getStatus()).thenReturn(Status.RUNNING);
    nodes.add(node);//from  w w  w  .j av a  2  s.  c om
    when(computeService.listNodes()).thenReturn(nodes);

    when(computeService.createNodesInGroup(instance.getTag(), Integer.parseInt(instance.getNumber()), template))
            .thenReturn(nodes);

    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getOptions()).thenReturn(templateOptions);

    when(templateOptions.runAsRoot(true)).thenReturn(templateOptions);
    when(templateOptions.as(AWSEC2TemplateOptions.class)).thenReturn(awsEC2TemplateOptions);

    // Tags
    when(tagManager.retrieveAllTags(any(Options.class))).thenReturn(Lists.newArrayList(connectorIaasTag));

    Set<Instance> created = jcloudsProvider.createInstance(infratructure, instance);

    assertThat(created.size(), is(1));

    assertThat(created.stream().findAny().get().getId(), is("RegionOne/1cde5a56-27a6-46ce-bdb7-8b01b8fe2592"));

    verify(computeService, times(1)).createNodesInGroup(instance.getTag(),
            Integer.parseInt(instance.getNumber()), template);

}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.jclouds.aws.AWSEC2JCloudsProviderTest.java

@Test
public void testCreateInstanceWithSecurityGroup() throws NumberFormatException, RunNodesException {

    Infrastructure infratructure = InfrastructureFixture.getInfrastructure("id-aws", "aws", "endPoint",
            "userName", "password");

    when(computeServiceCache.getComputeService(infratructure)).thenReturn(computeService);

    when(computeService.templateBuilder()).thenReturn(templateBuilder);

    Instance instance = InstanceFixture.getInstanceWithSecurityGroup("instance-id", "instance-name", "image",
            "2", "512", "2", "77.154.227.148", "1.0.0.2", "running", "default");

    when(templateBuilder.minRam(Integer.parseInt(instance.getHardware().getMinRam())))
            .thenReturn(templateBuilder);

    when(templateBuilder.minCores(Double.parseDouble(instance.getHardware().getMinCores())))
            .thenReturn(templateBuilder);

    when(templateBuilder.imageId(instance.getImage())).thenReturn(templateBuilder);

    when(templateBuilder.build()).thenReturn(template);

    Set nodes = Sets.newHashSet();
    NodeMetadataImpl node = mock(NodeMetadataImpl.class);
    when(node.getId()).thenReturn("RegionOne/1cde5a56-27a6-46ce-bdb7-8b01b8fe2592");
    when(node.getName()).thenReturn("someName");
    Hardware hardware = mock(Hardware.class);
    when(hardware.getProcessors()).thenReturn(Lists.newArrayList());
    when(node.getHardware()).thenReturn(hardware);
    when(hardware.getType()).thenReturn(ComputeType.HARDWARE);
    when(node.getStatus()).thenReturn(Status.RUNNING);
    nodes.add(node);/*from  w ww  .  j  a  v  a2  s. c  o m*/
    when(computeService.listNodes()).thenReturn(nodes);

    when(computeService.createNodesInGroup(instance.getTag(), Integer.parseInt(instance.getNumber()), template))
            .thenReturn(nodes);

    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getOptions()).thenReturn(templateOptions);

    when(templateOptions.runAsRoot(true)).thenReturn(templateOptions);

    when(templateOptions.as(AWSEC2TemplateOptions.class)).thenReturn(awsEC2TemplateOptions);

    Set<Instance> created = jcloudsProvider.createInstance(infratructure, instance);

    assertThat(created.size(), is(1));

    assertThat(created.stream().findAny().get().getId(), is("RegionOne/1cde5a56-27a6-46ce-bdb7-8b01b8fe2592"));

    verify(computeService, times(1)).createNodesInGroup(instance.getTag(),
            Integer.parseInt(instance.getNumber()), template);

    verify(awsEC2TemplateOptions, times(1)).securityGroups(instance.getOptions().getSecurityGroupNames());

}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.jclouds.aws.AWSEC2JCloudsProviderTest.java

@Test
public void testCreateInstanceWithSubnetId() throws NumberFormatException, RunNodesException {

    Infrastructure infratructure = InfrastructureFixture.getInfrastructure("id-aws", "aws", "endPoint",
            "userName", "password");

    when(computeServiceCache.getComputeService(infratructure)).thenReturn(computeService);

    when(computeService.templateBuilder()).thenReturn(templateBuilder);

    Instance instance = InstanceFixture.getInstanceWithSubnetId("instance-id", "instance-name", "image", "2",
            "512", "2", "77.154.227.148", "1.0.0.2", "running", "127.0.0.1");

    when(templateBuilder.minRam(Integer.parseInt(instance.getHardware().getMinRam())))
            .thenReturn(templateBuilder);

    when(templateBuilder.minCores(Double.parseDouble(instance.getHardware().getMinCores())))
            .thenReturn(templateBuilder);

    when(templateBuilder.imageId(instance.getImage())).thenReturn(templateBuilder);

    when(templateBuilder.build()).thenReturn(template);

    Set nodes = Sets.newHashSet();
    NodeMetadataImpl node = mock(NodeMetadataImpl.class);
    when(node.getId()).thenReturn("RegionOne/1cde5a56-27a6-46ce-bdb7-8b01b8fe2592");
    when(node.getName()).thenReturn("someName");
    Hardware hardware = mock(Hardware.class);
    when(hardware.getProcessors()).thenReturn(Lists.newArrayList());
    when(node.getHardware()).thenReturn(hardware);
    when(hardware.getType()).thenReturn(ComputeType.HARDWARE);
    when(node.getStatus()).thenReturn(Status.RUNNING);
    nodes.add(node);/*from  www .  j  a va2  s  . co  m*/
    when(computeService.listNodes()).thenReturn(nodes);

    when(computeService.createNodesInGroup(instance.getTag(), Integer.parseInt(instance.getNumber()), template))
            .thenReturn(nodes);

    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getOptions()).thenReturn(templateOptions);

    when(templateOptions.runAsRoot(true)).thenReturn(templateOptions);

    when(templateOptions.as(AWSEC2TemplateOptions.class)).thenReturn(awsEC2TemplateOptions);

    Set<Instance> created = jcloudsProvider.createInstance(infratructure, instance);

    assertThat(created.size(), is(1));

    assertThat(created.stream().findAny().get().getId(), is("RegionOne/1cde5a56-27a6-46ce-bdb7-8b01b8fe2592"));

    verify(computeService, times(1)).createNodesInGroup(instance.getTag(),
            Integer.parseInt(instance.getNumber()), template);

    verify(awsEC2TemplateOptions, times(1)).subnetId(instance.getOptions().getSubnetId());

}

From source file:com.newtranx.util.mysql.fabric.SpringQueryAllShardsAspect.java

@Around("@annotation(com.newtranx.util.mysql.fabric.QueryAllShards)")
public Object union(ProceedingJoinPoint pjp) throws Throwable {
    Method method = AspectJUtils.getMethod(pjp);
    QueryAllShards annotation = method.getAnnotation(QueryAllShards.class);
    String table = annotation.table();
    log.debug("Table=" + table);
    Set<String> groups = groupsCache.get(cacheKey);
    log.debug("ServerGroups=" + groups);
    List<Object> list;
    boolean readOnly = annotation.readOnly();
    Pattern excludePattern;/*from   www  .  j av a  2s.co  m*/
    String excludeRegex = annotation.excludeShardsPatternRegex();
    if (!StringUtils.isEmpty(excludeRegex)) {
        excludePattern = Pattern.compile(excludeRegex);
    } else {
        excludePattern = null;
    }

    Function<Boolean, List<Object>> computeFunction = (par) -> {
        Stream<String> stream = groups.stream();
        if (par)
            stream = stream.parallel();
        return stream.filter(gp -> {
            boolean exclude = excludePattern != null && excludePattern.matcher(gp).matches();
            if (exclude) {
                log.debug("Skipping group:" + gp);
            }
            return !exclude;
        }).map(gp -> {
            log.debug("Querying group: " + gp);
            ds.whenNewConnection().doInit(conn -> conn.setServerGroupName(gp))
                    .doInit(conn -> conn.setReadOnly(readOnly));
            try {
                return pjp.proceed();
            } catch (Throwable t) {
                throw Exceptions.propagate(t);
            } finally {
                ds.clearInitOps();
            }
        }).collect(Collectors.toList());
    };

    if (StringUtils.isEmpty(annotation.parallelPool())) {
        list = computeFunction.apply(false);
    } else {
        ForkJoinPool pool;
        if ("!jdkCommon".equals(annotation.parallelPool()))
            pool = ForkJoinPool.commonPool();
        else
            pool = applicationContext.getBean(annotation.parallelPool(), ForkJoinPool.class);
        log.debug("Executing queries in parallel, pool=" + pool);
        list = pool.submit(() -> {
            return computeFunction.apply(true);
        }).get();
    }
    Aggregator aggregator;
    try {
        aggregator = (Aggregator) annotation.aggregator().getDeclaredMethod("getInstance", EMPTY_PARAM)
                .invoke(null, EMPTY_ARGS);
    } catch (Exception e) {
        log.warn("Can not get singleton for class " + annotation.aggregator().getName()
                + ", creating new instance");
        aggregator = annotation.aggregator().newInstance();
    }
    return aggregator.apply(list);
}

From source file:com.foilen.smalltools.spring.messagesource.UsageMonitoringMessageSource.java

private void init() {

    // Check the base folder
    File basenameFile = new File(basename);
    logger.info("Base name is {}", basename);
    File directory = basenameFile.getParentFile();
    logger.info("Base directory is {}", directory.getAbsoluteFile());
    if (!directory.exists()) {
        throw new SmallToolsException("Directory: " + directory.getAbsolutePath() + " does not exists");
    }//  w  ww. ja  v a2s. com

    tmpUsed = new File(directory.getAbsolutePath() + File.separatorChar + "_messages_usage.txt");

    // Check the files in it
    String startswith = basenameFile.getName() + "_";
    String endswith = ".properties";
    for (File file : directory.listFiles(
            (FilenameFilter) (dir, name) -> name.startsWith(startswith) && name.endsWith(endswith))) {
        // Create the locale
        logger.info("Found messages file {}", directory.getAbsoluteFile());
        String filename = file.getName();
        String localePart = filename.substring(startswith.length(), filename.length() - endswith.length());
        Locale locale = new Locale(localePart);
        logger.info("Locale is {} -> {}", localePart, locale);
        filePerLocale.put(locale, file);

        // Load the file
        Properties properties = new Properties();
        try (FileInputStream inputStream = new FileInputStream(file)) {
            properties.load(new InputStreamReader(inputStream, CharsetTools.UTF_8));
        } catch (IOException e) {
            logger.error("Problem reading the property file {}", file.getAbsoluteFile(), e);
            throw new SmallToolsException("Problem reading the file", e);
        }

        // Check codes and save values
        Map<String, String> messages = new HashMap<>();
        messagesPerLocale.put(locale, messages);
        for (Object key : properties.keySet()) {
            String name = (String) key;
            String value = properties.getProperty(name);
            allCodesInFiles.add(name);
            messages.put(name, value);
        }

    }

    // Add missing codes in all the maps (copy one that has it)
    for (Locale locale : filePerLocale.keySet()) {
        Set<String> missingCodes = new HashSet<>();
        Map<String, String> messagesForCurrentLocale = messagesPerLocale.get(locale);

        // Get the ones missing
        missingCodes.addAll(allCodesInFiles);
        missingCodes.removeAll(messagesForCurrentLocale.keySet());

        for (String missingCode : missingCodes) {
            logger.info("Locale {} was missing code {}", locale, missingCode);

            String codeValue = findAnyValue(missingCode);
            messagesForCurrentLocale.put(missingCode, codeValue);
        }
    }

    // Load the already known codes
    if (tmpUsed.exists()) {
        for (String line : FileTools.readFileLinesIteration(tmpUsed.getAbsolutePath())) {
            knownUsedCodes.add(line);
        }
    }

    smoothTrigger = new SmoothTrigger(() -> {

        synchronized (lock) {

            logger.info("Begin saving locale files");

            // Go through each locale
            for (Entry<Locale, File> entry : filePerLocale.entrySet()) {
                Map<String, String> messages = messagesPerLocale.get(entry.getKey());

                try (PrintWriter printWriter = new PrintWriter(entry.getValue(),
                        CharsetTools.UTF_8.toString())) {

                    // Save the known used (sorted) at the top
                    for (String code : knownUsedCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER)
                            .collect(Collectors.toList())) {
                        printWriter.println(code + "=" + messages.get(code));
                    }
                    printWriter.println();

                    // Save the others (sorted) at the bottom
                    Set<String> unknownCodes = new HashSet<>();
                    unknownCodes.addAll(messages.keySet());
                    unknownCodes.removeAll(knownUsedCodes);
                    if (!unknownCodes.isEmpty()) {
                        printWriter.println("# Unknown");
                        printWriter.println();

                        for (String code : unknownCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER)
                                .collect(Collectors.toList())) {
                            printWriter.println(code + "=" + messages.get(code));
                        }
                        printWriter.println();
                    }
                } catch (Exception e) {
                    logger.error("Could not write the file", e);
                }
            }

            // Save the known
            FileTools.writeFile(Joiner.on('\n').join(
                    knownUsedCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList())),
                    tmpUsed);

            logger.info("Done saving locale files");
        }

    }) //
            .setDelayAfterLastTriggerMs(5000) //
            .setMaxDelayAfterFirstRequestMs(10000) //
            .setFirstPassThrough(true) //
            .start();

    smoothTrigger.request();
}