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.controller.server.SegmentHelper.java

private <ResultT> void sendRequestAsync(final WireCommand request, final ReplyProcessor replyProcessor,
        final CompletableFuture<ResultT> resultFuture, final ConnectionFactory connectionFactory,
        final PravegaNodeUri uri) {
    CompletableFuture<ClientConnection> connectionFuture = connectionFactory.establishConnection(uri,
            replyProcessor);/*from   www  .j  a  v  a  2s.  c om*/
    connectionFuture.whenComplete((connection, e) -> {
        if (connection == null) {
            resultFuture.completeExceptionally(new WireCommandFailedException(new ConnectionFailedException(e),
                    request.getType(), WireCommandFailedException.Reason.ConnectionFailed));
        } else {
            try {
                connection.send(request);
            } catch (ConnectionFailedException cfe) {
                throw new WireCommandFailedException(cfe, request.getType(),
                        WireCommandFailedException.Reason.ConnectionFailed);
            } catch (Exception e2) {
                throw new RuntimeException(e2);
            }
        }
    }).exceptionally(e -> {
        Throwable cause = ExceptionHelpers.getRealException(e);
        if (cause instanceof WireCommandFailedException) {
            resultFuture.completeExceptionally(cause);
        } else if (cause instanceof ConnectionFailedException) {
            resultFuture.completeExceptionally(new WireCommandFailedException(cause, request.getType(),
                    WireCommandFailedException.Reason.ConnectionFailed));
        } else {
            resultFuture.completeExceptionally(new RuntimeException(cause));
        }
        return null;
    });
    resultFuture.whenComplete((result, e) -> {
        connectionFuture.thenAccept(c -> c.close());
    });
}

From source file:co.runrightfast.vertx.demo.testHarness.jmx.DemoMXBeanImpl.java

private <A extends com.google.protobuf.Message> Handler<AsyncResult<Message<A>>> responseHandler(
        final CompletableFuture future, final Class<A> messageType) {
    return result -> {
        if (result.succeeded()) {
            future.complete(result.result().body());
        } else {//www  .  j  a  v  a2 s .  c o  m
            log.logp(SEVERE, getClass().getName(),
                    String.format("responseHandler.failure::%s", messageType.getName()), "request failed",
                    result.cause());
            future.completeExceptionally(result.cause());
        }
    };
}

From source file:net.data.technology.jraft.extensions.http.HttpRpcClient.java

@Override
public CompletableFuture<RaftResponseMessage> send(RaftRequestMessage request) {
    CompletableFuture<RaftResponseMessage> future = new CompletableFuture<RaftResponseMessage>();
    String payload = this.gson.toJson(request);
    HttpPost postRequest = new HttpPost(this.serverUrl);
    postRequest.setEntity(new StringEntity(payload, StandardCharsets.UTF_8));
    this.httpClient.execute(postRequest, new FutureCallback<HttpResponse>() {

        @Override//from  w  w w  .  java  2s.co  m
        public void completed(HttpResponse result) {
            if (result.getStatusLine().getStatusCode() != 200) {
                logger.info("receive an response error code "
                        + String.valueOf(result.getStatusLine().getStatusCode()) + " from server");
                future.completeExceptionally(new IOException("Service Error"));
            }

            try {
                InputStreamReader reader = new InputStreamReader(result.getEntity().getContent());
                RaftResponseMessage response = gson.fromJson(reader, RaftResponseMessage.class);
                future.complete(response);
            } catch (Throwable error) {
                logger.info("fails to parse the response from server due to errors", error);
                future.completeExceptionally(error);
            }
        }

        @Override
        public void failed(Exception ex) {
            future.completeExceptionally(ex);
        }

        @Override
        public void cancelled() {
            future.completeExceptionally(new IOException("request cancelled"));
        }
    });
    return future;
}

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

public CompletableFuture<Void> updatePolicy(String scope, String stream, ScalingPolicy policy,
        int segmentNumber, HostControllerStore hostControllerStore, ConnectionFactory clientCF) {
    final CompletableFuture<Void> result = new CompletableFuture<>();
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);

    final WireCommandType type = WireCommandType.UPDATE_SEGMENT_POLICY;
    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override//  www.j a  v  a2  s  .  co  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 segmentPolicyUpdated(WireCommands.SegmentPolicyUpdated policyUpdated) {
            result.complete(null);
        }

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

    Pair<Byte, Integer> extracted = extractFromPolicy(policy);

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

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

public CompletableFuture<Boolean> deleteSegment(final String scope, final String stream,
        final int segmentNumber, final HostControllerStore hostControllerStore,
        final ConnectionFactory clientCF) {
    final CompletableFuture<Boolean> result = new CompletableFuture<>();
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);

    final WireCommandType type = WireCommandType.DELETE_SEGMENT;

    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

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

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

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

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

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

