Example usage for java.util Iterator forEachRemaining

List of usage examples for java.util Iterator forEachRemaining

Introduction

In this page you can find the example usage for java.util Iterator forEachRemaining.

Prototype

default void forEachRemaining(Consumer<? super E> action) 

Source Link

Document

Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Usage

From source file:net.csthings.cassinate.CassinateHelper.java

public void truncateAllTables(String keyspaceName) {
    Iterator<TableMetadata> tables = cluster.getMetadata().getKeyspace(keyspaceName).getTables().iterator();
    LOG.debug("Truncating tables in {}", keyspaceName);
    tables.forEachRemaining(
            t -> session.executeAsync(String.format("TRUNCATE TABLE %s.%s ;", keyspaceName, t.getName())));
}

From source file:net.csthings.cassinate.CassinateHelper.java

public void dropAllTables(String keyspaceName) {
    Iterator<TableMetadata> tables = cluster.getMetadata().getKeyspace(keyspaceName).getTables().iterator();
    LOG.debug("Truncating tables: {}", tables.toString());
    tables.forEachRemaining(
            t -> session.executeAsync(String.format("DROP TABLE %s.%s ;", keyspaceName, t.getName())));
}

From source file:info.archinnov.achilles.it.TestNativeQueries.java

@Test
public void should_iterate_regular_typed_query() throws Exception {
    //Given/*from w  w w.ja v a 2s.  co  m*/
    final Map<String, Object> values = new HashMap<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    values.put("id", id);
    values.put("date1", "'2015-10-01 00:00:00+0000'");
    values.put("date2", "'2015-10-02 00:00:00+0000'");
    values.put("date3", "'2015-10-03 00:00:00+0000'");
    values.put("date4", "'2015-10-04 00:00:00+0000'");
    values.put("date5", "'2015-10-05 00:00:00+0000'");
    values.put("date6", "'2015-10-06 00:00:00+0000'");
    values.put("date7", "'2015-10-07 00:00:00+0000'");
    values.put("date8", "'2015-10-08 00:00:00+0000'");
    values.put("date9", "'2015-10-09 00:00:00+0000'");
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_many_rows.cql", values);

    final SimpleStatement statement = new SimpleStatement("SELECT * FROM simple WHERE id = :id LIMIT 100");

    //When
    final Iterator<TypedMap> iter = manager.query().nativeQuery(statement, id).iterator();

    //Then
    final AtomicBoolean foundEntity = new AtomicBoolean(false);
    iter.forEachRemaining(instance -> {
        foundEntity.getAndSet(true);
        assertThat(instance).isNotNull();
        assertThat(instance.<String>getTyped("value")).contains("id - date");
    });
    assertThat(foundEntity.get()).isTrue();
}

From source file:net.anthavio.vinbudin.vui.ChatUI.java

private void refreshMessageBoard() {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy 'at' HH:mm z");
    Iterator<ChatMessage> messages = service.messagesIterator();
    StringBuilder sb = new StringBuilder();
    messages.forEachRemaining(message -> {
        sb.append(sdf.format(message.getDate())).append(", ").append(message.getAuthor().getName()).append(" [")
                .append(message.getAuthor().getFrom().name()).append("]: ").append(message.getText())
                .append("\n");
    });/*from www . j a va 2 s .c  om*/
    labelBoard.setValue(sb.toString());
}

From source file:info.archinnov.achilles.it.TestTypedQueries.java

@Test
public void should_iterate_regular_typed_query() throws Exception {
    //Given/*from w ww  .ja  v  a  2  s . c o m*/
    final Map<String, Object> values = new HashMap<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    values.put("id", id);
    values.put("date1", "'2015-10-01 00:00:00+0000'");
    values.put("date2", "'2015-10-02 00:00:00+0000'");
    values.put("date3", "'2015-10-03 00:00:00+0000'");
    values.put("date4", "'2015-10-04 00:00:00+0000'");
    values.put("date5", "'2015-10-05 00:00:00+0000'");
    values.put("date6", "'2015-10-06 00:00:00+0000'");
    values.put("date7", "'2015-10-07 00:00:00+0000'");
    values.put("date8", "'2015-10-08 00:00:00+0000'");
    values.put("date9", "'2015-10-09 00:00:00+0000'");
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_many_rows.cql", values);

    final SimpleStatement statement = new SimpleStatement("SELECT * FROM simple WHERE id = :id LIMIT 100");

    //When
    final Iterator<SimpleEntity> iter = manager.query().typedQueryForSelect(statement, id).iterator();

    //Then
    final AtomicBoolean foundEntity = new AtomicBoolean(false);
    iter.forEachRemaining(instance -> {
        foundEntity.getAndSet(true);
        assertThat(instance).isNotNull();
        assertThat(instance.getValue()).contains("id - date");
    });

    assertThat(foundEntity.get()).isTrue();
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Tidy up duplicates created because of the lack of consistency in deduplication (+lack of upsert!)
 * @param tx//ww w.  ja v  a  2 s. c  o  m
 * @param grouped_vertices
 * @param mutable_stats_per_batch
 */
public static void mergeDuplicates(final TitanTransaction tx, final String bucket_path,
        final Map<JsonNode, List<Vertex>> grouped_vertices, final MutableStatsBean mutable_stats_per_batch) {
    grouped_vertices.entrySet().stream().filter(kv -> !kv.getValue().isEmpty()).forEach(kv -> {

        final Stream<Vertex> vertices = kv.getValue().stream().sorted((a, b) -> postProcSortingMethod(a, b));
        final Iterator<Vertex> it = vertices.iterator();
        if (it.hasNext()) {
            final long matches_found = kv.getValue().size() - 1;
            mutable_stats_per_batch.vertex_matches_found += matches_found; //(#vertices)
            if (matches_found > 0) {
                mutable_stats_per_batch.vertices_updated++;//(#keys)
            }

            final Vertex merge_into = it.next();
            if (it.hasNext()) {
                mutable_stats_per_batch.vertices_updated++;
            }
            it.forEachRemaining(v -> {
                // special case: add all buckets, update times etc
                Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false).map(vp -> vp.value())
                        .forEach(val -> merge_into.property(Cardinality.set, GraphAnnotationBean.a2_p, val));
                merge_into.property(GraphAnnotationBean.a2_tm, new Date().getTime());

                // copy vertex properties into the "merge_into" vertex
                Optionals.streamOf(v.properties(), false).filter(vp -> !_RESERVED_PROPERTIES.contains(vp.key())) // (ie don't overwrite system properties)
                        .forEach(vp -> merge_into.property(vp.key(), vp.value()));

                // OK edges are the difficult bit
                mergeEdges(bucket_path, Direction.IN, false, merge_into, v, mutable_stats_per_batch);
                mergeEdges(bucket_path, Direction.OUT, false, merge_into, v, mutable_stats_per_batch);

                // (finally remove this vertex)
                // (previously - commened out code, we just removed the bucket, but since we're trying to remove singletons, we'll always delete)
                //Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false).filter(vp -> bucket_path.equals(vp.value())).forEach(vp -> vp.remove());
                //if (!v.properties(GraphAnnotationBean.a2_p).hasNext()) v.remove();
                v.remove();
            });
        }

    });
}

