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:org.apache.pulsar.client.impl.ClientCnx.java

@Override
protected void handleGetSchemaResponse(CommandGetSchemaResponse commandGetSchemaResponse) {
    checkArgument(state == State.Ready);

    long requestId = commandGetSchemaResponse.getRequestId();

    CompletableFuture<Optional<SchemaInfo>> future = pendingGetSchemaRequests.remove(requestId);
    if (future == null) {
        log.warn("{} Received unknown request id from server: {}", ctx.channel(), requestId);
        return;/* w w w  .ja va2s. co m*/
    }

    if (commandGetSchemaResponse.hasErrorCode()) {
        // Request has failed
        ServerError rc = commandGetSchemaResponse.getErrorCode();
        if (rc == ServerError.TopicNotFound) {
            future.complete(Optional.empty());
        } else {
            future.completeExceptionally(
                    getPulsarClientException(rc, commandGetSchemaResponse.getErrorMessage()));
        }
    } else {
        future.complete(Optional.of(SchemaInfoUtil.newSchemaInfo(commandGetSchemaResponse.getSchema())));
    }
}

From source file:org.apache.pulsar.client.impl.ClientCnx.java

CompletableFuture<ProducerResponse> sendRequestWithId(ByteBuf cmd, long requestId) {
    CompletableFuture<ProducerResponse> future = new CompletableFuture<>();
    pendingRequests.put(requestId, future);
    ctx.writeAndFlush(cmd).addListener(writeFuture -> {
        if (!writeFuture.isSuccess()) {
            log.warn("{} Failed to send request to broker: {}", ctx.channel(),
                    writeFuture.cause().getMessage());
            pendingRequests.remove(requestId);
            future.completeExceptionally(writeFuture.cause());
        }// w  w  w .  j av  a2 s .  c om
    });
    requestTimeoutQueue.add(new RequestTime(System.currentTimeMillis(), requestId));
    return future;
}

From source file:org.apache.pulsar.client.impl.ClientCnx.java

public CompletableFuture<MessageIdData> sendGetLastMessageId(ByteBuf request, long requestId) {
    CompletableFuture<MessageIdData> future = new CompletableFuture<>();

    pendingGetLastMessageIdRequests.put(requestId, future);

    ctx.writeAndFlush(request).addListener(writeFuture -> {
        if (!writeFuture.isSuccess()) {
            log.warn("{} Failed to send GetLastMessageId request to broker: {}", ctx.channel(),
                    writeFuture.cause().getMessage());
            pendingGetLastMessageIdRequests.remove(requestId);
            future.completeExceptionally(writeFuture.cause());
        }//from  ww w .j  a va2  s  .  co  m
    });

    return future;
}

From source file:org.apache.pulsar.client.impl.ClientCnx.java

public CompletableFuture<Optional<SchemaInfo>> sendGetSchema(ByteBuf request, long requestId) {
    CompletableFuture<Optional<SchemaInfo>> future = new CompletableFuture<>();

    pendingGetSchemaRequests.put(requestId, future);

    ctx.writeAndFlush(request).addListener(writeFuture -> {
        if (!writeFuture.isSuccess()) {
            log.warn("{} Failed to send GetSchema request to broker: {}", ctx.channel(),
                    writeFuture.cause().getMessage());
            pendingGetLastMessageIdRequests.remove(requestId);
            future.completeExceptionally(writeFuture.cause());
        }/*from   ww w  .java 2s  .  c o m*/
    });

    return future;
}

From source file:org.apache.pulsar.client.impl.ClientCnx.java

private void checkRequestTimeout() {
    while (!requestTimeoutQueue.isEmpty()) {
        RequestTime request = requestTimeoutQueue.peek();
        if (request == null || (System.currentTimeMillis() - request.creationTimeMs) < operationTimeoutMs) {
            // if there is no request that is timed out then exit the loop
            break;
        }//from  www.j av a 2  s .c  om
        request = requestTimeoutQueue.poll();
        CompletableFuture<ProducerResponse> requestFuture = pendingRequests.remove(request.requestId);
        if (requestFuture != null && !requestFuture.isDone()
                && requestFuture.completeExceptionally(new TimeoutException(
                        request.requestId + " lookup request timedout after ms " + operationTimeoutMs))) {
            log.warn("{} request {} timed out after {} ms", ctx.channel(), request.requestId,
                    operationTimeoutMs);
        } else {
            // request is already completed successfully.
        }
    }
}

From source file:org.apache.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.  j  a v a 2s. c o m

    final CompletableFuture<ClientCnx> cnxFuture = new CompletableFuture<ClientCnx>();

    // Trigger async connect to broker
    bootstrap.connect(address).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            log.warn("Failed to open connection to {} : {}", address,
                    future.cause().getClass().getSimpleName());
            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:org.apache.pulsar.client.impl.ConsumerImpl.java

