Example usage for java.util Collection stream

List of usage examples for java.util Collection stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:eu.cloudwave.wp5.feedbackhandler.aggregations.strategies.RequestAggregationStrategyImpl.java

/**
 * {@inheritDoc}//from   w  w w  .j  a  v  a2  s  .c o  m
 */
@Override
public RequestAggregationValues aggregate(RequestCollector requests) {
    double expectedCount = getExpectedNumberOfMeasurementValueGroups();

    /*
     * Group by aggregation interval and create summary statistics with min, avg, max and count
     */
    Collection<Long> groupedByAggregationInterval = requests.getReqTimestamps().stream()
            .collect(Collectors.groupingBy(
                    timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
                    Collectors.counting()))
            .values();
    int calculatedCount = groupedByAggregationInterval.size();

    try {
        if (calculatedCount != 0) {
            // use integer summaryStatistics to get min, avg, max
            IntSummaryStatistics stats = groupedByAggregationInterval.stream().mapToInt(p -> toInt(p))
                    .summaryStatistics();

            // no time range selected, just return int summary
            if (expectedCount == 0) {
                return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(),
                        stats.getSum(), stats.getCount());
            } else {
                // if calculated count != expected count --> adjust minimum, average and count value
                if (Double.compare(calculatedCount, expectedCount) != 0) {
                    double newAverage = (double) (stats.getSum() / expectedCount);
                    return new RequestAggregationValuesImpl(0, stats.getMax(), newAverage, stats.getSum(),
                            (int) expectedCount);
                } else {
                    return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(),
                            stats.getSum(), (int) expectedCount);
                }
            }
        } else {
            return new RequestAggregationValuesImpl(0, 0, 0, 0, 0);
        }
    } catch (ArithmeticException e) {
        System.out.println(e.getMessage());
        return new RequestAggregationValuesImpl(0, 0, 0, 0, 0);
    }
}

From source file:com.haulmont.restapi.service.EntitiesControllerManager.java

/**
 * Finds entity with given metaClass and converts it to JSON.
 *//*from  ww w .j  a v  a2s  . c  o m*/
@Nullable
protected CreatedEntityInfo getMainEntityInfo(Collection<Entity> importedEntities, MetaClass metaClass,
        String version) {
    Entity mainEntity = null;
    if (importedEntities.size() > 1) {
        Optional<Entity> first = importedEntities.stream().filter(e -> e.getMetaClass().equals(metaClass))
                .findFirst();
        if (first.isPresent())
            mainEntity = first.get();
    } else {
        mainEntity = importedEntities.iterator().next();
    }

    if (mainEntity != null) {
        String json = entitySerializationAPI.toJson(mainEntity);
        json = restControllerUtils.transformJsonIfRequired(metaClass.getName(), version,
                JsonTransformationDirection.TO_VERSION, json);
        return new CreatedEntityInfo(mainEntity.getId(), json);
    }
    return null;
}

From source file:com.vmware.photon.controller.deployer.dcp.task.CreateIsoTaskService.java

private void getContainerEntities(final State currentState, Collection<String> containerLinks) {

    OperationJoin.create(containerLinks.stream().map(containerLink -> Operation.createGet(this, containerLink)))
            .setCompletion((ops, exs) -> {
                if (null != exs && !exs.isEmpty()) {
                    failTask(exs);//  w  ww  .  ja v a 2  s.c om
                    return;
                }

                try {
                    Set<ContainerService.State> containerStates = ops.values().stream()
                            .map(getOperation -> getOperation.getBody(ContainerService.State.class))
                            .collect(Collectors.toSet());
                    applyConfiguration(currentState, containerStates);
                } catch (Throwable t) {
                    failTask(t);
                }
            }).sendWith(this);
}

From source file:net.dv8tion.jda.entities.impl.TextChannelImpl.java

@Override
public void deleteMessages(Collection<Message> messages) {
    deleteMessagesByIds(messages.stream().map(msg -> msg.getId()).collect(Collectors.toList()));
}

From source file:cc.arduino.contributions.packages.ContributionsIndexer.java

