Example usage for java.util.concurrent CompletableFuture completeExceptionally

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

Introduction

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

Prototype

public boolean completeExceptionally(Throwable ex) 

Source Link

Document

If not already completed, causes invocations of #get() and related methods to throw the given exception.

Usage

From source file:io.pravega.client.stream.mock.MockController.java

private CompletableFuture<Void> abortTxSegment(UUID txId, Segment segment) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override/* ww w .j a  v a2  s  .com*/
        public void connectionDropped() {
            result.completeExceptionally(new ConnectionClosedException());
        }

        @Override
        public void wrongHost(WrongHost wrongHost) {
            result.completeExceptionally(new NotImplementedException());
        }

        @Override
        public void transactionCommitted(TransactionCommitted transactionCommitted) {
            result.completeExceptionally(new RuntimeException("Transaction already committed."));
        }

        @Override
        public void transactionAborted(TransactionAborted transactionAborted) {
            result.complete(null);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };
    sendRequestOverNewConnection(new AbortTransaction(idGenerator.get(), segment.getScopedName(), txId),
            replyProcessor, result);
    return result;
}

From source file:io.pravega.client.stream.mock.MockController.java

private boolean deleteSegment(String name, PravegaNodeUri uri) {
    CompletableFuture<Boolean> result = new CompletableFuture<>();
    FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override//from w  ww . ja  v a2s  .c  om
        public void connectionDropped() {
            result.completeExceptionally(new ConnectionClosedException());
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(new NotImplementedException());
        }

        @Override
        public void segmentDeleted(WireCommands.SegmentDeleted segmentDeleted) {
            result.complete(true);
        }

        @Override
        public void noSuchSegment(WireCommands.NoSuchSegment noSuchSegment) {
            result.complete(false);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };
    DeleteSegment command = new WireCommands.DeleteSegment(idGenerator.get(), name);
    sendRequestOverNewConnection(command, replyProcessor, result);
    return getAndHandleExceptions(result, RuntimeException::new);
}

From source file:io.pravega.client.stream.mock.MockController.java

private boolean createSegment(String name, PravegaNodeUri uri) {
    CompletableFuture<Boolean> result = new CompletableFuture<>();
    FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override// ww  w  .  ja va2  s .c  o  m
        public void connectionDropped() {
            result.completeExceptionally(new ConnectionClosedException());
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(new NotImplementedException());
        }

        @Override
        public void segmentAlreadyExists(WireCommands.SegmentAlreadyExists segmentAlreadyExists) {
            result.complete(false);
        }

        @Override
        public void segmentCreated(WireCommands.SegmentCreated segmentCreated) {
            result.complete(true);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };
    CreateSegment command = new WireCommands.CreateSegment(idGenerator.get(), name,
            WireCommands.CreateSegment.NO_SCALE, 0);
    sendRequestOverNewConnection(command, replyProcessor, result);
    return getAndHandleExceptions(result, RuntimeException::new);
}

From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessor.java

private CompletableFuture<Void> writeRequest(AutoScaleEvent event) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    try {/*from  w w w .  ja v  a  2s .  c  om*/
        CompletableFuture.runAsync(() -> {
            try {
                writer.get().writeEvent(event.getKey(), event).get();
                result.complete(null);
            } catch (InterruptedException | ExecutionException e) {
                log.error("error sending request to requeststream {}", e);
                result.completeExceptionally(e);
            }
        }, executor);
    } catch (RejectedExecutionException e) {
        log.error("our executor queue is full. failed to post scale event for {}/{}/{}", event.getScope(),
                event.getStream(), event.getSegmentNumber());
        result.completeExceptionally(e);
    }

    return result;
}

From source file:io.pravega.service.server.host.stat.AutoScaleProcessor.java

private CompletableFuture<Void> writeRequest(ScaleEvent event) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    try {// w  w  w  . j a  v  a2s.com
        CompletableFuture.runAsync(() -> {
            try {
                writer.get().writeEvent(event.getKey(), event).get();
                result.complete(null);
            } catch (InterruptedException | ExecutionException e) {
                log.error("error sending request to requeststream {}", e);
                result.completeExceptionally(e);
            }
        }, executor);
    } catch (RejectedExecutionException e) {
        log.error("our executor queue is full. failed to post scale event for {}/{}/{}", event.getScope(),
                event.getStream(), event.getSegmentNumber());
        result.completeExceptionally(e);
    }

    return result;
}

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

/**
 * Logic that runs when we come across an old test object
 * Check if source is done://from w  w  w.j av a 2s.  c  o m
 * A. Has timed out
 * B. Has created enough results
 * If either are true, copy over what test results there are (if any), mark as done
 * 
 * @param data_bucket
 * @param old_test_source
 * @param source_test_db
 * @return
 */
