Example usage for java.util.concurrent CompletableFuture exceptionally

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

Introduction

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

Prototype

public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn) 

Source Link

Usage

From source file:org.kordamp.javatrove.example06.impl.GithubImplTest.java

@Test
public void failurePath() {
    // given:/*  w w w  . j  av a  2s  . com*/
    stubFor(get(urlEqualTo("/orgs/" + ORGANIZATION + "/repos"))
            .willReturn(aResponse().withStatus(500).withStatusMessage("Internal Error")));

    // when:
    CompletableFuture<Collection<Repository>> promise = github.repositories(ORGANIZATION);
    await().timeout(2, SECONDS).until(promise::isCompletedExceptionally, equalTo(true));

    // then:
    promise.exceptionally(throwable -> {
        assertThat(throwable.getMessage(), equalTo("Internal Error"));
        return null;
    });
    verify(getRequestedFor(urlEqualTo("/orgs/" + ORGANIZATION + "/repos")));
}

From source file:io.pravega.test.integration.selftest.Producer.java

/**
 * Executes one iteration of the Producer.
 * 1. Requests a new ProducerOperation from the DataSource.
 * 2. Executes it.//from   ww w .j a  v a 2s .  com
 * 3. Completes the ProducerOperation with either success or failure based on the outcome step #2.
 */
private CompletableFuture<Void> runOneIteration() {
    this.iterationCount.incrementAndGet();

    val futures = new ArrayList<CompletableFuture<Void>>();
    for (int i = 0; i < this.config.getProducerParallelism(); i++) {
        ProducerOperation op = this.dataSource.nextOperation();
        if (op == null) {
            // Nothing more to do.
            this.canContinue.set(false);
            break;
        }

        CompletableFuture<Void> result;
        try {
            CompletableFuture<Void> waitOn = op.getWaitOn();
            if (waitOn != null) {
                result = waitOn.exceptionally(ex -> null).thenComposeAsync(v -> executeOperation(op),
                        this.executorService);
            } else {
                result = executeOperation(op);
            }
        } catch (Throwable ex) {
            // Catch and handle sync errors.
            op.completed(-1);
            if (handleOperationError(ex, op)) {
                // Exception handled; skip this iteration since there's nothing more we can do.
                continue;
            } else {
                result = Futures.failedFuture(ex);
            }
        }

        futures.add(result.exceptionally(ex -> {
            // Catch and handle async errors.
            if (handleOperationError(ex, op)) {
                return null;
            }

            throw new CompletionException(ex);
        }));
    }

    return Futures.allOf(futures);
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_TestBuckets.java

/**
 * Logic that runs when we come across a new test object.
 * Kicks off a test by calling BucketTestService.test_bucket -> this typically calls CoreManagementService.test_bucket
 * Updates the status based on if the test_bucket started successfully
 * //from www  .j a v  a2s  .  c  o  m
 * @param data_bucket
 * @param new_test_source
 * @param bucket_test_service
 * @param source_test_db
 * @return
 */
private CompletableFuture<Boolean> handleNewTestSource(final DataBucketBean data_bucket,
        final TestQueueBean new_test_source, final BucketTestService bucket_test_service,
        final ICrudService<TestQueueBean> source_test_db) {
    //get the test params
    final ProcessingTestSpecBean test_spec = new_test_source.test_params();

    //try to test the bucket
    _logger.debug("Running bucket test");
    @SuppressWarnings("unchecked")
    final ICrudService<JsonNode> v1_output_db = _underlying_management_db.get()
            .getUnderlyingPlatformDriver(ICrudService.class, Optional.of("ingest." + data_bucket._id())).get();
    final CompletableFuture<Boolean> delete_datastore = v1_output_db.deleteDatastore(); //(this is done in a few other places, so just to be on the safe side here)
    final ManagementFuture<Boolean> test_res_future = bucket_test_service.test_bucket(_core_management_db.get(),
            data_bucket, test_spec);

    return delete_datastore.exceptionally(ex -> {
        _logger.error("Error trying to clear v1 output db before test run: ingest." + data_bucket._id(), ex);
        return false;
    }).thenCompose(y -> test_res_future.thenCompose(res -> {
        return test_res_future.getManagementResults().<Boolean>thenCompose(man_res -> {
            //return updateTestSourceStatus(new_test_source._id(), (res ? "in_progress" : "error"), source_test_db, Optional.of(new Date()), Optional.empty(), Optional.of(man_res.stream().map(
            return updateTestSourceStatus(new_test_source._id(),
                    (res ? TestStatus.in_progress : TestStatus.error), source_test_db, Optional.of(new Date()),
                    Optional.empty(), Optional.of(man_res.stream().map(msg -> {
                        return "[" + msg.date() + "] " + msg.source() + " (" + msg.command() + "): "
                                + (msg.success() ? "INFO" : "ERROR") + ": " + msg.message();
                    }).collect(Collectors.joining("\n"))));
        });
    }).exceptionally(t -> {
        updateTestSourceStatus(new_test_source._id(), TestStatus.error, source_test_db, Optional.of(new Date()),
                Optional.empty(), Optional.of(ErrorUtils.getLongForm("Error during test_bucket: {0}", t)))
                        .thenCompose(x -> {
                            if (!x)
                                _logger.error(
                                        "Had an error trying to update status of test object after having an error during test bucket, somethings gone horribly wrong");
                            return CompletableFuture.completedFuture(x); //this return doesn't matter
                        });
        return false;
    }));
}

From source file:com.microsoft.azure.servicebus.samples.receiveloop.ReceiveLoop.java

public void run(String connectionString) throws Exception {

    QueueClient sendClient;/*from  w w w  . j av  a 2 s .c o m*/
    IMessageReceiver receiver;
    CompletableFuture receiveTask;

    // Create a QueueClient instance using the connection string builder
    // We set the receive mode to "PeekLock", meaning the message is delivered
    // under a lock and must be acknowledged ("completed") to be removed from the queue

    sendClient = new QueueClient(new ConnectionStringBuilder(connectionString, "BasicQueue"),
            ReceiveMode.PEEKLOCK);
    this.sendMessagesAsync(sendClient).thenRunAsync(() -> sendClient.closeAsync());

    receiver = ClientFactory.createMessageReceiverFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue"), ReceiveMode.PEEKLOCK);
    receiveTask = this.receiveMessagesAsync(receiver);

    waitForEnter(10);

    receiveTask.cancel(true);
    receiver.close();

    CompletableFuture.allOf(receiveTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException((Throwable) t);
    })).join();

}

