List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:io.sqp.client.impl.SqpConnectionImpl.java
@Override public synchronized PreparedStatement prepare(String query) { CompletableFuture<Void> future = new CompletableFuture<>(); String stmtId = generateNewStatementId(); PreparedStatementImpl stmt = new PreparedStatementImpl(this, _lobManager, stmtId, future); // well, it is pretty awkward that we return a prepared stmt from which we know that it will fail // TODO: fix that awkwardness if (!checkOpenAndNoErrors(future)) { return stmt; }//from w ww . ja v a 2 s.c om send(new PrepareQueryMessage(query, stmtId), new ConfirmationResponseHandler(future, MessageType.PrepareCompleteMessage, "waiting for a parse complete")); return stmt; }
From source file:org.onlab.nio.service.IOLoopMessaging.java
protected CompletableFuture<Void> sendAsync(Endpoint ep, DefaultMessage message) { CompletableFuture<Void> future = new CompletableFuture<>(); if (ep.equals(localEp)) { dispatchLocally(message);/* w w w . ja v a 2 s . co m*/ future.complete(null); return future; } DefaultMessageStream stream = null; try { stream = streams.borrowObject(ep); stream.write(message); future.complete(null); } catch (Exception e) { future.completeExceptionally(e); } finally { try { streams.returnObject(ep, stream); } catch (Exception e) { log.warn("Failed to return stream to pool"); } } return future; }
From source file:org.apache.bookkeeper.meta.MockLedgerManager.java
@Override public CompletableFuture<Versioned<LedgerMetadata>> writeLedgerMetadata(long ledgerId, LedgerMetadata metadata, Version currentVersion) {//from ww w . j a v a 2s. com CompletableFuture<Versioned<LedgerMetadata>> promise = new CompletableFuture<>(); preWriteHook.runHook(ledgerId, metadata).thenComposeAsync((ignore) -> { try { Versioned<LedgerMetadata> oldMetadata = readMetadata(ledgerId); if (oldMetadata == null) { return FutureUtils.exception(new BKException.BKNoSuchLedgerExistsException()); } else if (!oldMetadata.getVersion().equals(currentVersion)) { return FutureUtils.exception(new BKException.BKMetadataVersionException()); } else { LongVersion oldVersion = (LongVersion) oldMetadata.getVersion(); metadataMap.put(ledgerId, Pair.of(new LongVersion(oldVersion.getLongVersion() + 1), serDe.serialize(metadata))); Versioned<LedgerMetadata> readBack = readMetadata(ledgerId); return FutureUtils.value(readBack); } } catch (Exception e) { LOG.error("Error writing metadata", e); return FutureUtils.exception(e); } }, executor).whenComplete((res, ex) -> { if (ex != null) { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; executeCallback(() -> promise.completeExceptionally(cause)); } else { executeCallback(() -> promise.complete(res)); } }); return promise; }
From source file:org.apache.pulsar.io.kafka.connect.PulsarOffsetBackingStore.java
@Override public void start() { try {/*from ww w. j a v a 2s. co m*/ client = PulsarClient.builder().serviceUrl(serviceUrl).build(); log.info("Successfully created pulsar client to {}", serviceUrl); producer = client.newProducer(Schema.BYTES).topic(topic).create(); log.info("Successfully created producer to produce updates to topic {}", topic); reader = client.newReader(Schema.BYTES).topic(topic).startMessageId(MessageId.earliest).create(); log.info("Successfully created reader to replay updates from topic {}", topic); CompletableFuture<Void> endFuture = new CompletableFuture<>(); readToEnd(endFuture); endFuture.join(); } catch (PulsarClientException e) { log.error("Failed to create pulsar client to cluster at {}", serviceUrl, e); throw new RuntimeException("Failed to create pulsar client to cluster at " + serviceUrl, e); } }
From source file:com.devicehive.service.DeviceCommandService.java
public Pair<String, CompletableFuture<List<DeviceCommand>>> sendSubscribeRequest(final Set<String> devices, final Set<String> names, final Date timestamp, final BiConsumer<DeviceCommand, String> callback) throws InterruptedException { final String subscriptionId = UUID.randomUUID().toString(); Collection<CompletableFuture<Collection<DeviceCommand>>> futures = devices.stream() .map(device -> new CommandSubscribeRequest(subscriptionId, device, names, timestamp)) .map(subscribeRequest -> { CompletableFuture<Collection<DeviceCommand>> future = new CompletableFuture<>(); Consumer<Response> responseConsumer = response -> { String resAction = response.getBody().getAction(); if (resAction.equals(Action.COMMAND_SUBSCRIBE_RESPONSE.name())) { future.complete(response.getBody().cast(CommandSubscribeResponse.class).getCommands()); } else if (resAction.equals(Action.COMMAND_EVENT.name())) { callback.accept(response.getBody().cast(CommandEvent.class).getCommand(), subscriptionId); } else { logger.warn("Unknown action received from backend {}", resAction); }//from w w w .ja v a2 s . com }; Request request = Request.newBuilder().withBody(subscribeRequest) .withPartitionKey(subscribeRequest.getDevice()).withSingleReply(false).build(); rpcClient.call(request, responseConsumer); return future; }).collect(Collectors.toList()); CompletableFuture<List<DeviceCommand>> future = CompletableFuture .allOf(futures.toArray(new CompletableFuture[futures.size()])).thenApply(v -> futures.stream() .map(CompletableFuture::join).flatMap(Collection::stream).collect(Collectors.toList())); return Pair.of(subscriptionId, future); }
From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java
private CompletableFuture<ClientCnx> createConnection(InetSocketAddress address, int connectionKey) { if (log.isDebugEnabled()) { log.debug("Connection for {} not found in cache", address); }//from w w w.j a va 2 s .co m final CompletableFuture<ClientCnx> cnxFuture = new CompletableFuture<ClientCnx>(); // Trigger async connect to broker bootstrap.connect(address).addListener((ChannelFuture future) -> { if (!future.isSuccess()) { cnxFuture.completeExceptionally(new PulsarClientException(future.cause())); cleanupConnection(address, connectionKey, cnxFuture); return; } log.info("[{}] Connected to server", future.channel()); future.channel().closeFuture().addListener(v -> { // Remove connection from pool when it gets closed if (log.isDebugEnabled()) { log.debug("Removing closed connection from pool: {}", v); } cleanupConnection(address, connectionKey, cnxFuture); }); // We are connected to broker, but need to wait until the connect/connected handshake is // complete final ClientCnx cnx = (ClientCnx) future.channel().pipeline().get("handler"); if (!future.channel().isActive() || cnx == null) { if (log.isDebugEnabled()) { log.debug("[{}] Connection was already closed by the time we got notified", future.channel()); } cnxFuture.completeExceptionally(new ChannelException("Connection already closed")); return; } cnx.connectionFuture().thenRun(() -> { if (log.isDebugEnabled()) { log.debug("[{}] Connection handshake completed", cnx.channel()); } cnxFuture.complete(cnx); }).exceptionally(exception -> { log.warn("[{}] Connection handshake failed: {}", cnx.channel(), exception.getMessage()); cnxFuture.completeExceptionally(exception); cleanupConnection(address, connectionKey, cnxFuture); cnx.ctx().close(); return null; }); }); return cnxFuture; }
From source file:com.devicehive.rpcclient.RpcClientActionTest.java
@Test public void testListUserAction() throws Exception { ListUserRequest listUserRequest = new ListUserRequest(); listUserRequest.setLogin(UUID.randomUUID().toString()); // nonexistent login Request request = Request.newBuilder().withBody(listUserRequest).build(); CompletableFuture<Response> future = new CompletableFuture<>(); client.call(request, future::complete); Response response = future.get(10, TimeUnit.SECONDS); ListUserResponse responseBody = (ListUserResponse) response.getBody(); assertNotNull(responseBody.getUsers().isEmpty()); }
From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java
CompletableFuture receiveMessagesAsync(String connectionString, String queueName, ExecutorService executorService) throws Exception { CompletableFuture running = new CompletableFuture(); QueueClient receiver = new QueueClient(new ConnectionStringBuilder(connectionString, "BasicQueue"), ReceiveMode.PEEKLOCK);/*from w ww.j a va 2 s . com*/ running.whenComplete((r, t) -> { try { receiver.close(); } catch (ServiceBusException e) { System.out.printf(e.getMessage()); } }); // register the RegisterMessageHandler callback receiver.registerMessageHandler(new IMessageHandler() { // callback invoked when the message handler loop has obtained a message public CompletableFuture<Void> onMessageAsync(IMessage message) { // receives message is passed to callback if (message.getLabel() != null && message.getContentType() != null && message.getLabel().contentEquals("Scientist") && message.getContentType().contentEquals("application/json")) { byte[] body = message.getBody(); Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class); System.out.printf( "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s," + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\", \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n", message.getMessageId(), message.getSequenceNumber(), message.getEnqueuedTimeUtc(), message.getExpiresAtUtc(), message.getContentType(), scientist != null ? scientist.get("firstName") : "", scientist != null ? scientist.get("name") : ""); } else { return receiver.deadLetterAsync(message.getLockToken()); } return receiver.completeAsync(message.getLockToken()); } // callback invoked when the message handler has an exception to report public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) { System.out.printf(exceptionPhase + "-" + throwable.getMessage()); } }, // 1 concurrent call, messages are auto-completed, auto-renew duration new MessageHandlerOptions(1, false, Duration.ofMinutes(1)), executorService); return running; }
From source file:org.pentaho.di.ui.repo.controller.RepositoryConnectController.java
public String createConnection() { CompletableFuture<String> future = new CompletableFuture<>(); spoonSupplier.get().getShell().getDisplay().asyncExec(() -> { DatabaseDialog databaseDialog = new DatabaseDialog(spoonSupplier.get().getShell(), new DatabaseMeta()); databaseDialog.open();//from w w w . j a v a2s .co m DatabaseMeta databaseMeta = databaseDialog.getDatabaseMeta(); if (databaseMeta != null) { if (!isDatabaseWithNameExist(databaseMeta, true)) { addDatabase(databaseMeta); future.complete(databaseMeta.getName()); } else { DatabaseDialog.showDatabaseExistsDialog(spoonSupplier.get().getShell(), databaseMeta); } } future.complete("None"); }); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("name", future.get()); return jsonObject.toJSONString(); } catch (Exception e) { jsonObject.put("name", "None"); return jsonObject.toJSONString(); } }
From source file:org.apache.pulsar.client.impl.HttpLookupService.java
@Override public CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName) { CompletableFuture<Optional<SchemaInfo>> future = new CompletableFuture<>(); String schemaName = topicName.getSchemaName(); String path = String.format("admin/v2/schemas/%s/schema", schemaName); httpClient.get(path, GetSchemaResponse.class).thenAccept(response -> { future.complete(Optional.of(SchemaInfoUtil.newSchemaInfo(schemaName, response))); }).exceptionally(ex -> {/*from www . j a v a2 s . c o m*/ if (ex.getCause() instanceof NotFoundException) { future.complete(Optional.empty()); } else { log.warn("Failed to get schema for topic {} : {}", topicName, ex.getCause().getClass()); future.completeExceptionally(ex); } return null; }); return future; }