private CompletableFuture<Boolean> handleExistingTestSource(final DataBucketBean data_bucket,
        final TestQueueBean old_test_source, final ICrudService<TestQueueBean> source_test_db) {

    // if null==started_processing_on, then source is still being started in a different thread, so just ignore it:
    if (null == old_test_source.started_processing_on()) {
        return CompletableFuture.completedFuture(true);
    }

    //ENTRY: is old      
    final ProcessingTestSpecBean test_spec = old_test_source.test_params();
    //get v1 bucket
    return getTestOutputCrudService(data_bucket).map(v2_output_db -> {
        //got the output crud, check if time is up or we have enough test results
        //1: time is up by checking started_on+test_spec vs now
        final long max_run_time_secs = Optional.ofNullable(test_spec.max_run_time_secs()).orElse(60L);
        final long time_expires_on = old_test_source.started_processing_on().getTime()
                + (max_run_time_secs * 1000L);
        if (new Date().getTime() > time_expires_on) {
            _logger.debug("Test job: " + data_bucket.full_name() + " expired, need to retire");
            return retireTestJob(data_bucket, old_test_source, source_test_db, v2_output_db);
        }
        //2: test results, if we've hit the requested num results
        return checkTestHitRequestedNumResults(v2_output_db, data_bucket, test_spec, old_test_source,
                source_test_db);
    }).orElseGet(() -> {
        //we couldn't get the output crud, need to exit out
        //complete exceptionally so sync will throw an error
        _logger.error("Error getting test output crud");
        CompletableFuture<Boolean> db_error_future = new CompletableFuture<Boolean>();
        db_error_future.completeExceptionally(
                new Exception("Error retrieving output db for test job: " + data_bucket._id()));
        return db_error_future;
    });
}

From source file:io.pravega.controller.server.SegmentHelper.java

public CompletableFuture<UUID> createTransaction(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<UUID> result = new CompletableFuture<>();
    final WireCommandType type = WireCommandType.CREATE_TRANSACTION;
    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override/*from   w  w w  .  j  a v  a 2 s .  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 transactionCreated(WireCommands.TransactionCreated transactionCreated) {
            result.complete(txId);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };

    WireCommands.CreateTransaction request = new WireCommands.CreateTransaction(idGenerator.get(),
            Segment.getScopedName(scope, stream, segmentNumber), txId);
    sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri));
    return result;
}

From source file:io.pravega.controller.server.SegmentHelper.java

/**
 * This method sends segment sealed message for the specified segment.
 * It owns up the responsibility of retrying the operation on failures until success.
 *
 * @param scope               stream scope
 * @param stream              stream name
 * @param segmentNumber       number of segment to be sealed
 * @param hostControllerStore host controller store
 * @param clientCF            connection factory
 * @return void/*from   ww w  . java2s .  co m*/
 */
public CompletableFuture<Boolean> sealSegment(final String scope, final String stream, final int segmentNumber,
        final HostControllerStore hostControllerStore, final ConnectionFactory clientCF) {
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);
    final CompletableFuture<Boolean> result = new CompletableFuture<>();
    final WireCommandType type = WireCommandType.SEAL_SEGMENT;
    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override
        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 segmentSealed(WireCommands.SegmentSealed segmentSealed) {
            result.complete(true);
        }

        @Override
        public void segmentIsSealed(WireCommands.SegmentIsSealed segmentIsSealed) {
            result.complete(true);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };

    WireCommands.SealSegment request = new WireCommands.SealSegment(idGenerator.get(),
            Segment.getScopedName(scope, stream, segmentNumber));
    sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri));
    return result;
}

From source file:spring.travel.site.services.HttpClient.java

private <T> CompletableFuture<T> execute(Supplier<Request> requestSupplier, Consumer<Request> requestConsumer,
        ResponseMapper<T> responseMapper) {
    CompletableFuture<T> future = new CompletableFuture<>();
    try {//from w  w  w  .ja va 2s  .  co  m
        Request request = requestSupplier.get();
        requestConsumer.accept(request);
        asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<T>() {
            @Override
            public T onCompleted(Response response) throws Exception {
                T t = responseMapper.map(response);
                future.complete(t);
                return t;
            }

            @Override
            public void onThrowable(Throwable t) {
                future.completeExceptionally(t);
            }
        });
    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
    try {/*from ww  w .j a  va2  s .c  om*/
        ClientResponse response = apply(request);
        callback.response(response);
        return CompletableFuture.completedFuture(response);
    } catch (Throwable t) {
        callback.failure(t);
        CompletableFuture<Object> future = new CompletableFuture<>();
        future.completeExceptionally(t);
        return future;
    }
}