public Set<ContributedTool> getInstalledTools() {
    Set<ContributedTool> tools = new HashSet<>();
    if (index == null) {
        return tools;
    }//from www. j  av  a  2 s  . c o m
    for (ContributedPackage pack : index.getPackages()) {
        Collection<ContributedPlatform> platforms = pack.getPlatforms().stream() //
                .filter(p -> p.isInstalled()) //
                .collect(Collectors.toList());
        Map<String, List<ContributedPlatform>> platformsByName = platforms.stream()
                .collect(Collectors.groupingBy(ContributedPlatform::getName));

        platformsByName.forEach((platformName, platformsWithName) -> {
            if (platformsWithName.size() > 1) {
                platformsWithName = platformsWithName.stream() //
                        .filter(p -> !p.isBuiltIn()) //
                        .collect(Collectors.toList());
            }
            for (ContributedPlatform p : platformsWithName) {
                tools.addAll(p.getResolvedTools());
            }
        });
    }
    return tools;
}

From source file:ddf.ldap.ldaplogin.SslLdapLoginModule.java

private void installLdapConnectionPool(String connectionPoolId) {
    BundleContext bundleContext = getContext();
    if (bundleContext != null) {
        try {/* w w w .j a  va2s .  c  om*/
            Collection<ServiceReference<GenericObjectPool>> serviceReferences = bundleContext
                    .getServiceReferences(GenericObjectPool.class, String.format("(id=%s)", connectionPoolId));
            ServiceReference<GenericObjectPool> serviceReference = serviceReferences.stream().findFirst()
                    .orElseThrow(() -> new IllegalStateException(
                            "No LDAPConnectionPool service found with id:" + connectionPoolId));
            ldapConnectionPool = bundleContext.getService(serviceReference);
        } catch (InvalidSyntaxException | IllegalStateException e) {
            LOGGER.error("Unable to get LDAP Connection pool. LDAP log in will not be possible.", e);
        }
    }
}

From source file:com.vsct.dt.hesperides.resources.HesperidesApplicationResource.java