From source file:com.microsoft.azure.servicebus.samples.messagebrowse.MessageBrowse.java

public void run(String connectionString) throws Exception {

    QueueClient sendClient;//from  ww  w.  java2  s .com
    IMessageReceiver receiver;
    CompletableFuture receiveTask;

    // Create a QueueClient instance using the connection string builder
    // We set the receive mode to "PeekLock", meaning the message is delivered
    // under a lock and must be acknowledged ("completed") to be removed from the queue

    sendClient = new QueueClient(new ConnectionStringBuilder(connectionString, "BasicQueue"),
            ReceiveMode.PEEKLOCK);
    this.sendMessagesAsync(sendClient).thenRunAsync(() -> sendClient.closeAsync());

    receiver = ClientFactory.createMessageReceiverFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue"), ReceiveMode.PEEKLOCK);
    receiveTask = this.peekMessagesAsync(receiver);

    // wait for ENTER or 10 seconds elapsing
    waitForEnter(10);

    receiveTask.cancel(true);

    CompletableFuture.allOf(receiveTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException((Throwable) t);
    }), receiver.closeAsync()).join();
}

From source file:com.microsoft.azure.servicebus.samples.timetolive.TimeToLive.java

public void run(String connectionString) throws Exception {

    IMessageSender sendClient;/*  w w  w  .  j  a va  2  s  .  co  m*/
    CompletableFuture<Void> receiveTask;
    CompletableFuture<Void> fixUpTask;

    // send messages
    sendClient = ClientFactory.createMessageSenderFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue"));
    this.sendMessagesAsync(sendClient);

    // wait for all messages to expire
    Thread.sleep(15 * 1000);

    ExecutorService executorService = Executors.newCachedThreadPool();
    // start the receiver tasks and the fixup tasks
    receiveTask = this.receiveMessagesAsync(connectionString, "BasicQueue", executorService);
    fixUpTask = this.pickUpAndFixDeadLetters(connectionString, "BasicQueue", sendClient, executorService);

    // wait for ENTER or 10 seconds elapsing
    waitForEnter(10);

    // cancel the running tasks
    receiveTask.cancel(true);
    fixUpTask.cancel(true);

    // wait for the tasks to complete
    CompletableFuture.allOf(sendClient.closeAsync(), receiveTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException(t);
    }), fixUpTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException(t);
    })).join();

    executorService.shutdown();
}

