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:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java

/**
 * @param node/* w  w w.  java  2  s  . c  o m*/
 */
public static Stream<Property> streamProperties(Node node) {
    return StreamSupport.stream(propertiesIterable(node).spliterator(), false);
}

From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java

@Override
public CompletableFuture<Map<String, String>> getAnalyticsLibraries(final Optional<DataBucketBean> bucket,
        final Collection<AnalyticThreadJobBean> jobs) {
    if (_state_name == State.IN_TECHNOLOGY) {

        final String name_or_id = jobs.stream().findFirst().get().analytic_technology_name_or_id();

        final SingleQueryComponent<SharedLibraryBean> tech_query = CrudUtils.anyOf(SharedLibraryBean.class)
                .when(SharedLibraryBean::_id, name_or_id).when(SharedLibraryBean::path_name, name_or_id);

        final List<SingleQueryComponent<SharedLibraryBean>> other_libs = Stream
                .concat(Optional.ofNullable(jobs.stream().findFirst().get().module_name_or_id()).map(Stream::of)
                        .orElseGet(Stream::empty),
                        Optionals.ofNullable(jobs).stream()
                                .flatMap(job -> Optionals.ofNullable(job.library_names_or_ids()).stream()))
                .map(name -> {//from   www .j  av a2s  .  c om
                    return CrudUtils.anyOf(SharedLibraryBean.class).when(SharedLibraryBean::_id, name)
                            .when(SharedLibraryBean::path_name, name);
                }).collect(Collector.of(LinkedList::new, LinkedList::add, (left, right) -> {
                    left.addAll(right);
                    return left;
                }));

        @SuppressWarnings("unchecked")
        final MultiQueryComponent<SharedLibraryBean> spec = CrudUtils.<SharedLibraryBean>anyOf(tech_query,
                other_libs.toArray(new SingleQueryComponent[other_libs.size()]));

        // Get the names or ids, get the shared libraries, get the cached ids (must be present)

        return this._core_management_db.readOnlyVersion().getSharedLibraryStore()
                .getObjectsBySpec(spec, Arrays.asList(JsonUtils._ID, "path_name"), true).thenApply(cursor -> {
                    return StreamSupport.stream(cursor.spliterator(), false)
                            .collect(Collectors.<SharedLibraryBean, String, String>toMap(lib -> lib.path_name(),
                                    lib -> _globals.local_cached_jar_dir() + "/"
                                            + JarCacheUtils.buildCachedJarName(lib)));
                });
    } else {
        throw new RuntimeException(ErrorUtils.TECHNOLOGY_NOT_MODULE);
    }
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Utility function to handle fields
 * TODO (ALEPH-14): need to be able to specify different options for different fields via columnar settings
 * @param mutable_mapping//w w w  .  j ava 2 s.co  m
 * @param fielddata_info
 * @param mapper
 */
protected static void handleMappingFields(final ObjectNode mutable_mapping,
        final Optional<Tuple3<JsonNode, JsonNode, Boolean>> fielddata_info, final ObjectMapper mapper,
        final String index_type) {
    Optional.ofNullable(mutable_mapping.get("fields")).filter(j -> !j.isNull() && j.isObject()).ifPresent(j -> {
        StreamSupport.stream(Spliterators.spliteratorUnknownSize(j.fields(), Spliterator.ORDERED), false)
                .forEach(Lambdas.wrap_consumer_u(kv -> {
                    final ObjectNode mutable_o = (ObjectNode) kv.getValue();
                    setMapping(mutable_o, fielddata_info, mapper, index_type);
                }));
    });
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.services.TestElasticsearchIndexService.java

@Test
public void test_endToEnd_fixedFixed() throws IOException, InterruptedException, ExecutionException {
    final Calendar time_setter = GregorianCalendar.getInstance();
    time_setter.set(2015, 1, 1, 13, 0, 0);
    final String bucket_str = Resources.toString(
            Resources.getResource(
                    "com/ikanow/aleph2/search_service/elasticsearch/services/test_end_2_end_bucket2.json"),
            Charsets.UTF_8);//from  w  w  w . j a  va 2  s . c o m
    final DataBucketBean bucket = BeanTemplateUtils.build(bucket_str, DataBucketBean.class)
            .with("_id", "2b_test_end_2_end").with("full_name", "/test/end-end/fixed/fixed")
            .with("modified", time_setter.getTime()).done().get();

    final String template_name = ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.empty());

    // Check starting from clean

    {
        try {
            _crud_factory.getClient().admin().indices().prepareDeleteTemplate(template_name).execute()
                    .actionGet();
        } catch (Exception e) {
        } // (This is fine, just means it doesn't exist)      
        try {
            _crud_factory.getClient().admin().indices().prepareDelete(template_name + "*").execute()
                    .actionGet();
        } catch (Exception e) {
        } // (This is fine, just means it doesn't exist)      

        final GetIndexTemplatesRequest gt = new GetIndexTemplatesRequest().names(template_name);
        final GetIndexTemplatesResponse gtr = _crud_factory.getClient().admin().indices().getTemplates(gt)
                .actionGet();
        assertTrue("No templates to start with", gtr.getIndexTemplates().isEmpty());
    }

    final ICrudService<JsonNode> index_service_crud = _index_service.getDataService()
            .flatMap(s -> s.getWritableDataService(JsonNode.class, bucket, Optional.empty(), Optional.empty()))
            .flatMap(IDataWriteService::getCrudService).get();

    // Check template added:

    {
        final GetIndexTemplatesRequest gt2 = new GetIndexTemplatesRequest().names(template_name);
        final GetIndexTemplatesResponse gtr2 = _crud_factory.getClient().admin().indices().getTemplates(gt2)
                .actionGet();
        assertTrue(
                "Cache should contain the template: " + _index_service._bucket_template_cache.asMap().keySet(),
                _index_service._bucket_template_cache.asMap().containsKey(bucket._id() + ":true"));
        assertEquals(1, gtr2.getIndexTemplates().size());
    }

    // Get batch sub-service

    @SuppressWarnings("unchecked")
    final Optional<ICrudService.IBatchSubservice<JsonNode>> batch_service = index_service_crud
            .getUnderlyingPlatformDriver(ICrudService.IBatchSubservice.class, Optional.empty())
            .map(t -> (IBatchSubservice<JsonNode>) t);

    {
        assertTrue("Batch service must exist", batch_service.isPresent());
    }

    // Get information about the crud service

    final ElasticsearchContext es_context = (ElasticsearchContext) index_service_crud
            .getUnderlyingPlatformDriver(ElasticsearchContext.class, Optional.empty()).get();

    {
        assertTrue("Read write index", es_context instanceof ElasticsearchContext.ReadWriteContext);
        assertTrue("Temporal index", es_context
                .indexContext() instanceof ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext);
        assertTrue("Auto type", es_context
                .typeContext() instanceof ElasticsearchContext.TypeContext.ReadWriteTypeContext.FixedRwTypeContext);
    }

    // Write some docs out

    Arrays.asList(1, 2, 3, 4, 5).stream().map(i -> {
        time_setter.set(2015, i, 1, 13, 0, 0);
        return time_setter.getTime();
    }).map(d -> (ObjectNode) _mapper.createObjectNode().put("@timestamp", d.getTime())).forEach(o -> {
        ObjectNode o1 = o.deepCopy();
        o1.put("val1", 10);
        ObjectNode o2 = o.deepCopy();
        o2.put("val1", "test");
        batch_service.get().storeObject(o1, false);
        batch_service.get().storeObject(o2, false);
    });

    //(give it a chance to run)
    Thread.sleep(8000L);

    final GetMappingsResponse gmr = es_context.client().admin().indices()
            .prepareGetMappings(template_name + "*").execute().actionGet();

    // Should have 5 different indexes, each with 2 types + _default_

    assertEquals(1, gmr.getMappings().keys().size());
    final Set<String> expected_keys = Arrays.asList("test_fixed_fixed__1cb6bdcdf44f").stream()
            .collect(Collectors.toSet());
    final Set<String> expected_types = Arrays.asList("data_object").stream().collect(Collectors.toSet());

    // Check an alias gets created also
    List<String> aliases = getAliasedBuffers(bucket, Optional.empty());
    assertEquals(Arrays.asList(ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.empty())), aliases);
    // Check the top level alias is created
    final List<String> aliases_2 = this.getMainAliasedBuffers(bucket);
    assertEquals(Arrays.asList(ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.empty())), aliases_2);

    StreamSupport.stream(gmr.getMappings().spliterator(), false).forEach(x -> {
        assertTrue(
                "Is one of the expected keys: " + x.key + " vs  "
                        + expected_keys.stream().collect(Collectors.joining(":")),
                expected_keys.contains(x.key));
        // Size 1: data_object 
        assertEquals(1, x.value.size());
        //DEBUG
        //System.out.println(" ? " + x.key);
        StreamSupport.stream(x.value.spliterator(), false).forEach(Lambdas.wrap_consumer_u(y -> {
            //DEBUG
            //System.out.println("?? " + y.key + " --- " + y.value.sourceAsMap().toString());
            assertTrue("Is expected type: " + y.key, expected_types.contains(y.key));
        }));
    });

    //TEST DELETION:
    test_handleDeleteOrPurge(bucket, Optional.empty(), false);
}

