Example usage for java.util.stream StreamSupport stream

List of usage examples for java.util.stream StreamSupport stream

Introduction

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

Prototype

public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) 

Source Link

Document

Creates a new sequential or parallel Stream from a Spliterator .

Usage

From source file:fi.hsl.parkandride.dev.DevController.java

@RequestMapping(method = PUT, value = DEV_PREDICTION_HISTORY)
@TransactionalRead // each call to predictionService.updatePredictionsHistoryForFacility creates a separate write transaction to avoid too long transactions
public ResponseEntity<Void> generatePredictionHistory(@NotNull @PathVariable(FACILITY_ID) Long facilityId) {
    facilityRepository.getFacility(facilityId); // ensure facility exists
    final UtilizationSearch utilizationSearch = new UtilizationSearch();
    utilizationSearch.start = DateTime.now().minusWeeks(5);
    utilizationSearch.end = DateTime.now();
    utilizationSearch.facilityIds = Collections.singleton(facilityId);
    final List<Utilization> utilizations = Lists
            .newArrayList(utilizationRepository.findUtilizations(utilizationSearch));
    DateTime lastTimestamp = utilizations.stream().map(u -> u.timestamp).max(DateTime::compareTo)
            .orElse(utilizationSearch.end);
    StreamSupport
            .stream(spliteratorUnknownSize(new DateTimeIterator(utilizationSearch.start.plusWeeks(4),
                    lastTimestamp.minus(PredictionRepository.PREDICTION_RESOLUTION), // avoid collision with scheduled predictions
                    PredictionRepository.PREDICTION_RESOLUTION), Spliterator.ORDERED), false)
            .map(endTime -> utilizations.stream().filter(utilization -> utilization.timestamp.isBefore(endTime))
                    .collect(toList()))/*w ww .  ja va2  s  .com*/
            .forEach(utilizationList -> predictionService.updatePredictionsHistoryForFacility(utilizationList));
    return new ResponseEntity<>(CREATED);
}

From source file:com._4dconcept.springframework.data.marklogic.core.query.QueryBuilder.java

@Nullable
private Criteria buildCriteria(MarklogicPersistentProperty property, Object value) {
    Optional<? extends TypeInformation<?>> typeInformation = StreamSupport
            .stream(property.getPersistentEntityTypes().spliterator(), false).findFirst();
    if (typeInformation.isPresent()) {
        MarklogicPersistentEntity<?> nestedEntity = mappingContext.getPersistentEntity(typeInformation.get());
        return nestedEntity != null ? buildCriteria(value, nestedEntity) : null;
    } else {//w ww .  j a  va 2  s . c  o m
        Criteria criteria = new Criteria();

        if (value instanceof Collection) {
            criteria.setOperator(Criteria.Operator.or);
            Collection<?> collection = (Collection<?>) value;
            criteria.setCriteriaObject(
                    collection.stream().map(o -> buildCriteria(property, o)).collect(Collectors.toList()));
        } else {
            criteria.setQname(property.getQName());
            criteria.setCriteriaObject(value);
        }

        return criteria;
    }
}

From source file:org.openmhealth.shim.withings.mapper.WithingsBodyMeasureDataPointMapper.java

/**
 * @param measuresNode the list of measures in a measure group node
 * @param bodyMeasureType the measure type of interest
 * @return the value of the specified measure type, if present
 *///  w w w  . j av a2 s.  co m
protected Optional<BigDecimal> getValueForMeasureType(JsonNode measuresNode,
        WithingsBodyMeasureType bodyMeasureType) {

    List<BigDecimal> values = StreamSupport.stream(measuresNode.spliterator(), false)
            .filter((measureNode) -> asRequiredLong(measureNode, "type") == bodyMeasureType.getMagicNumber())
            .map(this::getValue).collect(Collectors.toList());

    if (values.isEmpty()) {
        return Optional.empty();
    }

    if (values.size() > 1) {
        throw new JsonNodeMappingException(
                format("The following Withings measures node contains multiple measures of type %s.\n%s.",
                        bodyMeasureType, measuresNode));
    }

    return Optional.of(values.get(0));
}

From source file:edu.umd.umiacs.clip.tools.io.AllFiles.java

private static Stream<CSVRecord> overridenRecords(CSVFormat format, Path path) throws IOException {
    return StreamSupport.stream(format.parse(
            new BufferedReader(new InputStreamReader(new BufferedInputStream(newInputStream(path), BUFFER_SIZE),
                    UTF_8.newDecoder().onMalformedInput(IGNORE))))
            .spliterator(), false);//from   ww  w .j a v  a2s. c o  m
}

From source file:io.mandrel.document.impl.ElasticsearchDocumentStore.java

@Override
public Collection<Document> byPages(int pageSize, int pageNumber) {
    return StreamSupport
            .stream(client.prepareSearch(index).setSize(pageSize).setFrom(pageNumber * pageSize)
                    .setQuery(QueryBuilders.matchAllQuery()).get().getHits().spliterator(), true)
            .map(mapper).collect(Collectors.toList());
}

From source file:com.jaredjstewart.SampleSecurityManager.java