From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java

public void run(String connectionString) throws Exception {

    CompletableFuture<Void> receiveTask;
    CompletableFuture<Void> fixUpTask;
    IMessageSender sendClient;//from  w  w  w  . j  a  v  a 2 s  . c  o  m

    sendClient = ClientFactory.createMessageSenderFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue"));

    // max delivery-count scenario
    this.sendMessagesAsync(sendClient, 1).join();
    this.exceedMaxDelivery(connectionString, "BasicQueue").join();

    // fix-up scenario
    this.sendMessagesAsync(sendClient, Integer.MAX_VALUE);
    ExecutorService executorService = Executors.newCachedThreadPool();
    receiveTask = this.receiveMessagesAsync(connectionString, "BasicQueue", executorService);
    fixUpTask = this.PickUpAndFixDeadletters(connectionString, "BasicQueue", sendClient, executorService);

    // wait for ENTER or 10 seconds elapsing
    waitForEnter(10);

    receiveTask.cancel(true);
    fixUpTask.cancel(true);

    CompletableFuture.allOf(sendClient.closeAsync(), receiveTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException((Throwable) t);
    }), fixUpTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException((Throwable) t);
    })).join();

    executorService.shutdown();
}

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

private CompletableFuture<Topic> createPersistentTopic(final String topic) throws RuntimeException {
    checkTopicNsOwnership(topic);//ww  w.  j av  a2 s.c  o m

    final long topicCreateTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    DestinationName destinationName = DestinationName.get(topic);
    if (!pulsar.getNamespaceService().isServiceUnitActive(destinationName)) {
        // namespace is being unloaded
        String msg = String.format("Namespace is being unloaded, cannot add topic %s", topic);
        log.warn(msg);
        throw new RuntimeException(new ServiceUnitNotReadyException(msg));
    }

    final CompletableFuture<Topic> topicFuture = new CompletableFuture<>();

    getManagedLedgerConfig(destinationName).thenAccept(config -> {
        // Once we have the configuration, we can proceed with the async open operation

        managedLedgerFactory.asyncOpen(destinationName.getPersistenceNamingEncoding(), config,
                new OpenLedgerCallback() {
                    @Override
                    public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                        PersistentTopic persistentTopic = new PersistentTopic(topic, ledger,
                                BrokerService.this);

                        CompletableFuture<Void> replicationFuture = persistentTopic.checkReplication();
                        replicationFuture.thenRun(() -> {
                            log.info("Created topic {}", topic);
                            long topicLoadLatencyMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime())
                                    - topicCreateTimeMs;
                            pulsarStats.recordTopicLoadTimeValue(topic, topicLoadLatencyMs);
                            addTopicToStatsMaps(destinationName, persistentTopic);
                            topicFuture.complete(persistentTopic);
                        });
                        replicationFuture.exceptionally((ex) -> {
                            log.warn("Replication check failed. Removing topic from topics list {}, {}", topic,
                                    ex);
                            persistentTopic.stopReplProducers().whenComplete((v, exception) -> {
                                topics.remove(topic, topicFuture);
                                topicFuture.completeExceptionally(ex);
                            });

                            return null;
                        });
                    }

                    @Override
                    public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                        log.warn("Failed to create topic {}", topic, exception);
                        topics.remove(topic, topicFuture);
                        topicFuture.completeExceptionally(new PersistenceException(exception));
                    }
                }, null);

    }).exceptionally((exception) -> {
        log.warn("[{}] Failed to get topic configuration: {}", topic, exception.getMessage(), exception);
        topics.remove(topic, topicFuture);
        topicFuture.completeExceptionally(exception);
        return null;
    });

    return topicFuture;
}

From source file:io.pravega.test.integration.selftest.Producer.java

/**
 * Executes the given operation.// w  w w . j a va  2  s .  c  om
 */
