Example usage for java.util.concurrent CompletableFuture isDone

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

Introduction

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

Prototype

public boolean isDone() 

Source Link

Document

Returns true if completed in any fashion: normally, exceptionally, or via cancellation.

Usage

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void invoke_onOkRequest_onIOException_futureCompletesExceptionally()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Req req = new Req();

    Channel channel = mock(Channel.class);
    doAnswer(invocation -> {//from  w w  w .  j  a  va 2  s  .c o  m
        throw new IOException("boom");
    }).when(channel).basicPublish(anyString(), any(), any(), any());

    CompletableFuture<Res> answer = new CompletableFuture<>();
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    doReturn(answer).when(receiver).put(anyString(), any());

    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);
    doReturn(DEFAULT_RPC_EXCHANGE).when(channelProvider).rpcExchange();

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver);
    CompletableFuture<Res> actual = invoker.invoke(req, Res.class);

    assertSame(answer, actual);
    assertTrue(actual.isDone());
    assertTrue(actual.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        actual.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof IOException);
        throw ex;
    }
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void invoke_onNokRequest_onIllegalArgEx_futureCompletesExceptionally()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Req req = new Req();

    Channel channel = mock(Channel.class);

    CompletableFuture<Res> answer = new CompletableFuture<>();
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    doReturn(answer).when(receiver).put(anyString(), any());

    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);

    ObjectMapper mapper = mock(ObjectMapper.class);
    doThrow(IllegalArgumentException.class).when(mapper).writeValueAsBytes(any());

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver,
            new DefaultRequestRouter(), new UidGenerator() {
            }, new DefaultSerializer(mapper), Maps.newHashMap());
    CompletableFuture<Res> actual = invoker.invoke(req, Res.class);

    assertSame(answer, actual);/*from   www.  j  a v a  2  s. com*/
    assertTrue(actual.isDone());
    assertTrue(actual.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        actual.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof IllegalArgumentException);
        throw ex;
    }
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void invoke_onNokRequest_onEncodingEx_futureCompletesExceptionally()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Req req = new Req();

    Channel channel = mock(Channel.class);

    CompletableFuture<Res> answer = new CompletableFuture<>();
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    doReturn(answer).when(receiver).put(anyString(), any());

    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);

    ObjectMapper mapper = mock(ObjectMapper.class);
    doThrow(JsonProcessingException.class).when(mapper).writeValueAsBytes(any());

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver,
            new DefaultRequestRouter(), new UidGenerator() {
            }, new DefaultSerializer(mapper), Maps.newHashMap());
    CompletableFuture<Res> actual = invoker.invoke(req, Res.class);

    assertSame(answer, actual);/*from  ww  w  .ja va  2  s .  c o  m*/
    assertTrue(actual.isDone());
    assertTrue(actual.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        actual.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof EncodingException);
        throw ex;
    }
}

From source file:io.pravega.segmentstore.server.reading.StorageReaderTests.java

/**
 * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read).
 * Test this both with successful and failed reads.
 */// ww  w. jav  a 2 s .  co m
@Test
public void testDependents() {
    final Duration waitTimeout = Duration.ofSeconds(5);
    TestStorage storage = new TestStorage();
    CompletableFuture<Integer> signal = new CompletableFuture<>();
    AtomicBoolean wasReadInvoked = new AtomicBoolean();
    storage.readImplementation = () -> {
        if (wasReadInvoked.getAndSet(true)) {
            Assert.fail(
                    "Read was invoked multiple times, which is a likely indicator that the requests were not chained.");
        }
        return signal;
    };

    @Cleanup
    StorageReader reader = new StorageReader(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    CompletableFuture<StorageReader.Result> c1 = new CompletableFuture<>();
    CompletableFuture<StorageReader.Result> c2 = new CompletableFuture<>();
    reader.execute(new StorageReader.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT));
    reader.execute(new StorageReader.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT));

    Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone());

    signal.completeExceptionally(new IntentionalException());
    AssertExtensions.assertThrows("The first read was not failed with the correct exception.",
            () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);

    AssertExtensions.assertThrows("The second read was not failed with the correct exception.",
            () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void closingInvoker_onIOException_exception()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Channel channel = mock(Channel.class);
    doThrow(new IOException("boom")).when(channel).close();
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver);

    CompletableFuture<Void> actual = invoker.close();

    verify(channel).close();//from   w ww. j av  a 2 s  .  c o m
    verifyNoMoreInteractions(channel);

    assertTrue(actual.isDone());
    assertTrue(actual.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        actual.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof IOException);
        throw ex;
    }
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void closingInvoker_success()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Channel channel = mock(Channel.class);
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver);

    CompletableFuture<Void> actual = invoker.close();

    verify(channel).close();/*  w  w  w.j a  v  a  2  s .  c o  m*/
    verifyNoMoreInteractions(channel);

    actual.get();

    assertTrue(actual.isDone());
    assertFalse(actual.isCompletedExceptionally());
}

