Example usage for java.util.concurrent CompletableFuture join

List of usage examples for java.util.concurrent CompletableFuture join

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture join.

Prototype

@SuppressWarnings("unchecked")
public T join() 

Source Link

Document

Returns the result value when complete, or throws an (unchecked) exception if completed exceptionally.

Usage

From source file:org.mortbay.jetty.load.generator.starter.AbstractLoadGeneratorStarter.java

public void run() throws Exception {

    Resource resourceProfile = getResource();

    LoadGenerator.Builder loadGeneratorBuilder = new LoadGenerator.Builder() //
            .host(starterArgs.getHost()) //
            .port(starterArgs.getPort()) //
            .iterationsPerThread(starterArgs.getRunIteration()) //
            .usersPerThread(starterArgs.getUsers()) //
            .resourceRate(starterArgs.getTransactionRate()) //
            .httpClientTransportBuilder(httpClientTransportBuilder()) //
            .sslContextFactory(sslContextFactory()) //
            .resource(resourceProfile) //
            .warmupIterationsPerThread(starterArgs.getWarmupNumber()) //
            .scheme(starterArgs.getScheme()); //

    if (starterArgs.getMaxRequestsQueued() > 0) {
        loadGeneratorBuilder.maxRequestsQueued(starterArgs.getMaxRequestsQueued());
    }//from   w  ww  .  j  ava  2 s. com

    if (getExecutorService() != null) {
        loadGeneratorBuilder.executor(getExecutorService());
    }

    boolean runFor = false;

    if (starterArgs.getRunningTime() > 0) {
        loadGeneratorBuilder.runFor(starterArgs.getRunningTime(), starterArgs.getRunningTimeUnit());
    }

    for (Resource.Listener listener : getResourceListeners()) {
        loadGeneratorBuilder.resourceListener(listener);
    }

    for (Request.Listener listener : getListeners()) {
        loadGeneratorBuilder.requestListener(listener);
    }

    for (LoadGenerator.Listener listener : getLoadGeneratorListeners()) {
        loadGeneratorBuilder.listener(listener);
    }

    LoadGenerator loadGenerator = loadGeneratorBuilder.build();
    logger.info("loadgenerator.config: {}", loadGenerator.getConfig().toString());
    CompletableFuture<Void> cf = loadGenerator.begin();
    cf.join();
    logger.info("load test done");
}

From source file:com.devicehive.handler.command.CommandSubscribeIntegrationTest.java

@Test
@Ignore//ww  w. ja  v  a2  s .  c  o  m
public void shouldUnsubscribeFromCommands() throws Exception {
    String device1 = randomUUID().toString();

    String subscriber1 = randomUUID().toString();
    String subscriber2 = randomUUID().toString();

    CommandSubscribeRequest sr1 = new CommandSubscribeRequest(subscriber1, device1, null, null);
    Request r1 = Request.newBuilder().withBody(sr1).withSingleReply(false).build();
    TestCallback c1 = new TestCallback();
    client.call(r1, c1);

    CommandSubscribeRequest sr2 = new CommandSubscribeRequest(subscriber2, device1, null, null);
    Request r2 = Request.newBuilder().withBody(sr2).withSingleReply(false).build();
    TestCallback c2 = new TestCallback();
    client.call(r2, c2);

    Stream.of(c1.subscribeFuture, c2.subscribeFuture).forEach(CompletableFuture::join);

    DeviceCommand command = new DeviceCommand();
    command.setId(0);
    command.setCommand("increase_temperature");
    command.setDeviceGuid(device1);
    CommandInsertRequest event = new CommandInsertRequest(command);
    CompletableFuture<Response> f1 = new CompletableFuture<>();
    client.call(Request.newBuilder().withBody(event).build(), f1::complete);

    f1.join();

    assertThat(c1.commands, hasSize(1));
    assertThat(c2.commands, hasSize(1));

    CommandUnsubscribeRequest ur = new CommandUnsubscribeRequest(sr1.getSubscriptionId(), null);
    Request r3 = Request.newBuilder().withBody(ur).withSingleReply(false).build();
    client.call(r3, c1);

    c1.subscribeFuture.join();

    DeviceCommand command2 = new DeviceCommand();
    command2.setId(1);
    command2.setCommand("increase_temperature");
    command2.setDeviceGuid(device1);
    CommandInsertRequest event2 = new CommandInsertRequest(command2);
    CompletableFuture<Response> f2 = new CompletableFuture<>();
    client.call(Request.newBuilder().withBody(event2).build(), f2::complete);

    f2.join();

    assertThat(c1.commands, hasSize(1));
    assertThat(c2.commands, hasSize(2));
}

