List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:com.vmware.loginsightapi.LogInsightClient.java
/** * Performs message query. Returns a CompletableFuture for * MessageQueryResponse/*w ww. jav a 2 s . com*/ * * @param apiUrl * relative url of the API * @return MessageQueryResponse CompletableFuture object * @throws LogInsightApiException * Exception */ public CompletableFuture<MessageQueryResponse> messageQuery(String apiUrl) { HttpGet request = null; CompletableFuture<MessageQueryResponse> completableFuture = new CompletableFuture<MessageQueryResponse>(); try { request = getHttpRequest(apiUrl, false); asyncHttpClient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { try { InputStream responseBody = httpResponse.getEntity().getContent(); String responseString = IOUtils.toString(responseBody, "UTF-8"); logger.warn("Response: " + responseString); completableFuture.complete(MessageQueryResponse.fromJsonString(responseString)); } catch (IOException e) { e.printStackTrace(); completableFuture.completeExceptionally(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.client.impl.PulsarClientImpl.java
@Override public CompletableFuture<Consumer> subscribeAsync(final String topic, final String subscription, final ConsumerConfiguration conf) { if (state.get() != State.Open) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed")); }// w w w . j a va 2s . com if (!DestinationName.isValid(topic)) { return FutureUtil .failedFuture(new PulsarClientException.InvalidTopicNameException("Invalid topic name")); } if (subscription == null) { return FutureUtil.failedFuture( new PulsarClientException.InvalidConfigurationException("Invalid subscription name")); } if (conf == null) { return FutureUtil.failedFuture( new PulsarClientException.InvalidConfigurationException("Consumer configuration undefined")); } CompletableFuture<Consumer> consumerSubscribedFuture = new CompletableFuture<>(); getPartitionedTopicMetadata(topic).thenAccept(metadata -> { if (log.isDebugEnabled()) { log.debug("[{}] Received topic metadata. partitions: {}", topic, metadata.partitions); } ConsumerBase consumer; // gets the next single threaded executor from the list of executors ExecutorService listenerThread = externalExecutorProvider.getExecutor(); if (metadata.partitions > 1) { consumer = new PartitionedConsumerImpl(PulsarClientImpl.this, topic, subscription, conf, metadata.partitions, listenerThread, consumerSubscribedFuture); } else { consumer = new ConsumerImpl(PulsarClientImpl.this, topic, subscription, conf, listenerThread, consumerSubscribedFuture); } synchronized (consumers) { consumers.put(consumer, Boolean.TRUE); } }).exceptionally(ex -> { log.warn("[{}] Failed to get partitioned topic metadata", topic, ex); consumerSubscribedFuture.completeExceptionally(ex); return null; }); return consumerSubscribedFuture; }
From source file:org.apache.pulsar.tests.integration.utils.DockerUtils.java
public static ContainerExecResultBytes runCommandWithRawOutput(DockerClient docker, String containerId, String... cmd) throws ContainerExecException { CompletableFuture<Boolean> future = new CompletableFuture<>(); String execid = docker.execCreateCmd(containerId).withCmd(cmd).withAttachStderr(true).withAttachStdout(true) .exec().getId();//from w ww . ja v a 2 s . com String cmdString = Arrays.stream(cmd).collect(Collectors.joining(" ")); ByteBuf stdout = Unpooled.buffer(); ByteBuf stderr = Unpooled.buffer(); docker.execStartCmd(execid).withDetach(false).exec(new ResultCallback<Frame>() { @Override public void close() { } @Override public void onStart(Closeable closeable) { LOG.info("DOCKER.exec({}:{}): Executing...", containerId, cmdString); } @Override public void onNext(Frame object) { if (StreamType.STDOUT == object.getStreamType()) { stdout.writeBytes(object.getPayload()); } else if (StreamType.STDERR == object.getStreamType()) { stderr.writeBytes(object.getPayload()); } } @Override public void onError(Throwable throwable) { future.completeExceptionally(throwable); } @Override public void onComplete() { LOG.info("DOCKER.exec({}:{}): Done", containerId, cmdString); future.complete(true); } }); future.join(); InspectExecResponse resp = docker.inspectExecCmd(execid).exec(); while (resp.isRunning()) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } resp = docker.inspectExecCmd(execid).exec(); } int retCode = resp.getExitCode(); byte[] stdoutBytes = new byte[stdout.readableBytes()]; stdout.readBytes(stdoutBytes); byte[] stderrBytes = new byte[stderr.readableBytes()]; stderr.readBytes(stderrBytes); ContainerExecResultBytes result = ContainerExecResultBytes.of(retCode, stdoutBytes, stderrBytes); LOG.info("DOCKER.exec({}:{}): completed with {}", containerId, cmdString, retCode); if (retCode != 0) { throw new ContainerExecException(cmdString, containerId, null); } return result; }
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);// w ww.j av a2s . c om 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:org.apache.bookkeeper.mledger.impl.OffloadPrefixTest.java
@Test public void testTrimOccursDuringOffload() throws Exception { CountDownLatch offloadStarted = new CountDownLatch(1); CompletableFuture<Void> blocker = new CompletableFuture<>(); MockLedgerOffloader offloader = new MockLedgerOffloader() { @Override//from w w w . ja va2s . c o m public CompletableFuture<Void> offload(ReadHandle ledger, UUID uuid, Map<String, String> extraMetadata) { offloadStarted.countDown(); return blocker.thenCompose((f) -> super.offload(ledger, uuid, extraMetadata)); } }; ManagedLedgerConfig config = new ManagedLedgerConfig(); config.setMaxEntriesPerLedger(10); config.setMinimumRolloverTime(0, TimeUnit.SECONDS); config.setRetentionTime(0, TimeUnit.MINUTES); config.setLedgerOffloader(offloader); ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("my_test_ledger", config); ManagedCursor cursor = ledger.openCursor("foobar"); // Create 3 ledgers, saving position at start of each for (int i = 0; i < 21; i++) { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); PositionImpl startOfSecondLedger = PositionImpl.get(ledger.getLedgersInfoAsList().get(1).getLedgerId(), 0); PositionImpl startOfThirdLedger = PositionImpl.get(ledger.getLedgersInfoAsList().get(2).getLedgerId(), 0); // trigger an offload which should offload the first two ledgers OffloadCallbackPromise cbPromise = new OffloadCallbackPromise(); ledger.asyncOffloadPrefix(startOfThirdLedger, cbPromise, null); offloadStarted.await(); // trim first ledger cursor.markDelete(startOfSecondLedger, new HashMap<>()); assertEventuallyTrue(() -> ledger.getLedgersInfoAsList().size() == 2); Assert.assertEquals( ledger.getLedgersInfoAsList().stream().filter(e -> e.getOffloadContext().getComplete()).count(), 0); // complete offloading blocker.complete(null); cbPromise.get(); Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); Assert.assertEquals( ledger.getLedgersInfoAsList().stream().filter(e -> e.getOffloadContext().getComplete()).count(), 1); Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); Assert.assertEquals(offloader.offloadedLedgers().size(), 1); Assert.assertTrue( offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); }
From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java
protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) { checkPermission(CLUSTER_WRITE);//from w w w. j a va2s .c om if (ep.equals(localEp)) { try { dispatchLocally(message); } catch (IOException e) { return Tools.exceptionalFuture(e); } return CompletableFuture.completedFuture(null); } CompletableFuture<Void> future = new CompletableFuture<>(); try { Connection connection = null; try { connection = channels.borrowObject(ep); connection.send(message, future); } finally { if (connection != null) { channels.returnObject(ep, connection); } } } catch (Exception e) { future.completeExceptionally(e); } return future; }
From source file:io.pravega.controller.server.SegmentHelper.java
public CompletableFuture<TxnStatus> commitTransaction(final String scope, final String stream, final int segmentNumber, final UUID txId, final HostControllerStore hostControllerStore, final ConnectionFactory clientCF) { final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore); final CompletableFuture<TxnStatus> result = new CompletableFuture<>(); final WireCommandType type = WireCommandType.COMMIT_TRANSACTION; final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override//from w w w . j a v a 2s. c o m public void connectionDropped() { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped)); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost)); } @Override public void transactionCommitted(WireCommands.TransactionCommitted transactionCommitted) { result.complete(TxnStatus.newBuilder().setStatus(TxnStatus.Status.SUCCESS).build()); } @Override public void transactionAborted(WireCommands.TransactionAborted transactionAborted) { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.PreconditionFailed)); } @Override public void processingFailure(Exception error) { result.completeExceptionally(error); } }; WireCommands.CommitTransaction request = new WireCommands.CommitTransaction(idGenerator.get(), Segment.getScopedName(scope, stream, segmentNumber), txId); sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri)); return result; }
From source file:org.apache.bookkeeper.stream.storage.impl.sc.ZkStorageContainerManagerTest.java
@Test public void testStartContainerOnFailures() throws Exception { scManager.close();/*from w w w. jav a 2s . c o m*/ long containerId = 11L; AtomicBoolean returnGoodContainer = new AtomicBoolean(false); CompletableFuture<StorageContainer> startFuture = new CompletableFuture<>(); StorageContainer goodSc = createStorageContainer(containerId, startFuture, FutureUtils.Void()); mockScFactory = (scId) -> { if (returnGoodContainer.get()) { return goodSc; } else { return createStorageContainer(scId, FutureUtils.exception(new Exception("Failed to start")), FutureUtils.Void()); } }; scRegistry = spy(new StorageContainerRegistryImpl(mockScFactory)); scManager = new ZkStorageContainerManager( myEndpoint, new StorageConfiguration(new CompositeConfiguration()) .setClusterControllerScheduleInterval(1, TimeUnit.SECONDS), clusterMetadataStore, scRegistry, NullStatsLogger.INSTANCE); // start the storage container manager scManager.start(); // update assignment map ClusterAssignmentData cad = ClusterAssignmentData.newBuilder() .putServers(NetUtils.endpointToString(myEndpoint), ServerAssignmentData.newBuilder().addContainers(containerId).build()) .build(); clusterMetadataStore.updateClusterAssignmentData(cad); // wait until container start is called and verify it is not started. verify(scRegistry, timeout(10000).atLeastOnce()).startStorageContainer(eq(containerId)); assertEquals(0, scManager.getLiveContainers().size()); // flip the flag to return a good container to simulate successful startup returnGoodContainer.set(true); FutureUtils.complete(startFuture, goodSc); // wait until container start is called again and the container is started MoreAsserts.assertUtil(ignored -> scManager.getLiveContainers().size() >= 1, () -> null); assertEquals(1, scManager.getLiveContainers().size()); assertTrue(scManager.getLiveContainers().containsKey(containerId)); }
From source file:org.apache.pulsar.client.impl.PulsarClientImpl.java
@Override public CompletableFuture<Consumer> subscribeAsync(final String topic, final String subscription, final ConsumerConfiguration conf) { if (state.get() != State.Open) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed")); }/*from w w w .java2 s . c o m*/ if (!DestinationName.isValid(topic)) { return FutureUtil .failedFuture(new PulsarClientException.InvalidTopicNameException("Invalid topic name")); } if (subscription == null) { return FutureUtil.failedFuture( new PulsarClientException.InvalidConfigurationException("Invalid subscription name")); } if (conf == null) { return FutureUtil.failedFuture( new PulsarClientException.InvalidConfigurationException("Consumer configuration undefined")); } CompletableFuture<Consumer> consumerSubscribedFuture = new CompletableFuture<>(); getPartitionedTopicMetadata(topic).thenAccept(metadata -> { if (log.isDebugEnabled()) { log.debug("[{}] Received topic metadata. partitions: {}", topic, metadata.partitions); } ConsumerBase consumer; // gets the next single threaded executor from the list of executors ExecutorService listenerThread = externalExecutorProvider.getExecutor(); if (metadata.partitions > 1) { consumer = new PartitionedConsumerImpl(PulsarClientImpl.this, topic, subscription, conf, metadata.partitions, listenerThread, consumerSubscribedFuture); } else { consumer = new ConsumerImpl(PulsarClientImpl.this, topic, subscription, conf, listenerThread, -1, consumerSubscribedFuture); } synchronized (consumers) { consumers.put(consumer, Boolean.TRUE); } }).exceptionally(ex -> { log.warn("[{}] Failed to get partitioned topic metadata", topic, ex); consumerSubscribedFuture.completeExceptionally(ex); return null; }); return consumerSubscribedFuture; }
From source file:org.onosproject.store.consistent.impl.DistributedLeadershipManager.java
@Override public CompletableFuture<Leadership> runForLeadership(String path) { log.debug("Running for leadership for topic: {}", path); CompletableFuture<Leadership> resultFuture = new CompletableFuture<>(); doRunForLeadership(path, resultFuture); return resultFuture; }