From source file:io.pravega.segmentstore.server.reading.StorageReadManagerTests.java

/**
 * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read).
 * Test this both with successful and failed reads.
 *//*w w w.  j  av a  2  s.c o m*/
@Test
public void testDependents() {
    final Duration waitTimeout = Duration.ofSeconds(5);
    TestStorage storage = new TestStorage();
    CompletableFuture<Integer> signal = new CompletableFuture<>();
    AtomicBoolean wasReadInvoked = new AtomicBoolean();
    storage.readImplementation = () -> {
        if (wasReadInvoked.getAndSet(true)) {
            Assert.fail(
                    "Read was invoked multiple times, which is a likely indicator that the requests were not chained.");
        }
        return signal;
    };

    @Cleanup
    StorageReadManager reader = new StorageReadManager(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    CompletableFuture<StorageReadManager.Result> c1 = new CompletableFuture<>();
    CompletableFuture<StorageReadManager.Result> c2 = new CompletableFuture<>();
    reader.execute(new StorageReadManager.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT));
    reader.execute(new StorageReadManager.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT));

    Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone());

    signal.completeExceptionally(new IntentionalException());
    AssertExtensions.assertThrows("The first read was not failed with the correct exception.",
            () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);

    AssertExtensions.assertThrows("The second read was not failed with the correct exception.",
            () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);
}

From source file:com.eventsourcing.repository.RepositoryTest.java

@Test
@SneakyThrows/*from  w w w  .j  a  v a  2  s  .co m*/
public void streamExceptionIndexing() {
    IndexedCollection<EntityHandle<TestEvent>> coll = indexEngine.getIndexedCollection(TestEvent.class);
    coll.clear();
    UUID eventUUID = UUID.randomUUID();
    StreamExceptionCommand command = StreamExceptionCommand.builder().eventUUID(eventUUID).build();
    CompletableFuture<Void> future = repository.publish(command);
    while (!future.isDone()) {
        Thread.sleep(10);
    } // to avoid throwing an exception
    assertTrue(future.isCompletedExceptionally());
    // result() was not called
    assertFalse(command.isResultCalled());
    try (ResultSet<EntityHandle<CommandTerminatedExceptionally>> resultSet = repository.query(
            CommandTerminatedExceptionally.class,
            and(all(CommandTerminatedExceptionally.class),
                    existsIn(indexEngine.getIndexedCollection(EventCausalityEstablished.class),
                            CommandTerminatedExceptionally.ID, EventCausalityEstablished.EVENT)))) {
        assertEquals(resultSet.size(), 1);
    }
    assertTrue(journal.get(command.uuid()).isPresent());
    assertFalse(journal.get(eventUUID).isPresent());
    assertTrue(repository.query(TestEvent.class, equal(TestEvent.ATTR, "test")).isEmpty());
}

From source file:com.yahoo.pulsar.broker.service.BrokerService.java

public Topic getTopicReference(String topic) throws Exception {
    CompletableFuture<Topic> future = topics.get(topic);
    if (future != null && future.isDone() && !future.isCompletedExceptionally()) {
        return future.get();
    } else {/* www  .  java 2  s. co m*/
        return null;
    }
}

From source file:com.yahoo.pulsar.broker.service.ServerCnx.java

@Override
protected void handleAck(CommandAck ack) {
    checkArgument(state == State.Connected);
    CompletableFuture<Consumer> consumerFuture = consumers.get(ack.getConsumerId());

    if (consumerFuture != null && consumerFuture.isDone() && !consumerFuture.isCompletedExceptionally()) {
        consumerFuture.getNow(null).messageAcked(ack);
    }//w  w  w. j  av  a 2 s .com
}