From source file:com.devicehive.handler.notification.NotificationSubscribeInsertIntegrationTest.java

@Test
@Ignore//from  ww  w.  j a va 2s . c  o  m
public void shouldUnsubscribeFromNotifications() throws Exception {
    String device1 = randomUUID().toString();

    String subscriber1 = randomUUID().toString();
    String subscriber2 = randomUUID().toString();

    NotificationSubscribeRequest sr1 = new NotificationSubscribeRequest(subscriber1, device1, null, null);
    Request r1 = Request.newBuilder().withBody(sr1).withSingleReply(false).build();
    TestCallback c1 = new TestCallback();
    client.call(r1, c1);

    NotificationSubscribeRequest sr2 = new NotificationSubscribeRequest(subscriber2, device1, null, null);
    Request r2 = Request.newBuilder().withBody(sr2).withSingleReply(false).build();
    TestCallback c2 = new TestCallback();
    client.call(r2, c2);

    Stream.of(c1.subscribeFuture, c2.subscribeFuture).forEach(CompletableFuture::join);

    DeviceNotification notification = new DeviceNotification();
    notification.setId(0);
    notification.setNotification("temperature");
    notification.setDeviceGuid(device1);
    NotificationInsertRequest event = new NotificationInsertRequest(notification);
    CompletableFuture<Response> f1 = new CompletableFuture<>();
    client.call(Request.newBuilder().withBody(event).build(), f1::complete);

    f1.get(15, TimeUnit.SECONDS);

    assertThat(c1.notifications, hasSize(1));
    assertThat(c2.notifications, hasSize(1));

    NotificationUnsubscribeRequest ur = new NotificationUnsubscribeRequest(sr1.getSubscriptionId(), null);
    Request r3 = Request.newBuilder().withBody(ur).withSingleReply(false).build();
    client.call(r3, c1);

    c1.subscribeFuture.join();

    DeviceNotification notification2 = new DeviceNotification();
    notification2.setId(1);
    notification2.setNotification("temperature");
    notification2.setDeviceGuid(device1);
    NotificationInsertRequest event2 = new NotificationInsertRequest(notification2);
    CompletableFuture<Response> f2 = new CompletableFuture<>();
    client.call(Request.newBuilder().withBody(event2).build(), f2::complete);

    f2.join();

    assertThat(c1.notifications, hasSize(1));
    assertThat(c2.notifications, hasSize(2));
}

From source file:io.lettuce.core.support.AsyncConnectionPoolSupportTest.java

@Test
public void shouldPropagateAsyncFlow() {

    AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport
            .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri),
                    BoundedPoolConfig.create());

    CompletableFuture<String> pingResponse = pool.acquire().thenCompose(c -> {
        return c.async().ping().whenComplete((s, throwable) -> pool.release(c));
    });/*from w w w.ja  v a2s  .  c o m*/

    pingResponse.join();
    assertThat(pingResponse).isCompletedWithValue("PONG");

    pool.close();
}

From source file:de.kaixo.mubi.lists.store.MubiListsToElasticSearchLoader.java