From source file:org.apache.bookkeeper.common.util.TestBackoff.java

@Test
public void testDecorrelatedJittered() throws Exception {
    long startMs = ThreadLocalRandom.current().nextLong(1L, 1000L);
    long maxMs = ThreadLocalRandom.current().nextLong(startMs, startMs * 2);
    Stream<Long> backoffs = Backoff.decorrelatedJittered(startMs, maxMs).limit(10);
    Iterator<Long> backoffIter = backoffs.iterator();
    assertTrue(backoffIter.hasNext());/*from  w w  w. jav a 2s  . c o  m*/
    assertEquals(startMs, backoffIter.next().longValue());
    AtomicLong prevMs = new AtomicLong(startMs);
    backoffIter.forEachRemaining(backoffMs -> {
        assertTrue(backoffMs >= startMs);
        assertTrue(backoffMs <= prevMs.get() * 3);
        assertTrue(backoffMs <= maxMs);
        prevMs.set(backoffMs);
    });
}

From source file:org.apache.bookkeeper.common.util.TestBackoff.java

@Test
public void testDecorrelatedJitteredPolicy() throws Exception {
    long startMs = ThreadLocalRandom.current().nextLong(1L, 1000L);
    long maxMs = ThreadLocalRandom.current().nextLong(startMs, startMs * 2);
    Stream<Long> backoffs = Backoff.Jitter.of(DECORRELATED, startMs, maxMs, 10).toBackoffs();
    Iterator<Long> backoffIter = backoffs.iterator();
    assertTrue(backoffIter.hasNext());/* w  w  w.  j  a v  a2 s  .  c  o m*/
    assertEquals(startMs, backoffIter.next().longValue());
    AtomicLong prevMs = new AtomicLong(startMs);
    backoffIter.forEachRemaining(backoffMs -> {
        assertTrue(backoffMs >= startMs);
        assertTrue(backoffMs <= prevMs.get() * 3);
        assertTrue(backoffMs <= maxMs);
        prevMs.set(backoffMs);
    });
}

From source file:org.apache.jena.sparql.function.library.strjoin.java

@Override
public final NodeValue exec(List<NodeValue> args) {
    if (args == null)
        // The contract on the function interface is that this should not happen.
        throw new ARQInternalErrorException(Lib.className(this) + ": Null args list");

    Iterator<NodeValue> iter = args.iterator();
    String sep = iter.next().asString();

    List<String> x = new ArrayList<>();
    iter.forEachRemaining(arg -> x.add(arg.asString()));

    return NodeValue.makeString(String.join(sep, x));
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorOverGraphTest.java

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAllowTraversalToIterateInDifferentThreadThanOriginallyEvaluatedWithAutoCommit()
        throws Exception {
    // this test sort of simulates Gremlin Server interaction where a Traversal is eval'd in one Thread, but
    // then iterated in another.  note that Gremlin Server configures the script engine to auto-commit
    // after evaluation.  this basically tests the state of the Gremlin Server GremlinExecutor when
    // being used in sessionless mode
    final ExecutorService evalExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterSuccess(b -> {
        final GraphTraversalSource g = (GraphTraversalSource) b.get("g");
        if (g.getGraph().features().graph().supportsTransactions())
            g.tx().commit();//  w w  w  .  ja v  a  2  s.  c om
    }).executorService(evalExecutor).create();

    final Map<String, Object> bindings = new HashMap<>();
    bindings.put("g", g);

    final AtomicInteger vertexCount = new AtomicInteger(0);

    final ExecutorService iterationExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    gremlinExecutor.eval("g.V().out()", bindings).thenAcceptAsync(o -> {
        final Iterator itty = (Iterator) o;
        itty.forEachRemaining(v -> vertexCount.incrementAndGet());
    }, iterationExecutor).join();

    assertEquals(6, vertexCount.get());

    gremlinExecutor.close();
    evalExecutor.shutdown();
    evalExecutor.awaitTermination(30000, TimeUnit.MILLISECONDS);
    iterationExecutor.shutdown();
    iterationExecutor.awaitTermination(30000, TimeUnit.MILLISECONDS);
}