@Path("/{application_name}/platforms/{platform_name}/global_properties_usage")
@GET/* ww w.  j  av a 2  s.co  m*/
@Timed
@ApiOperation("Retrieve global properties usage in application")
public Response getGlobalPropertiesUsage(@Auth final User user,
        @PathParam("application_name") final String applicationName,
        @PathParam("platform_name") final String platformName) {

    Collection<PlatformData> l = this.applications
            .getApplicationsFromSelector(data -> data.getApplicationName().equals(applicationName)
                    && data.getPlatformName().equals(platformName));

    PlatformData p = l.stream().findFirst().get();

    Map<String, Set<HashMap>> usage = new HashMap<>();

    applications.getProperties(new PlatformKey(applicationName, platformName), "#").getKeyValueProperties()
            .stream().forEach(globalProp -> {

                Set<HashMap> buffer = new HashSet<HashMap>();

                p.getModules().stream().forEach(elem -> {

                    PlatformKey currentPlatformKey = new PlatformKey(applicationName, platformName);

                    Optional<HesperidesPropertiesModel> oModel;
                    HesperidesPropertiesModel model;

                    if (!elem.isWorkingCopy()) {
                        oModel = modules.getModel(new ModuleKey(elem.getName(), Release.of(elem.getVersion())));
                    } else {
                        oModel = modules
                                .getModel(new ModuleKey(elem.getName(), WorkingCopy.of(elem.getVersion())));
                    }

                    if (oModel.isPresent()) {

                        model = oModel.get();
                        if (model.getKeyValueProperties().stream()
                                .anyMatch(prop -> prop.getName().equals(globalProp.getName()))) {

                            buffer.add(new HashMap() {
                                {
                                    put("path", elem.getPropertiesPath());
                                    put("inModel", true);
                                }
                            });
                        }
                    } else {

                        model = null;
                    }

                    applications.getProperties(currentPlatformKey, elem.getPropertiesPath())
                            .getKeyValueProperties().stream().forEach(prop -> {

                                if (prop.getName().equals(globalProp.getName())
                                        || prop.getValue().contains("{{" + globalProp.getName() + "}}")) {

                                    if (model == null) {

                                        buffer.add(new HashMap() {
                                            {
                                                put("path", elem.getPropertiesPath());
                                                put("inModel", false);
                                            }
                                        });
                                    } else {

                                        Boolean inModel = model.getKeyValueProperties().stream()
                                                .anyMatch(mod -> prop.getName().equals(mod.getName()));

                                        buffer.add(new HashMap() {
                                            {
                                                put("path", elem.getPropertiesPath());
                                                put("inModel", inModel);
                                            }
                                        });
                                    }
                                }
                            });
                });
                //            usage.put(globalProp.getName(), buffer.stream().distinct().collect(Collectors.toList()));
                usage.put(globalProp.getName(), buffer);
            });

    return Response.ok(usage).build();
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

CompletableFuture<Void> closeServerResources(Collection<CloseableServerResource> resources) {
    if (resources.isEmpty()) {
        return CompletableFuture.completedFuture(null);
    }/*from w w w.  j a va2s.  co  m*/
    CompletableFuture<Void> future = new CompletableFuture<>();

    List<String> cursorIds = resources.stream().filter(r -> r instanceof CursorImpl)
            .map(CloseableServerResource::getId).collect(Collectors.toList());
    List<String> statementIds = resources.stream().filter(r -> r instanceof PreparedStatementImpl)
            .map(CloseableServerResource::getId).collect(Collectors.toList());
    // now set their status to closed
    resources.forEach(CloseableServerResource::setClosed);

    // remove them from the open resource list
    // TODO: wait for success?
    cursorIds.forEach(_openServerResources::remove);
    statementIds.forEach(_openServerResources::remove);

    send(new ReleaseMessage(cursorIds, statementIds), new ConfirmationResponseHandler(future,
            MessageType.ReleaseCompleteMessage, "waiting for a cursor/statement release confirmation"));
    return future;
}

From source file:com.vigglet.util.ModelUtilBase.java

public Collection<T> findByCompany(int company, int pageSize, int page, String searchText, int limit) {
    int skip = (pageSize * (page - 1));

    if (page > 0 || (searchText != null && !searchText.isEmpty()
            && searchText.length() >= getMinLenghtOfSearchText())) {
        Collection<T> result = getOrderdList(company);
        if (searchText != null && !searchText.isEmpty() && searchText.length() >= getMinLenghtOfSearchText()) {
            String[] searchTextSplit = searchText.split(" ");
            if (searchTextSplit.length > 1 || !StringUtils.isNumeric(searchText)) {
                result = result.stream().filter((T t) -> t.matchesSearchableFields(searchTextSplit))
                        .collect(Collectors.toList());
            }/*from   www.j  a va2  s.c o m*/
        }

        int i = 0;
        if (page > 0) {
            Collection<T> result2 = new ArrayList<>(pageSize);
            for (T t : result) {
                if (++i < skip) {
                    continue;
                }

                if (i == (skip + pageSize)) {
                    break;
                }

                if (i >= skip && i <= (skip + pageSize)) {
                    result2.add(t);
                }
            }
            return result2;
        }

        return result;
    }

    if (limit > 0) {
        return getLimitedList(company, limit);
    }

    return findByCompany(company);
}

From source file:org.ligoj.app.plugin.security.fortify.FortifyPluginResource.java

/**
 * Call a Fortify REST service to fetch items by their name.<br>
 * NOTE : process manager will be shut down.
 *
 * @param node/*  www. j a  v a 2 s. c  om*/
 *            node to query.
 * @param url
 *            query URL.
 * @param criteria
 *            Optional name to match.
 * @return Projects matching to the given criteria.
 */
private Collection<FortifyProject> findAll(final String node, final String url, final String criteria)
        throws IOException {
    // Check the user can log-in to Fortify
    final Collection<Map<String, Object>> data = getFortifyResource(this.pvResource.getNodeParameters(node),
            url);
    final Format format = new NormalizeFormat();
    final String formatCriteria = format.format(StringUtils.trimToEmpty(criteria));

    // Filter by criteria on the project name
    final Map<Integer, FortifyProject> result = new TreeMap<>();
    data.stream().filter(item -> (format.format(item.get("name"))).contains(formatCriteria)).forEach(item -> {
        final FortifyProject entry = toProject(item);
        result.put(entry.getId(), entry);
    });
    return result.values();
}