public boolean prepareIndex(boolean dropAndCreate) {
    final IndicesAdminClient indexClient = client.admin().indices();

    if (indexClient.exists(new IndicesExistsRequest(INDEX_NAME)).actionGet().isExists()) {
        if (dropAndCreate) {
            indexClient.delete(new DeleteIndexRequest(INDEX_NAME)).actionGet();
        } else {//from   ww  w  .j a  va2  s.co  m
            return false;
        }
    }

    InputStream indexSettingsStream = MubiListsToElasticSearchLoader.class
            .getResourceAsStream(INDEX_SETTINGS_JSON);
    if (indexSettingsStream == null) {
        logger.error("Resource not found: " + INDEX_SETTINGS_JSON);
        return false;
    }

    Settings indexSettings = ImmutableSettings.builder()
            .loadFromStream(INDEX_SETTINGS_JSON, indexSettingsStream).build();

    InputStream mappingInputStream = MubiListsToElasticSearchLoader.class
            .getResourceAsStream(LIST_MAPPING_JSON);
    if (mappingInputStream == null) {
        logger.error("Resource not found: " + LIST_MAPPING_JSON);
        return false;
    }

    try {
        String mapping = CharStreams.toString(new InputStreamReader(mappingInputStream, "UTF-8"));
        CompletableFuture<? extends ActionResponse> future = supplyAsync(
                indexClient.prepareCreate(INDEX_NAME).setSettings(indexSettings).addMapping(TYPE, mapping)::get)
                        .thenApply(r -> indexClient.prepareFlush(INDEX_NAME).get());
        future.join();
    } catch (IOException e) {
        // We do not expect this to happen!
        logger.error("This should not have happened!", e);
        return false;
    } catch (ElasticsearchException e) {
        logger.error("While trying to create index " + INDEX_NAME + ": ", e);
        return false;
    } catch (CompletionException e) {
        logger.error("While trying to create index " + INDEX_NAME + ": ", e);
        return false;
    }
    return true;
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_PurgeBuckets.java

/**
 * Returns back all purge sources that aren't marked as complete or errored,
 * deletes everything that was pulled back
 * /*from www  .  j  a  v  a2 s  .com*/
 * @param source_test_db
 * @return
 */
protected CompletableFuture<List<PurgeQueueBean>> getAllPurgeSources(
        final ICrudService<PurgeQueueBean> source_test_db) {
    final QueryComponent<PurgeQueueBean> get_query = CrudUtils.allOf(PurgeQueueBean.class)
            .whenNot(PurgeQueueBean::status, PurgeStatus.complete)
            .whenNot(PurgeQueueBean::status, PurgeStatus.error); //can be complete | error | in_progress | submitted | {unset/anything else}

    final CompletableFuture<List<PurgeQueueBean>> get_command = source_test_db.getObjectsBySpec(get_query)
            .thenApply(c -> StreamSupport.stream(c.spliterator(), false).collect(Collectors.toList()));

    return get_command.thenCompose(__ -> {
        return source_test_db.deleteObjectBySpec(get_query);
    }).thenApply(__ -> get_command.join()); // (ie return the original command but only once the update has completed)
}

From source file:com.nike.cerberus.server.config.guice.CmsGuiceModule.java

@Provides
@Singleton//from w w  w.  j  a va  2 s.  c  o  m
public CodahaleMetricsListener metricsListener(
        @Named("metrics.slf4j.reporting.enabled") boolean slf4jReportingEnabled,
        @Named("metrics.jmx.reporting.enabled") boolean jmxReportingEnabled,
        @Named("graphite.url") String graphiteUrl, @Named("graphite.port") int graphitePort,
        @Named("graphite.reporting.enabled") boolean graphiteEnabled,
        @Named("appInfoFuture") CompletableFuture<AppInfo> appInfoFuture,
        CodahaleMetricsCollector metricsCollector) {
    List<ReporterFactory> reporters = new ArrayList<>();

    if (slf4jReportingEnabled)
        reporters.add(new DefaultSLF4jReporterFactory());

    if (jmxReportingEnabled)
        reporters.add(new DefaultJMXReporterFactory());

    if (graphiteEnabled) {
        AppInfo appInfo = appInfoFuture.join();
        String graphitePrefix = appInfo.appId() + "." + appInfo.dataCenter() + "." + appInfo.environment() + "."
                + appInfo.instanceId();
        reporters.add(new DefaultGraphiteReporterFactory(graphitePrefix, graphiteUrl, graphitePort));
    }

    if (reporters.isEmpty()) {
        logger.info("No metrics reporters enabled - disabling metrics entirely.");
        return null;
    }

    String metricReporterTypes = reporters.stream().map(rf -> rf.getClass().getSimpleName())
            .collect(Collectors.joining(",", "[", "]"));
    logger.info("Metrics enabled. metric_reporter_types={}", metricReporterTypes);

    CodahaleMetricsEngine metricsEngine = new CodahaleMetricsEngine(metricsCollector, reporters);
    metricsEngine.start();
    return new CodahaleMetricsListener(metricsCollector);
}

From source file:com.ikanow.aleph2.graph.titan.services.TestTitanGraphService.java

@Test
public void test_onPublishOrUpdate() {

    final DataBucketBean bucket = BeanTemplateUtils.build(DataBucketBean.class)
            .with(DataBucketBean::full_name, "/test/validate/schema").done().get();

    // do nothing
    {//  w ww .  j  av a  2s  .  co  m
        CompletableFuture<Collection<BasicMessageBean>> ret_val = _mock_graph_db_service.onPublishOrUpdate(
                bucket, Optional.empty(), false, Collections.emptySet(), Collections.emptySet());

        assertEquals(Collections.emptyList(), ret_val.join());
    }
    // create all the indexes
    {
        CompletableFuture<Collection<BasicMessageBean>> ret_val = _mock_graph_db_service.onPublishOrUpdate(
                bucket, Optional.empty(), false, ImmutableSet.of(GraphSchemaBean.name), Collections.emptySet());

        assertEquals("" + ret_val.join().stream().map(b -> b.message()).collect(Collectors.joining(" // ")),
                Collections.emptyList(), ret_val.join());

        // But also now check the Titan indexes have all been created:

        final TitanManagement mgmt = _titan.openManagement();
        Stream<TitanGraphIndex> v_indexes = StreamUtils.stream(mgmt.getGraphIndexes(Vertex.class));
        Stream<TitanGraphIndex> e_indexes = StreamUtils.stream(mgmt.getGraphIndexes(Edge.class));
        assertEquals(4L, v_indexes.count());
        assertEquals(1L, e_indexes.count());
    }
    // rerun to check it all works second+ time round
    {
        CompletableFuture<Collection<BasicMessageBean>> ret_val = _mock_graph_db_service.onPublishOrUpdate(
                bucket, Optional.empty(), false, ImmutableSet.of(GraphSchemaBean.name), Collections.emptySet());

        assertEquals(
                "Should return no errors: "
                        + ret_val.join().stream().map(b -> b.message()).collect(Collectors.joining(";")),
                Collections.emptyList(), ret_val.join());

        // But also now check the Titan indexes have all been created:

        final TitanManagement mgmt = _titan.openManagement();
        Stream<TitanGraphIndex> v_indexes = StreamUtils.stream(mgmt.getGraphIndexes(Vertex.class));
        Stream<TitanGraphIndex> e_indexes = StreamUtils.stream(mgmt.getGraphIndexes(Edge.class));
        assertEquals(4L, v_indexes.count());
        assertEquals(1L, e_indexes.count());
    }
    // Error if specifying deduplication fields
    {
        final GraphSchemaBean graph_schema = BeanTemplateUtils.build(GraphSchemaBean.class)
                .with(GraphSchemaBean::custom_decomposition_configs, Arrays.asList())
                .with(GraphSchemaBean::deduplication_fields, Arrays.asList("nonempty")).done().get();

        final DataBucketBean dedup_fields_bucket = BeanTemplateUtils.build(DataBucketBean.class)
                .with(DataBucketBean::full_name, "/test/on/publish")
                .with(DataBucketBean::data_schema, BeanTemplateUtils.build(DataSchemaBean.class)
                        .with(DataSchemaBean::graph_schema, graph_schema).done().get())
                .done().get();

        CompletableFuture<Collection<BasicMessageBean>> ret_val = _mock_graph_db_service.onPublishOrUpdate(
                dedup_fields_bucket, Optional.empty(), false, ImmutableSet.of(GraphSchemaBean.name),
                Collections.emptySet());

        assertEquals(1, ret_val.join().size());
        assertEquals(1, ret_val.join().stream().filter(b -> !b.success()).count());
    }

    //(See also test_handleBucketDeletionRequest, for some coverage testing of onPublishOrUpdate)
}

From source file:com.ikanow.aleph2.management_db.services.DataBucketStatusCrudService.java

/** Tries to distribute a request to listening data import managers to notify their harvesters that the bucket state has been updated
 * @param update_reply - the future reply to the find-and-update
 * @param suspended_predicate - takes the status bean (must exist at this point) and checks whether the bucket should be suspended
 * @param underlying_data_bucket_db - the data bucket bean db store
 * @param actor_context - actor context for distributing out requests
 * @param retry_store - the retry store for handling data import manager connectivity problems
 * @return a collection of success/error messages from either this function or the 
 *//*from   ww w.  java  2 s  . com*/
private static <T> CompletableFuture<Collection<BasicMessageBean>> getOperationFuture(
        final CompletableFuture<Optional<DataBucketStatusBean>> update_reply,
        final Predicate<DataBucketStatusBean> suspended_predicate,
        final ICrudService<DataBucketBean> underlying_data_bucket_db,
        final ICrudService<DataBucketStatusBean> underlying_data_bucket_status_db,
        final ManagementDbActorContext actor_context,
        final ICrudService<BucketActionRetryMessage> retry_store) {
    return update_reply.thenCompose(sb -> {
        return sb.isPresent() ? underlying_data_bucket_db.getObjectById(sb.get()._id())
                : CompletableFuture.completedFuture(Optional.empty());
    }).thenCompose(bucket -> {
        if (!bucket.isPresent()) {
            return CompletableFuture.completedFuture(Arrays.asList(new BasicMessageBean(new Date(), // date
                    false, // success
                    IManagementDbService.CORE_MANAGEMENT_DB.get(),
                    BucketActionMessage.UpdateBucketActionMessage.class.getSimpleName(), null, // message code
                    ErrorUtils.get(ManagementDbErrorUtils.MISSING_STATUS_BEAN_OR_BUCKET,
                            update_reply.join().map(s -> s._id()).orElse("(unknown)")),
                    null) // details                  
            ));
        } else { // If we're here we've retrieved both the bucket and bucket status, so we're good to go
            final DataBucketStatusBean status_bean = update_reply.join().get();
            // (as above, if we're here then must exist)

            // Once we have the bucket, issue the update command
            final BucketActionMessage.UpdateBucketActionMessage update_message = new BucketActionMessage.UpdateBucketActionMessage(
                    bucket.get(), suspended_predicate.test(status_bean), // (ie user picks whether to suspend or unsuspend here)
                    bucket.get(), new HashSet<String>(
                            Optional.ofNullable(status_bean.node_affinity()).orElse(Collections.emptyList())));

            // Collect message and handle retries

            final CompletableFuture<Collection<BasicMessageBean>> management_results = MgmtCrudUtils
                    .applyRetriableManagementOperation(bucket.get(), actor_context, retry_store, update_message,
                            source -> {
                                return new BucketActionMessage.UpdateBucketActionMessage(
                                        update_message.bucket(), status_bean.suspended(),
                                        update_message.bucket(), new HashSet<String>(Arrays.asList(source)));
                            });

            return MgmtCrudUtils.handleUpdatingStatus(bucket.get(), status_bean,
                    suspended_predicate.test(status_bean), management_results,
                    underlying_data_bucket_status_db);
        }
    });
}

From source file:com.ikanow.aleph2.graph.titan.services.TestTitanGraphService.java

@SuppressWarnings("unchecked")
@Test/*from   w w  w  . j  a  v a 2s .  c om*/
public void test_handleBucketDeletionRequest() throws InterruptedException {
    final org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper titan_mapper = _titan.io(IoCore.graphson())
            .mapper().create().createMapper();

    // Ensure indexes exist

    final DataBucketBean bucket = BeanTemplateUtils.build(DataBucketBean.class)
            .with(DataBucketBean::full_name, "/test/bucket/delete").done().get();

    _mock_graph_db_service.onPublishOrUpdate(bucket, Optional.empty(), false,
            ImmutableSet.of(GraphSchemaBean.name), Collections.emptySet()).join();

    // Add a bunch of edges to delete

    final int N_OBJECTS = 300;
    {
        final TitanTransaction tx = _titan.buildTransaction().start();

        for (int ii = 0; ii < N_OBJECTS; ++ii) { // needs to be x6

            final Vertex v1 = tx.addVertex("test_del_A_" + ii);
            final Vertex v2 = tx.addVertex("test_del_B_" + ii);
            final Edge e1 = v1.addEdge("test_edge_" + ii, v2);
            if (0 == (ii % 3)) {
                v1.property(GraphAnnotationBean.a2_p, "/test/bucket/delete");
                v2.property(GraphAnnotationBean.a2_p, "/test/bucket/delete");
                e1.property(GraphAnnotationBean.a2_p, "/test/bucket/delete");
            } else if (1 == (ii % 3)) {
                v1.property(GraphAnnotationBean.a2_p, "/test/bucket/no_delete");
                v2.property(GraphAnnotationBean.a2_p, "/test/bucket/no_delete");
                e1.property(GraphAnnotationBean.a2_p, "/test/bucket/no_delete");
            } else if (2 == (ii % 3)) {
                v1.property(GraphAnnotationBean.a2_p, "/test/bucket/delete");
                v2.property(GraphAnnotationBean.a2_p, "/test/bucket/delete");
                v1.property(org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality.set,
                        GraphAnnotationBean.a2_p, "/test/bucket/delete_2");
                v2.property(org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality.set,
                        GraphAnnotationBean.a2_p, "/test/bucket/delete_2");

                // Alternate edges
                if (2 == (ii % 6)) {
                    e1.property(GraphAnnotationBean.a2_p, "/test/bucket/delete");
                } else {
                    e1.property(GraphAnnotationBean.a2_p, "/test/bucket/delete_2");
                }
            }

        }
        System.out.println("Building test graph: " + new Date().getTime());
        tx.commit();
        System.out.println("Built test graph: " + new Date().getTime());
    }
    //(wait for the data to appear)
    System.out.println("Waiting 2s for ES to refresh...");
    Thread.sleep(2000L);

    // Quick test that the setup seems sensible
    {
        final TitanTransaction tx = _titan.buildTransaction().start();

        //(have to use an index, full scans are disabled)
        assertEquals(2 * N_OBJECTS, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices()).count());
        assertEquals(N_OBJECTS, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").edges()).count());
        tx.commit();
    }

    // First phase of deletes 
    {
        final TitanTransaction tx = _titan.buildTransaction().start();

        {
            CompletableFuture<BasicMessageBean> ret_val = _mock_graph_db_service
                    .handleBucketDeletionRequest(bucket, Optional.of("alex"), true);

            // Got a "fail" reply
            assertEquals(false, ret_val.join().success());
        }
        //(try again without the secondary buffer)
        {
            CompletableFuture<BasicMessageBean> ret_val = _mock_graph_db_service
                    .handleBucketDeletionRequest(bucket, Optional.empty(), true);

            // Got a "success" reply
            assertEquals(true, ret_val.join().success());
        }

        System.out.println("Waiting 2s for ES to refresh... " + new Date().getTime());
        Thread.sleep(2000L);

        //(have to use an index, full scans are disabled)
        assertEquals("Vertices", 2 * (2 * N_OBJECTS) / 3, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices()).count());
        assertEquals("Edges", N_OBJECTS / 2, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").edges()).count());
        assertEquals("Vertices", 2 * (2 * N_OBJECTS) / 3, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "/test/bucket/delete").vertices()).count());
        assertEquals("Edges", N_OBJECTS / 2, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "/test/bucket/delete").edges()).count());

        // (Check that all the vertex references to the bucket have gone) 
        StreamUtils
                .<TitanVertex>stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices())
                .forEach((Vertex v) -> {
                    if (Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false)
                            .anyMatch(p -> p.value().equals("/test/bucket/delete"))) {
                        fail("All refs to /test/bucket/delete should be gone: "
                                + titan_mapper.convertValue(v, JsonNode.class));
                    }
                    v.edges(Direction.BOTH).forEachRemaining(e -> { //(should be implied by the edge query, but just to be on the safe side...)
                        if (Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false)
                                .anyMatch(p -> p.value().equals("/test/bucket/delete"))) {
                            fail("All refs to /test/bucket/delete should be gone: "
                                    + titan_mapper.convertValue(e, JsonNode.class));
                        }
                    });
                });

        tx.commit();
    }

    // Second phase of deletes (first: make sure fails if specifiy a secondary buffer)
    {
        CompletableFuture<BasicMessageBean> ret_val = _mock_graph_db_service.handleBucketDeletionRequest(bucket,
                Optional.of("alex"), true);

        assertFalse(ret_val.join().success());
    }
    // Let's try that again...
    {
        final DataBucketBean other_bucket = BeanTemplateUtils.build(DataBucketBean.class)
                .with(DataBucketBean::full_name, "/test/bucket/delete_2").done().get();

        final TitanTransaction tx = _titan.buildTransaction().start();

        CompletableFuture<BasicMessageBean> ret_val = _mock_graph_db_service
                .handleBucketDeletionRequest(other_bucket, Optional.empty(), true);

        assertTrue(ret_val.join().success());

        System.out.println("Waiting 2s for ES to refresh... " + new Date().getTime());
        Thread.sleep(2000L);

        //(have to use an index, full scans are disabled)
        assertEquals("Vertices", (2 * N_OBJECTS) / 3, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").vertices()).count());
        assertEquals("Edges", N_OBJECTS / 3, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "get_everything").edges()).count());
        assertEquals("Vertices", (2 * N_OBJECTS) / 3,
                StreamUtils
                        .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "/test/bucket/delete_2").vertices())
                        .count());
        assertEquals("Edges", N_OBJECTS / 3, StreamUtils
                .stream(tx.query().hasNot(GraphAnnotationBean.a2_p, "/test/bucket/delete_2").edges()).count());

        tx.commit();
    }
}