private CompletableFuture<Void> executeOperation(ProducerOperation operation) {
    CompletableFuture<Void> result;
    final AtomicLong startTime = new AtomicLong(TIME_PROVIDER.get());
    if (operation.getType() == ProducerOperationType.CREATE_TRANSACTION) {
        // Create the Transaction, then record it's name in the operation's result.
        StoreAdapter.Feature.Transaction.ensureSupported(this.store, "create transaction");
        startTime.set(TIME_PROVIDER.get());
        result = this.store.createTransaction(operation.getTarget(), this.config.getTimeout())
                .thenAccept(operation::setResult);
    } else if (operation.getType() == ProducerOperationType.MERGE_TRANSACTION) {
        // Merge the Transaction.
        StoreAdapter.Feature.Transaction.ensureSupported(this.store, "merge transaction");
        startTime.set(TIME_PROVIDER.get());
        result = this.store.mergeTransaction(operation.getTarget(), this.config.getTimeout());
    } else if (operation.getType() == ProducerOperationType.ABORT_TRANSACTION) {
        // Abort the Transaction.
        StoreAdapter.Feature.Transaction.ensureSupported(this.store, "abort transaction");
        startTime.set(TIME_PROVIDER.get());
        result = this.store.abortTransaction(operation.getTarget(), this.config.getTimeout());
    } else if (operation.getType() == ProducerOperationType.APPEND) {
        // Generate some random data, then append it.
        StoreAdapter.Feature.Append.ensureSupported(this.store, "append");
        Event event = this.dataSource.nextEvent(operation.getTarget(), this.id);
        operation.setLength(event.getSerialization().getLength());
        startTime.set(TIME_PROVIDER.get());
        result = this.store.append(operation.getTarget(), event, this.config.getTimeout());
    } else if (operation.getType() == ProducerOperationType.SEAL) {
        // Seal the target.
        StoreAdapter.Feature.Seal.ensureSupported(this.store, "seal");
        startTime.set(TIME_PROVIDER.get());
        result = this.store.seal(operation.getTarget(), this.config.getTimeout());
    } else {
        throw new IllegalArgumentException("Unsupported Operation Type: " + operation.getType());
    }

    return result.exceptionally(ex -> attemptReconcile(ex, operation)).thenRun(
            () -> operation.completed((TIME_PROVIDER.get() - startTime.get()) / AbstractTimer.NANOS_TO_MILLIS));
}

From source file:org.apache.pulsar.broker.service.BrokerService.java

private void createPersistentTopic(final String topic, CompletableFuture<Topic> topicFuture) {

    final long topicCreateTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    DestinationName destinationName = DestinationName.get(topic);
    if (!pulsar.getNamespaceService().isServiceUnitActive(destinationName)) {
        // namespace is being unloaded
        String msg = String.format("Namespace is being unloaded, cannot add topic %s", topic);
        log.warn(msg);/*from   w ww.ja v  a  2  s  .  com*/
        pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
        topicFuture.completeExceptionally(new ServiceUnitNotReadyException(msg));
        return;
    }

    getManagedLedgerConfig(destinationName).thenAccept(config -> {
        // Once we have the configuration, we can proceed with the async open operation

        managedLedgerFactory.asyncOpen(destinationName.getPersistenceNamingEncoding(), config,
                new OpenLedgerCallback() {
                    @Override
                    public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                        PersistentTopic persistentTopic = new PersistentTopic(topic, ledger,
                                BrokerService.this);

                        CompletableFuture<Void> replicationFuture = persistentTopic.checkReplication();
                        replicationFuture.thenRun(() -> {
                            log.info("Created topic {}", topic);
                            long topicLoadLatencyMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime())
                                    - topicCreateTimeMs;
                            pulsarStats.recordTopicLoadTimeValue(topic, topicLoadLatencyMs);
                            addTopicToStatsMaps(destinationName, persistentTopic);
                            topicFuture.complete(persistentTopic);
                        });
                        replicationFuture.exceptionally((ex) -> {
                            log.warn("Replication check failed. Removing topic from topics list {}, {}", topic,
                                    ex);
                            persistentTopic.stopReplProducers().whenComplete((v, exception) -> {
                                topics.remove(topic, topicFuture);
                                topicFuture.completeExceptionally(ex);
                            });

                            return null;
                        });
                    }

                    @Override
                    public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                        log.warn("Failed to create topic {}", topic, exception);
                        topics.remove(topic, topicFuture);
                        topicFuture.completeExceptionally(new PersistenceException(exception));
                    }
                }, null);

    }).exceptionally((exception) -> {
        log.warn("[{}] Failed to get topic configuration: {}", topic, exception.getMessage(), exception);
        // remove topic from topics-map in different thread to avoid possible deadlock if
        // createPersistentTopic-thread only tries to handle this future-result
        pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
        topicFuture.completeExceptionally(exception);
        return null;
    });
}