private Map<String, Role> readRoles(final JsonNode jsonNode) {
    if (jsonNode.get("roles") == null) {
        return Collections.EMPTY_MAP;
    }// ww w.j  ava2s.co m
    Map<String, Role> roleMap = new HashMap<>();
    for (JsonNode rolesNode : jsonNode.get("roles")) {
        Role role = new Role();
        role.name = rolesNode.get("name").asText();
        String regionNames = null;
        String keys = null;

        JsonNode regionsNode = rolesNode.get("regions");
        if (regionsNode != null) {
            if (regionsNode.isArray()) {
                regionNames = StreamSupport.stream(regionsNode.spliterator(), false).map(JsonNode::asText)
                        .collect(Collectors.joining(","));
            } else {
                regionNames = regionsNode.asText();
            }
        }

        for (JsonNode operationsAllowedNode : rolesNode.get("operationsAllowed")) {
            String[] parts = operationsAllowedNode.asText().split(":");
            String resourcePart = (parts.length > 0) ? parts[0] : null;
            String operationPart = (parts.length > 1) ? parts[1] : null;

            if (parts.length > 2) {
                regionNames = parts[2];
            }
            if (parts.length > 3) {
                keys = parts[3];
            }

            String regionPart = (regionNames != null) ? regionNames : "*";
            String keyPart = (keys != null) ? keys : "*";

            role.permissions.add(new ResourcePermission(resourcePart, operationPart, regionPart, keyPart));
        }

        roleMap.put(role.name, role);

        if (rolesNode.has("serverGroup")) {
            role.serverGroup = rolesNode.get("serverGroup").asText();
        }
    }

    return roleMap;
}

From source file:org.jsonschema2pojo.rules.AdditionalPropertiesRule.java

private JMethod addInnerBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) {
    Optional<JDefinedClass> builderClass = StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(jclass.classes(), Spliterator.ORDERED), false)
            .filter(definedClass -> definedClass.name().equals(getBuilderClassName(jclass))).findFirst();

    JMethod builder = builderClass.get().method(JMod.PUBLIC, builderClass.get(), "withAdditionalProperty");

    JVar nameParam = builder.param(String.class, "name");
    JVar valueParam = builder.param(propertyType, "value");

    JBlock body = builder.body();/*from   www .  ja  v a  2s. c  o  m*/
    JInvocation mapInvocation = body.invoke(JExpr.ref(JExpr.cast(jclass, JExpr._this().ref("instance")), field),
            "put");
    mapInvocation.arg(nameParam);
    mapInvocation.arg(valueParam);
    body._return(JExpr._this());

    return builder;
}

From source file:com._4dconcept.springframework.data.marklogic.repository.support.SimpleMarklogicRepository.java

@Override
@Transactional//from   w ww. ja  va 2  s. co  m
public <S extends T> List<S> saveAll(Iterable<S> entities) {
    Assert.notNull(entities, "entities must not be null");
    return StreamSupport.stream(entities.spliterator(), false).map(this::save).collect(Collectors.toList());
}

From source file:com.ikanow.aleph2.management_db.controllers.actors.BucketDeletionActor.java

/** Removes all "user" state related to the bucket being deleted/purged
 * @param bucket/*from w w w .  j  a  v a  2  s  .  c o m*/
 * @param core_management_db_service
 */
public static void deleteAllStateObjectsForBucket(final DataBucketBean bucket,
        final IManagementDbService core_management_db_service, boolean delete_bucket) {
    final ICrudService<AssetStateDirectoryBean> states = core_management_db_service
            .getStateDirectory(Optional.of(bucket), Optional.empty());

    states.getObjectsBySpec(CrudUtils.allOf(AssetStateDirectoryBean.class)).thenAccept(cursor -> {
        StreamSupport.stream(cursor.spliterator(), true).forEach(bean -> {

            Optional.ofNullable(Patterns.match(bean.state_type()).<ICrudService<JsonNode>>andReturn()
                    .when(t -> AssetStateDirectoryBean.StateDirectoryType.analytic_thread == t,
                            __ -> core_management_db_service.getBucketAnalyticThreadState(JsonNode.class,
                                    bucket, Optional.of(bean.collection_name())))
                    .when(t -> AssetStateDirectoryBean.StateDirectoryType.harvest == t,
                            __ -> core_management_db_service.getBucketHarvestState(JsonNode.class, bucket,
                                    Optional.of(bean.collection_name())))
                    .when(t -> AssetStateDirectoryBean.StateDirectoryType.enrichment == t,
                            __ -> core_management_db_service.getBucketEnrichmentState(JsonNode.class, bucket,
                                    Optional.of(bean.collection_name())))
                    .otherwise(__ -> null)).ifPresent(to_delete -> to_delete.deleteDatastore());
        });
    });

}

From source file:com.thinkbiganalytics.metadata.modeshape.user.JcrUserGroup.java

private <C, J> Iterable<C> iterateReferances(String nodeType, Class<C> modelClass, Class<J> jcrClass) {
    return () -> {
        @SuppressWarnings("unchecked")
        Iterable<Property> propItr = () -> {
            try {
                return (Iterator<Property>) this.node.getWeakReferences();
            } catch (Exception e) {
                throw new MetadataRepositoryException(
                        "Failed to retrieve the users in the group node: " + this.node, e);
            }/*  ww  w  .j  av a2s.  c  o m*/
        };

        return StreamSupport.stream(propItr.spliterator(), false).map(p -> JcrPropertyUtil.getParent(p))
                .filter(n -> JcrUtil.isNodeType(n, nodeType)).map(n -> {
                    try {
                        @SuppressWarnings("unchecked")
                        C entity = (C) ConstructorUtils.invokeConstructor(jcrClass, n);
                        return entity;
                    } catch (Exception e) {
                        throw new MetadataRepositoryException("Failed to retrieve create entity: " + jcrClass,
                                e);
                    }
                }).iterator();
    };
}