From source file:com.hubrick.vertx.s3.client.S3Client.java

private void populateGetResponseHeaders(MultiMap headers, GetObjectResponseHeaders getResponseHeaders) {
    populateCommonResponseHeaders(headers, getResponseHeaders);
    populateServerSideEncryptionResponseHeaders(headers, getResponseHeaders);
    getResponseHeaders.setAmzExpiration(Optional.ofNullable(headers.get(Headers.X_AMZ_EXPIRATION))
            .filter(StringUtils::isNotBlank).orElse(null));
    getResponseHeaders//w ww .j av  a2s. com
            .setAmzReplicationStatus(Optional.ofNullable(headers.get(Headers.X_AMZ_REPLICATION_STATUS))
                    .filter(StringUtils::isNotBlank).map(ReplicationStatus::valueOf).orElse(null));
    getResponseHeaders.setAmzRestore(Optional.ofNullable(headers.get(Headers.X_AMZ_RESTORE))
            .filter(StringUtils::isNotBlank).orElse(null));
    getResponseHeaders.setAmzStorageClass(Optional.ofNullable(headers.get(Headers.X_AMZ_STORAGE_CLASS))
            .filter(StringUtils::isNotBlank).map(StorageClass::fromString).orElse(null));
    getResponseHeaders.setAmzTaggingCount(Optional.ofNullable(headers.get(Headers.X_AMZ_TAGGING_COUNT))
            .filter(StringUtils::isNotBlank).map(Integer::valueOf).orElse(null));
    getResponseHeaders.setAmzWebsiteRedirectLocation(
            Optional.ofNullable(headers.get(Headers.X_AMZ_WEBSITE_REDIRECT_LOCATION))
                    .filter(StringUtils::isNotBlank).orElse(null));

    final MultiMap amzMeta = MultiMap.caseInsensitiveMultiMap();
    StreamSupport.stream(headers.spliterator(), true)
            .filter(header -> header.getKey().toLowerCase().startsWith(Headers.X_AMZ_META_PREFIX))
            .forEach(header -> amzMeta.add(header.getKey().replaceFirst(Headers.X_AMZ_META_PREFIX, ""),
                    header.getValue()));
    getResponseHeaders.setAmzMeta(amzMeta);
}