@Override
public CompletableFuture<Void> unsubscribeAsync() {
    if (getState() == State.Closing || getState() == State.Closed) {
        return FutureUtil
                .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed"));
    }//from   w  ww  .j av a2 s  . c  om
    final CompletableFuture<Void> unsubscribeFuture = new CompletableFuture<>();
    if (isConnected()) {
        setState(State.Closing);
        long requestId = client.newRequestId();
        ByteBuf unsubscribe = Commands.newUnsubscribe(consumerId, requestId);
        ClientCnx cnx = cnx();
        cnx.sendRequestWithId(unsubscribe, requestId).thenRun(() -> {
            cnx.removeConsumer(consumerId);
            unAckedMessageTracker.close();
            if (possibleSendToDeadLetterTopicMessages != null) {
                possibleSendToDeadLetterTopicMessages.clear();
            }
            client.cleanupConsumer(ConsumerImpl.this);
            log.info("[{}][{}] Successfully unsubscribed from topic", topic, subscription);
            setState(State.Closed);
            unsubscribeFuture.complete(null);
        }).exceptionally(e -> {
            log.error("[{}][{}] Failed to unsubscribe: {}", topic, subscription, e.getCause().getMessage());
            setState(State.Ready);
            unsubscribeFuture.completeExceptionally(e.getCause());
            return null;
        });
    } else {
        unsubscribeFuture.completeExceptionally(new PulsarClientException("Not connected to broker"));
    }
    return unsubscribeFuture;
}

From source file:org.apache.pulsar.client.impl.ConsumerImpl.java

@Override
protected CompletableFuture<Message<T>> internalReceiveAsync() {

    CompletableFuture<Message<T>> result = new CompletableFuture<>();
    Message<T> message = null;//www.ja v  a 2  s .c o m
    try {
        lock.writeLock().lock();
        message = incomingMessages.poll(0, TimeUnit.MILLISECONDS);
        if (message == null) {
            pendingReceives.add(result);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        result.completeExceptionally(e);
    } finally {
        lock.writeLock().unlock();
    }

    if (message != null) {
        trackMessage(message);
        Message<T> interceptMsg = beforeConsume(message);
        messageProcessed(interceptMsg);
        result.complete(interceptMsg);
    }

    return result;
}

From source file:org.apache.pulsar.client.impl.ConsumerImpl.java

@Override
public CompletableFuture<Void> closeAsync() {
    if (getState() == State.Closing || getState() == State.Closed) {
        unAckedMessageTracker.close();/* w w  w  .j  a  va2s. com*/
        if (possibleSendToDeadLetterTopicMessages != null) {
            possibleSendToDeadLetterTopicMessages.clear();
        }
        return CompletableFuture.completedFuture(null);
    }

    if (!isConnected()) {
        log.info("[{}] [{}] Closed Consumer (not connected)", topic, subscription);
        setState(State.Closed);
        unAckedMessageTracker.close();
        if (possibleSendToDeadLetterTopicMessages != null) {
            possibleSendToDeadLetterTopicMessages.clear();
        }
        client.cleanupConsumer(this);
        return CompletableFuture.completedFuture(null);
    }

    stats.getStatTimeout().ifPresent(Timeout::cancel);

    setState(State.Closing);

    acknowledgmentsGroupingTracker.close();

    long requestId = client.newRequestId();

    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    ClientCnx cnx = cnx();
    if (null == cnx) {
        cleanupAtClose(closeFuture);
    } else {
        ByteBuf cmd = Commands.newCloseConsumer(consumerId, requestId);
        cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
            cnx.removeConsumer(consumerId);
            if (exception == null || !cnx.ctx().channel().isActive()) {
                cleanupAtClose(closeFuture);
            } else {
                closeFuture.completeExceptionally(exception);
            }
            return null;
        });
    }

    return closeFuture;
}

From source file:org.apache.pulsar.client.impl.ConsumerImpl.java

private void failPendingReceive() {
    lock.readLock().lock();/*ww w  . jav  a 2  s  .  c om*/
    try {
        if (listenerExecutor != null && !listenerExecutor.isShutdown()) {
            while (!pendingReceives.isEmpty()) {
                CompletableFuture<Message<T>> receiveFuture = pendingReceives.poll();
                if (receiveFuture != null) {
                    receiveFuture.completeExceptionally(
                            new PulsarClientException.AlreadyClosedException("Consumer is already closed"));
                } else {
                    break;
                }
            }
        }
    } finally {
        lock.readLock().unlock();
    }
}