Example usage for java.util.concurrent CompletableFuture CompletableFuture

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

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> updateIndexTable(Data<Integer> updated) {
    Preconditions.checkNotNull(updated);
    Preconditions.checkNotNull(updated.getData());

    final CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (lock) {
        if (indexTable == null) {
            result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Indextable for stream: " + getName()));
        } else if (indexTable.getVersion().equals(updated.getVersion())) {
            indexTable = new Data<>(Arrays.copyOf(updated.getData(), updated.getData().length),
                    updated.getVersion() + 1);
            result.complete(null);//from  w w w.  j a  v a 2 s . c o m
        } else {
            result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT,
                    "Indextable for stream: " + getName()));
        }
    }
    return result;
}

From source file:co.runrightfast.vertx.core.impl.VertxServiceImpl.java

@Override
protected void shutDown() {
    if (vertx != null) {
        appEventLogger.accept(AppEvent.info(APP_STOPPING).build());
        final CompletableFuture<AsyncResult<Void>> closeResult = new CompletableFuture<>();
        vertx.close(closeResult::complete);
        while (true) {
            try {
                closeResult.get(10, TimeUnit.SECONDS);
                LOG.info("Vertx shutdown is complete.");
                appEventLogger.accept(AppEvent.info(APP_STOPPED).build());
                vertx = null;/*from   w  w w .j  a v a2s . c  o m*/
                vertxOptions = null;
                break;
            } catch (final ExecutionException ex) {
                appEventLogger.accept(AppEvent.info(APP_STOP_EXCEPTION).setException(ex).build());
                throw new RuntimeException("shutdown failed", ex);
            } catch (final TimeoutException ex) {
                LOG.logp(INFO, getClass().getName(), "shutDown", "Waiting for Vertx to shutdown");
            } catch (final InterruptedException ex) {
                appEventLogger.accept(AppEvent.info(APP_STOP_EXCEPTION).setException(ex).build());
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java

private boolean doArbitrationUpdate() {
    CompletableFuture<Boolean> result = new CompletableFuture<>();
    // TODO: currently we use 64-bit Long type for election id, should
    // we use 128-bit ?
    long nextElectId = controller.getNewMasterElectionId();
    Uint128 newElectionId = Uint128.newBuilder().setLow(nextElectId).build();
    MasterArbitrationUpdate arbitrationUpdate = MasterArbitrationUpdate.newBuilder().setDeviceId(p4DeviceId)
            .setElectionId(newElectionId).build();
    StreamMessageRequest requestMsg = StreamMessageRequest.newBuilder().setArbitration(arbitrationUpdate)
            .build();//from w w  w  . ja va2  s . com
    log.debug("Sending arbitration update to {} with election id {}...", deviceId, newElectionId);
    arbitrationUpdateMap.put(newElectionId, result);
    try {
        streamRequestObserver.onNext(requestMsg);
        return result.get();
    } catch (StatusRuntimeException e) {
        log.error("Unable to perform arbitration update on {}: {}", deviceId, e.getMessage());
        arbitrationUpdateMap.remove(newElectionId);
        return false;
    } catch (InterruptedException | ExecutionException e) {
        log.warn("Arbitration update failed for {} due to {}", deviceId, e);
        arbitrationUpdateMap.remove(newElectionId);
        return false;
    }
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

private <T> CompletableFuture<T> getInformation(Class<T> infoType, InformationSubject subject, String detail) {
    CompletableFuture<T> future = new CompletableFuture<>();
    if (!checkOpenAndNoErrors(future)) {
        return future;
    }/*from   w  w w .  j a  v a2s.  co m*/
    send(new InformationRequestMessage(subject, detail), new ResponseHandler<>(future, m -> {
        if (m.isA(MessageType.ReadyMessage)) {
            return false; // just ignore them
        } else if (m.isA(MessageType.InformationResponseMessage)) {
            InformationResponseMessage response = m.secureCast();
            Object value = response.getValue();
            if (!response.getResponseType().isCompatibleTo(infoType)) {
                future.completeExceptionally(new UnexpectedResultTypeException(value, infoType));
            } else {
                future.complete(infoType.cast(value));
            }
            return true;
        }
        throw new UnexpectedMessageException("waiting for information response", m);
    }));
    return future;
}

From source file:com.vmware.loginsightapi.LogInsightClient.java

/**
 * Performs aggregate query. Accepts callback
 * //from  www. ja  v  a 2  s  . c o m
 * @param apiUrl
 *            relative url of the API
 * @return AggregateResponse CompletableFuture
 * 
 */
public CompletableFuture<AggregateResponse> aggregateQuery(String apiUrl) {
    HttpGet request = null;
    CompletableFuture<AggregateResponse> completableFuture = new CompletableFuture<AggregateResponse>();
    try {
        request = getHttpRequest(apiUrl, true);
        logger.debug("Querying " + aggregateQueryUrl() + apiUrl);
        asyncHttpClient.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse httpResponse) {

                try {
                    String responseString = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
                    logger.warn("Response: " + responseString);
                    completableFuture.complete(AggregateResponse.fromJsonString(responseString));

                } catch (IOException e) {
                    e.printStackTrace();
                    completableFuture.completeExceptionally(
                            new LogInsightApiException("Unable to process the query response", e));
                }

            }

            @Override
            public void failed(Exception ex) {
                completableFuture.completeExceptionally(new LogInsightApiException("Failed message Query", ex));
            }

            @Override
            public void cancelled() {
                completableFuture.completeExceptionally(new LogInsightApiException("Cancelled message Query"));
            }

        });
    } catch (Exception ie) {
        completableFuture.completeExceptionally(new LogInsightApiException("Message query failed", ie));
    }
    return completableFuture;
}

From source file:com.yahoo.pulsar.broker.namespace.NamespaceServiceTest.java

@Test
public void testUnloadNamespaceBundleFailure() throws Exception {

    final String topicName = "persistent://my-property/use/my-ns/my-topic1";
    ConsumerConfiguration conf = new ConsumerConfiguration();
    Consumer consumer = pulsarClient.subscribe(topicName, "my-subscriber-name", conf);
    ConcurrentOpenHashMap<String, CompletableFuture<Topic>> topics = pulsar.getBrokerService().getTopics();
    Topic spyTopic = spy(topics.get(topicName).get());
    topics.clear();//w ww. ja va  2 s.  c  om
    CompletableFuture<Topic> topicFuture = CompletableFuture.completedFuture(spyTopic);
    // add mock topic
    topics.put(topicName, topicFuture);
    doAnswer(new Answer<CompletableFuture<Void>>() {
        @Override
        public CompletableFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
            CompletableFuture<Void> result = new CompletableFuture<>();
            result.completeExceptionally(new RuntimeException("first time failed"));
            return result;
        }
    }).when(spyTopic).close();
    NamespaceBundle bundle = pulsar.getNamespaceService().getBundle(DestinationName.get(topicName));
    try {
        pulsar.getNamespaceService().unloadNamespaceBundle(bundle);
    } catch (Exception e) {
        // fail
        fail(e.getMessage());
    }
    try {
        pulsar.getLocalZkCache().getZooKeeper().getData(ServiceUnitZkUtils.path(bundle), null, null);
        fail("it should fail as node is not present");
    } catch (org.apache.zookeeper.KeeperException.NoNodeException e) {
        // ok
    }
}

From source file:org.onosproject.store.consistent.impl.DistributedLeadershipManager.java

@Override
public CompletableFuture<Void> withdraw(String path) {
    activeTopics.remove(path);//ww w .ja  va2 s  .co m
    CompletableFuture<Void> resultFuture = new CompletableFuture<>();
    doWithdraw(path, resultFuture);
    return resultFuture;
}

From source file:io.pravega.controller.store.stream.ZKStream.java

@Override
CompletableFuture<Integer> createNewTransaction(final UUID txId, final long timestamp,
        final long leaseExpiryTime, final long maxExecutionExpiryTime, final long scaleGracePeriod) {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    createNewTransactionNode(txId, timestamp, leaseExpiryTime, maxExecutionExpiryTime, scaleGracePeriod)
            .whenComplete((value, ex) -> {
                if (ex != null) {
                    if (ExceptionHelpers.getRealException(ex) instanceof StoreException.DataNotFoundException) {
                        FutureHelpers.completeAfter(() -> createNewTransactionNode(txId, timestamp,
                                leaseExpiryTime, maxExecutionExpiryTime, scaleGracePeriod), future);
                    } else {
                        future.completeExceptionally(ex);
                    }/*from  w ww . j  av  a2 s  .  c o  m*/
                } else {
                    future.complete(value);
                }
            });
    return future;
}

From source file:com.ikanow.aleph2.aleph2_rest_utils.DataStoreCrudService.java

@Override
public CompletableFuture<Cursor<FileDescriptor>> getObjectsBySpec(QueryComponent<FileDescriptor> spec,
        List<String> field_list, boolean include) {
    try {//from  w  w w  .  j  a  v a2s  .  co m
        return CompletableFuture
                .completedFuture(new DataStoreCursor(getFolderFilenames(output_directory, fileContext)));
    } catch (IllegalArgumentException | IOException e) {
        final CompletableFuture<Cursor<FileDescriptor>> fut = new CompletableFuture<Cursor<FileDescriptor>>();
        fut.completeExceptionally(e);
        return fut;
    }
}

From source file:org.apache.pulsar.functions.instance.JavaInstanceRunnableProcessTest.java

@BeforeMethod
public void setup() throws Exception {
    mockProducers.clear();/*from   ww w  .j a v  a 2 s.c o  m*/
    mockConsumers.clear();

    functionDetails = FunctionDetails.newBuilder().setAutoAck(true).setClassName(TestFunction.class.getName())
            .addInputs("test-src-topic").setName("test-function").setOutput("test-output-topic")
            .setProcessingGuarantees(ProcessingGuarantees.ATLEAST_ONCE).setTenant("test-tenant")
            .setNamespace("test-namespace").build();

    config = new InstanceConfig();
    config.setFunctionId("test-function-id");
    config.setFunctionVersion("v1");
    config.setInstanceId("test-instance-id");
    config.setMaxBufferedTuples(1000);
    config.setFunctionDetails(functionDetails);

    mockClient = mock(PulsarClientImpl.class);

    // mock FunctionCacheManager
    fnCache = mock(FunctionCacheManager.class);
    doNothing().when(fnCache).registerFunctionInstance(anyString(), anyString(), anyList(), anyList());
    doNothing().when(fnCache).unregisterFunctionInstance(anyString(), anyString());

    ClassLoader clsLoader = JavaInstanceRunnableTest.class.getClassLoader();
    when(fnCache.getClassLoader(anyString())).thenReturn(clsLoader);

    // mock producer & consumer
    when(mockClient.createProducer(anyString(), any(ProducerConfiguration.class)))
            .thenAnswer(invocationOnMock -> {
                String topic = invocationOnMock.getArgumentAt(0, String.class);
                ProducerConfiguration conf = invocationOnMock.getArgumentAt(1, ProducerConfiguration.class);
                String producerName = conf.getProducerName();

                Pair<String, String> pair = Pair.of(topic, producerName);
                ProducerInstance producerInstance = mockProducers.get(pair);
                if (null == producerInstance) {
                    Producer producer = mock(Producer.class);
                    LinkedBlockingQueue<Message> msgQueue = new LinkedBlockingQueue<>();
                    final ProducerInstance instance = new ProducerInstance(producer, msgQueue);
                    producerInstance = instance;
                    when(producer.getProducerName()).thenReturn(producerName);
                    when(producer.getTopic()).thenReturn(topic);
                    when(producer.sendAsync(any(Message.class))).thenAnswer(invocationOnMock1 -> {
                        Message msg = invocationOnMock1.getArgumentAt(0, Message.class);
                        log.info("producer send message {}", msg);

                        CompletableFuture<MessageId> future = new CompletableFuture<>();
                        instance.addSendFuture(future);
                        msgQueue.put(msg);
                        return future;
                    });
                    when(producer.closeAsync()).thenReturn(FutureUtils.Void());

                    mockProducers.put(pair, producerInstance);
                }
                return producerInstance.getProducer();
            });
    when(mockClient.subscribe(anyString(), anyString(), any(ConsumerConfiguration.class)))
            .thenAnswer(invocationOnMock -> {
                String topic = invocationOnMock.getArgumentAt(0, String.class);
                String subscription = invocationOnMock.getArgumentAt(1, String.class);
                ConsumerConfiguration conf = invocationOnMock.getArgumentAt(2, ConsumerConfiguration.class);

                Pair<String, String> pair = Pair.of(topic, subscription);
                ConsumerInstance consumerInstance = mockConsumers.get(pair);
                if (null == consumerInstance) {
                    Consumer consumer = mock(Consumer.class);

                    ConsumerInstance instance = new ConsumerInstance(consumer, conf);
                    consumerInstance = instance;
                    when(consumer.getTopic()).thenReturn(topic);
                    when(consumer.getSubscription()).thenReturn(subscription);
                    when(consumer.acknowledgeAsync(any(Message.class))).thenAnswer(invocationOnMock1 -> {
                        Message msg = invocationOnMock1.getArgumentAt(0, Message.class);
                        log.info("Ack message {} : message id = {}", msg, msg.getMessageId());

                        instance.removeMessage(msg.getMessageId());
                        return FutureUtils.Void();
                    });
                    when(consumer.acknowledgeCumulativeAsync(any(Message.class)))
                            .thenAnswer(invocationOnMock1 -> {
                                Message msg = invocationOnMock1.getArgumentAt(0, Message.class);
                                log.info("Ack message cumulatively message id = {}", msg, msg.getMessageId());

                                instance.removeMessagesBefore(msg.getMessageId());
                                return FutureUtils.Void();
                            });
                    when(consumer.closeAsync()).thenAnswer(invocationOnMock1 -> {
                        mockConsumers.remove(pair, instance);
                        return FutureUtils.Void();
                    });
                    doAnswer(invocationOnMock1 -> {
                        mockConsumers.remove(pair, instance);
                        return null;
                    }).when(consumer).close();

                    mockConsumers.put(pair, consumerInstance);
                }
                return consumerInstance.getConsumer();
            });

    //
    // Mock State Store
    //

    StorageClientBuilder mockBuilder = mock(StorageClientBuilder.class);
    when(mockBuilder.withNamespace(anyString())).thenReturn(mockBuilder);
    when(mockBuilder.withSettings(any(StorageClientSettings.class))).thenReturn(mockBuilder);
    this.mockStorageClient = mock(StorageClient.class);
    when(mockBuilder.build()).thenReturn(mockStorageClient);
    StorageAdminClient adminClient = mock(StorageAdminClient.class);
    when(mockBuilder.buildAdmin()).thenReturn(adminClient);

    PowerMockito.mockStatic(StorageClientBuilder.class);
    PowerMockito.when(StorageClientBuilder.newBuilder()).thenReturn(mockBuilder);

    when(adminClient.getStream(anyString(), anyString()))
            .thenReturn(FutureUtils.value(StreamProperties.newBuilder().build()));
    mockTable = mock(Table.class);
    when(mockStorageClient.openTable(anyString())).thenReturn(FutureUtils.value(mockTable));

    //
    // Mock Function Stats
    //

    mockFunctionStats = spy(new FunctionStats());
    PowerMockito.whenNew(FunctionStats.class).withNoArguments().thenReturn(mockFunctionStats);

    // Mock message builder
    PowerMockito.mockStatic(MessageBuilder.class);
    PowerMockito.when(MessageBuilder.create()).thenAnswer(invocationOnMock -> {

        Message msg = mock(Message.class);
        MessageBuilder builder = mock(MessageBuilder.class);
        when(builder.setContent(any(byte[].class))).thenAnswer(invocationOnMock1 -> {
            byte[] content = invocationOnMock1.getArgumentAt(0, byte[].class);
            when(msg.getData()).thenReturn(content);
            return builder;
        });
        when(builder.setSequenceId(anyLong())).thenAnswer(invocationOnMock1 -> {
            long seqId = invocationOnMock1.getArgumentAt(0, long.class);
            when(msg.getSequenceId()).thenReturn(seqId);
            return builder;
        });
        when(builder.setProperty(anyString(), anyString())).thenAnswer(invocationOnMock1 -> {
            String key = invocationOnMock1.getArgumentAt(0, String.class);
            String value = invocationOnMock1.getArgumentAt(1, String.class);
            when(msg.getProperty(eq(key))).thenReturn(value);
            return builder;
        });
        when(builder.build()).thenReturn(msg);
        return builder;
    });
}