From source file:com.hubrick.vertx.s3.client.S3Client.java

private void populateHeadResponseHeaders(MultiMap headers, HeadObjectResponseHeaders headResponseHeaders) {
    populateCommonResponseHeaders(headers, headResponseHeaders);
    populateServerSideEncryptionResponseHeaders(headers, headResponseHeaders);
    headResponseHeaders.setAmzExpiration(Optional.ofNullable(headers.get(Headers.X_AMZ_EXPIRATION))
            .filter(StringUtils::isNotBlank).orElse(null));
    headResponseHeaders.setAmzMissingMeta(Optional.ofNullable(headers.get(Headers.X_AMZ_MISSING_META))
            .filter(StringUtils::isNotBlank).orElse(null));
    headResponseHeaders/*ww  w  . ja va 2  s  . c o m*/
            .setAmzReplicationStatus(Optional.ofNullable(headers.get(Headers.X_AMZ_REPLICATION_STATUS))
                    .filter(StringUtils::isNotBlank).map(ReplicationStatus::valueOf).orElse(null));
    headResponseHeaders.setAmzRestore(Optional.ofNullable(headers.get(Headers.X_AMZ_RESTORE))
            .filter(StringUtils::isNotBlank).orElse(null));
    headResponseHeaders.setAmzStorageClass(Optional.ofNullable(headers.get(Headers.X_AMZ_STORAGE_CLASS))
            .filter(StringUtils::isNotBlank).map(StorageClass::fromString).orElse(null));

    final MultiMap amzMeta = MultiMap.caseInsensitiveMultiMap();
    StreamSupport.stream(headers.spliterator(), true)
            .filter(header -> header.getKey().toLowerCase().startsWith(Headers.X_AMZ_META_PREFIX))
            .forEach(header -> amzMeta.add(header.getKey().replaceFirst(Headers.X_AMZ_META_PREFIX, ""),
                    header.getValue()));
    headResponseHeaders.setAmzMeta(amzMeta);
}