public CompletableFuture<Boolean> createSegment(final String scope, final String stream,
        final int segmentNumber, final ScalingPolicy policy, final HostControllerStore hostControllerStore,
        final ConnectionFactory clientCF) {
    final CompletableFuture<Boolean> result = new CompletableFuture<>();
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);

    final WireCommandType type = WireCommandType.CREATE_SEGMENT;

    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override//from  w  w w  .j a v  a  2  s . c  om
        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 segmentAlreadyExists(WireCommands.SegmentAlreadyExists segmentAlreadyExists) {
            result.complete(true);
        }

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

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

    Pair<Byte, Integer> extracted = extractFromPolicy(policy);

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

From source file:co.runrightfast.vertx.core.application.RunRightFastVertxApplicationLauncherTest.java

private Handler<AsyncResult<Message<GetVerticleDeployments.Response>>> getVerticleDeploymentsResponseHandler(
        final CompletableFuture future) {
    return result -> {
        if (result.succeeded()) {
            log.logp(INFO, getClass().getName(), "test_vertx_default_options.success",
                    JsonUtils.toVertxJsonObject(ProtobufUtils.protobuMessageToJson(result.result().body()))
                            .encodePrettily());
            future.complete(result.result().body());
        } else {/*from ww w  .j av a2s .c om*/
            log.logp(SEVERE, getClass().getName(), "test_vertx_default_options.failure",
                    "get-verticle-deployments failed", result.cause());
            future.completeExceptionally(result.cause());
        }
    };
}

From source file:com.yahoo.pulsar.common.naming.NamespaceBundleFactory.java

public NamespaceBundleFactory(PulsarService pulsar, HashFunction hashFunc) {
    this.hashFunc = hashFunc;

    this.bundlesCache = Caffeine.newBuilder().buildAsync((NamespaceName namespace, Executor executor) -> {
        String path = AdminResource.joinPath(LOCAL_POLICIES_ROOT, namespace.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading cache with bundles for {}", namespace);
        }/*from   w  w  w.  ja v  a  2s.  co  m*/

        if (pulsar == null || pulsar.getConfigurationCache() == null) {
            return CompletableFuture.completedFuture(getBundles(namespace, null));
        }

        CompletableFuture<NamespaceBundles> future = new CompletableFuture<>();
        // Read the static bundle data from the policies
        pulsar.getLocalZkCacheService().policiesCache().getAsync(path).thenAccept(policies -> {
            // If no policies defined for namespace, assume 1 single bundle
            BundlesData bundlesData = policies.map(p -> p.bundles).orElse(null);
            NamespaceBundles namespaceBundles = getBundles(namespace, bundlesData);
            future.complete(namespaceBundles);
        }).exceptionally(ex -> {
            future.completeExceptionally(ex);
            return null;
        });
        return future;
    });

    if (pulsar != null && pulsar.getConfigurationCache() != null) {
        pulsar.getLocalZkCacheService().policiesCache().registerListener(this);
    }

    this.pulsar = pulsar;
}

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

private <T> void sendRequestOverNewConnection(WireCommand request, ReplyProcessor replyProcessor,
        CompletableFuture<T> resultFuture) {
    ClientConnection connection = getAndHandleExceptions(
            connectionFactory.establishConnection(new PravegaNodeUri(endpoint, port), replyProcessor),
            RuntimeException::new);
    resultFuture.whenComplete((result, e) -> {
        connection.close();//ww  w.j  a va 2  s  . c  o  m
    });
    try {
        connection.send(request);
    } catch (Exception e) {
        resultFuture.completeExceptionally(e);
    }
}

From source file:io.pravega.controller.server.eventProcessor.ScaleRequestHandler.java

/**
 * Scale tasks exceptions are absorbed.//from   w w  w .  j ava 2s .co m
 *
 * @param request   incoming request from request stream.
 * @param segments  segments to seal
 * @param newRanges new ranges for segments to create
 * @param context   operation context
 * @return CompletableFuture
 */
private CompletableFuture<Void> executeScaleTask(final ScaleEvent request, final ArrayList<Integer> segments,
        final ArrayList<AbstractMap.SimpleEntry<Double, Double>> newRanges, final OperationContext context) {
    CompletableFuture<Void> result = new CompletableFuture<>();

    streamMetadataTasks.scale(request.getScope(), request.getStream(), segments, newRanges,
            System.currentTimeMillis(), context).whenCompleteAsync((res, e) -> {
                if (e != null) {
                    log.warn("Scale failed for request {}/{}/{} with exception {}", request.getScope(),
                            request.getStream(), request.getSegmentNumber(), e);
                    Throwable cause = ExceptionHelpers.getRealException(e);
                    if (cause instanceof LockFailedException) {
                        result.completeExceptionally(cause);
                    } else {
                        result.completeExceptionally(e);
                    }
                } else {
                    // completed - either successfully or with pre-condition-failure. Clear markers on all scaled segments.
                    log.error("scale done for {}/{}/{}", request.getScope(), request.getStream(),
                            request.getSegmentNumber());
                    result.complete(null);

                    clearMarkers(request.getScope(), request.getStream(), segments, context);
                }
            }, executor);

    return result;
}