List of usage examples for java.util.concurrent CompletableFuture completeExceptionally
public boolean completeExceptionally(Throwable ex)
From source file:org.apache.trafficcontrol.client.trafficops.TOSession.java
public CompletableFuture<Response.CollectionResponse> getDeliveryServices(final Map<String, ?> filterParams) { URI uri;/*from w w w . ja v a 2 s. c o m*/ try { uri = this.newUriBuilder("deliveryservices.json").setParameters(this.toPairs(filterParams)).build(); } catch (Throwable e) { final CompletableFuture<Response.CollectionResponse> f = new CompletableFuture<>(); f.completeExceptionally(e); return f; } LOG.debug("getDeliveryService url {}", uri); return ResponseFuture.builder(Response.CollectionResponse.class).setMethod(ResponseFuture.Method.GET) .setUri(uri).setSession(this.restClient()).build(); }
From source file:com.microsoft.azure.servicebus.samples.timetolive.TimeToLive.java
CompletableFuture pickUpAndFixDeadLetters(String connectionString, String queueName, IMessageSender resubmitSender, ExecutorService executorService) throws Exception { CompletableFuture running = new CompletableFuture(); QueueClient receiver = new QueueClient( new ConnectionStringBuilder(connectionString, "BasicQueue/$deadletterqueue"), ReceiveMode.PEEKLOCK); running.whenComplete((r, t) -> {//from w w w. ja v a2s.c om 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) { try { IMessage resubmitMessage = new Message(message.getBody()); System.out.printf( "\n\t\tFixing: \n\t\t\tMessageId = %s, \n\t\t\tSequenceNumber = %s, \n\t\t\tLabel = %s\n", message.getMessageId(), message.getSequenceNumber(), message.getLabel()); resubmitMessage.setMessageId(message.getMessageId()); resubmitMessage.setLabel(message.getLabel()); resubmitMessage.setContentType(message.getContentType()); resubmitMessage.setTimeToLive(Duration.ofMinutes(2)); resubmitSender.send(resubmitMessage); return receiver.completeAsync(message.getLockToken()); } catch (Exception e) { CompletableFuture failure = new CompletableFuture(); failure.completeExceptionally(e); return failure; } } // 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:com.android.tools.idea.diagnostics.crash.GoogleCrash.java
@Override @NotNull/*from w w w .j a va 2 s . c o m*/ public CompletableFuture<String> submit(@NotNull CrashReport report, boolean userReported) { if (!userReported) { // all non user reported crash events are rate limited on the client side if (!myRateLimiter.tryAcquire()) { CompletableFuture<String> f = new CompletableFuture<>(); f.completeExceptionally(new RuntimeException("Exceeded Quota of crashes that can be reported")); return f; } } Map<String, String> parameters = getDefaultParameters(); if (report.version != null) { parameters.put(KEY_VERSION, report.version); } parameters.put(KEY_PRODUCT_ID, report.productId); MultipartEntityBuilder builder = newMultipartEntityBuilderWithKv(parameters); report.serialize(builder); return submit(builder.build()); }
From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java
CompletableFuture PickUpAndFixDeadletters(String connectionString, String queueName, IMessageSender resubmitSender, ExecutorService executorService) throws Exception { CompletableFuture running = new CompletableFuture(); QueueClient receiver = new QueueClient( new ConnectionStringBuilder(connectionString, "BasicQueue/$deadletterqueue"), ReceiveMode.PEEKLOCK); running.whenComplete((r, t) -> {// w ww . ja v a 2 s . c o m 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) { try { IMessage resubmitMessage = new Message(message.getBody()); if (message.getLabel() != null && message.getLabel().contentEquals("Physicist")) { System.out.printf( "\n\t\tFixing: \n\t\t\tMessageId = %s, \n\t\t\tSequenceNumber = %s, \n\t\t\tLabel = %s\n", message.getMessageId(), message.getSequenceNumber(), message.getLabel()); resubmitMessage.setMessageId(message.getMessageId()); resubmitMessage.setLabel("Scientist"); resubmitMessage.setContentType(message.getContentType()); resubmitMessage.setTimeToLive(Duration.ofMinutes(2)); resubmitSender.send(resubmitMessage); } return receiver.completeAsync(message.getLockToken()); } catch (Exception e) { CompletableFuture failure = new CompletableFuture(); failure.completeExceptionally(e); return failure; } } // 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:io.pravega.client.segment.impl.SegmentOutputStreamFactoryImpl.java
@Override public SegmentOutputStream createOutputStreamForTransaction(Segment segment, UUID txId, Consumer<Segment> segmentSealedCallback, EventWriterConfig config) { CompletableFuture<String> name = new CompletableFuture<>(); FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override// w w w . j a v a 2 s . c om public void connectionDropped() { name.completeExceptionally(new ConnectionClosedException()); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { name.completeExceptionally(new NotImplementedException()); } @Override public void transactionInfo(WireCommands.TransactionInfo info) { name.complete(info.getTransactionName()); } @Override public void processingFailure(Exception error) { name.completeExceptionally(error); } }; val connectionFuture = controller.getEndpointForSegment(segment.getScopedName()) .thenCompose((PravegaNodeUri endpointForSegment) -> { return cf.establishConnection(endpointForSegment, replyProcessor); }); connectionFuture.thenAccept((ClientConnection connection) -> { try { connection.send(new WireCommands.GetTransactionInfo(1, segment.getScopedName(), txId)); } catch (ConnectionFailedException e) { throw new RuntimeException(e); } }).exceptionally(t -> { name.completeExceptionally(t); return null; }); name.whenComplete((s, e) -> { getAndHandleExceptions(connectionFuture, RuntimeException::new).close(); }); return new SegmentOutputStreamImpl(getAndHandleExceptions(name, RuntimeException::new), controller, cf, UUID.randomUUID(), segmentSealedCallback, getRetryFromConfig(config)); }
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. java 2 s . c o m 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:de.ii.xtraplatform.feature.provider.pgis.FeatureProviderPgis.java
private CompletionStage<Done> createFeatureStream(FeatureQuery query, FeatureConsumer featureConsumer) { Optional<SqlFeatureSource> featureSource = Optional.ofNullable(featureSources.get(query.getType())); if (!featureSource.isPresent()) { CompletableFuture<Done> promise = new CompletableFuture<>(); promise.completeExceptionally(new IllegalStateException("No features available for type")); return promise; }/*from ww w . ja v a 2 s .c om*/ return featureSource.get().runQuery(query, featureConsumer); }
From source file:org.eclipse.hono.service.AbstractApplication.java
/** * Starts up this application./* w w w . j av a 2 s .co m*/ * <p> * The start up process entails the following steps: * <ol> * <li>invoke <em>deployRequiredVerticles</em> to deploy the verticle(s) implementing the service's functionality</li> * <li>invoke <em>deployServiceVerticles</em> to deploy the protocol specific service endpoints</li> * <li>invoke <em>postRegisterServiceVerticles</em> to perform any additional post deployment steps</li> * <li>start the health check server</li> * </ol> * * @param args The command line arguments provided to the application. */ public void run(final ApplicationArguments args) { if (vertx == null) { throw new IllegalStateException("no Vert.x instance has been configured"); } else if (serviceFactories.isEmpty()) { throw new IllegalStateException("no service factory has been configured"); } healthCheckServer = new HealthCheckServer(vertx, config); final Future<Void> future = deployRequiredVerticles(config.getMaxInstances()) .compose(s -> deployServiceVerticles()).compose(s -> postRegisterServiceVerticles()) .compose(s -> healthCheckServer.start()); final CompletableFuture<Void> started = new CompletableFuture<>(); future.setHandler(result -> { if (result.failed()) { started.completeExceptionally(result.cause()); } else { started.complete(null); } }); final int startupTimeoutSeconds = config.getStartupTimeout(); try { log.debug("Waiting for {} seconds to start up", startupTimeoutSeconds); started.get(startupTimeoutSeconds, TimeUnit.SECONDS); } catch (TimeoutException e) { log.error("startup timed out after {} seconds, shutting down ...", startupTimeoutSeconds); shutdown(); } catch (InterruptedException e) { log.error("startup process has been interrupted, shutting down ..."); Thread.currentThread().interrupt(); shutdown(); } catch (ExecutionException e) { log.error("exception occurred during startup, shutting down ...", e); shutdown(); } }
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); }//w w w . jav a 2 s .c o 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.ikanow.aleph2.aleph2_rest_utils.DataStoreCrudService.java
@Override public CompletableFuture<Long> countObjectsBySpec(QueryComponent<FileDescriptor> spec) { try {// w ww . j a va2 s . co m return CompletableFuture.completedFuture( new DataStoreCursor(getFolderFilenames(output_directory, fileContext)).count()); } catch (IllegalArgumentException | IOException e) { final CompletableFuture<Long> fut = new CompletableFuture<Long>(); fut.completeExceptionally(e); return fut; } }