From source file:org.dllearner.reasoning.SPARQLReasoner.java

private String datatypeSparqlFilter(Iterable<OWLDatatype> dts) {
    return Joiner.on(" || ").join(StreamSupport.stream(dts.spliterator(), false)
            .map(input -> "DATATYPE(?o) = <" + input.toStringID() + ">").collect(Collectors.toList()));
}

From source file:org.apache.wicket.MarkupContainer.java

/**
 * Returns a sequential {@code Stream} with the direct children of this markup container as its
 * source. This stream doesn't traverse the component tree.
 *
 * @return a sequential {@code Stream} over the direct children of this markup container
 * @since 8.0/*w  w  w .  j a  va2s .  co m*/
 */
public Stream<Component> stream() {
    return StreamSupport.stream(spliterator(), false);
}

From source file:org.apache.wicket.MarkupContainer.java

/**
 * Returns a sequential {@code Stream} with the all children of this markup container as its
 * source. This stream does traverse the component tree.
 * /*w  w  w .  ja v a 2 s.  c o  m*/
 * @return a sequential {@code Stream} over the all children of this markup container
 * @since 8.0
 */
@SuppressWarnings("unchecked")
public Stream<Component> streamChildren() {
    class ChildrenIterator<C> implements Iterator<C> {
        private Iterator<C> currentIterator;

        private Deque<Iterator<C>> iteratorStack = new ArrayDeque<>();

        private ChildrenIterator(Iterator<C> iterator) {
            currentIterator = iterator;
        }

        @Override
        public boolean hasNext() {
            if (!currentIterator.hasNext() && !iteratorStack.isEmpty()) {
                currentIterator = iteratorStack.pop();
            }
            return currentIterator.hasNext();
        }

        @Override
        public C next() {
            C child = currentIterator.next();
            if (child instanceof Iterable) {
                iteratorStack.push(currentIterator);
                currentIterator = ((Iterable<C>) child).iterator();
            }
            return child;
        }
    }
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(new ChildrenIterator<>(iterator()), 0),
            false);
}

From source file:org.kie.workbench.common.dmn.backend.DMNMarshallerTest.java

@Test
public void test_function_java_WB_model() throws IOException {
    final DMNMarshaller m = getDMNMarshaller();

    @SuppressWarnings("unchecked")
    final Graph<?, Node<?, ?>> g = m.unmarshall(null, this.getClass().getResourceAsStream("/DROOLS-2372.dmn"));

    final Stream<Node<?, ?>> stream = StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(g.nodes().iterator(), Spliterator.ORDERED), false);
    final Optional<Decision> wbDecision = stream.filter(n -> n.getContent() instanceof ViewImpl)
            .map(n -> (ViewImpl) n.getContent()).filter(n -> n.getDefinition() instanceof Decision)
            .map(n -> (Decision) n.getDefinition()).findFirst();

    wbDecision.ifPresent(d -> {/*from  w w w.j  ava 2  s  . c o m*/
        assertTrue(d.getExpression() instanceof FunctionDefinition);
        final FunctionDefinition wbFunction = (FunctionDefinition) d.getExpression();

        //This is what the WB expects
        assertEquals(FunctionDefinition.Kind.JAVA, wbFunction.getKind());
    });

    final DMNRuntime runtime = roundTripUnmarshalMarshalThenUnmarshalDMN(
            this.getClass().getResourceAsStream("/DROOLS-2372.dmn"));
    final DMNModel dmnModel = runtime.getModels().get(0);

    final BusinessKnowledgeModelNode bkmNode = dmnModel.getBusinessKnowledgeModels().iterator().next();
    final org.kie.dmn.model.api.FunctionDefinition dmnFunction = bkmNode.getBusinessKnowledModel()
            .getEncapsulatedLogic();
    assertEquals(FunctionKind.JAVA, dmnFunction.getKind());
}