List of usage examples for java.util.concurrent CompletableFuture completeExceptionally
public boolean completeExceptionally(Throwable ex)
From source file:org.apache.pulsar.client.impl.BinaryProtoLookupService.java
private CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> findBroker( InetSocketAddress socketAddress, boolean authoritative, TopicName topicName) { CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> addressFuture = new CompletableFuture<>(); client.getCnxPool().getConnection(socketAddress).thenAccept(clientCnx -> { long requestId = client.newRequestId(); ByteBuf request = Commands.newLookup(topicName.toString(), authoritative, requestId); clientCnx.newLookup(request, requestId).thenAccept(lookupDataResult -> { URI uri = null;/*w ww. j a v a2 s . c om*/ try { // (1) build response broker-address if (useTls) { uri = new URI(lookupDataResult.brokerUrlTls); } else { String serviceUrl = lookupDataResult.brokerUrl; uri = new URI(serviceUrl); } InetSocketAddress responseBrokerAddress = InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort()); // (2) redirect to given address if response is: redirect if (lookupDataResult.redirect) { findBroker(responseBrokerAddress, lookupDataResult.authoritative, topicName) .thenAccept(addressPair -> { addressFuture.complete(addressPair); }).exceptionally((lookupException) -> { // lookup failed log.warn("[{}] lookup failed : {}", topicName.toString(), lookupException.getMessage(), lookupException); addressFuture.completeExceptionally(lookupException); return null; }); } else { // (3) received correct broker to connect if (lookupDataResult.proxyThroughServiceUrl) { // Connect through proxy addressFuture.complete(Pair.of(responseBrokerAddress, socketAddress)); } else { // Normal result with direct connection to broker addressFuture.complete(Pair.of(responseBrokerAddress, responseBrokerAddress)); } } } catch (Exception parseUrlException) { // Failed to parse url log.warn("[{}] invalid url {} : {}", topicName.toString(), uri, parseUrlException.getMessage(), parseUrlException); addressFuture.completeExceptionally(parseUrlException); } }).exceptionally((sendException) -> { // lookup failed log.warn("[{}] failed to send lookup request : {}", topicName.toString(), sendException.getMessage(), sendException instanceof ClosedChannelException ? null : sendException); addressFuture.completeExceptionally(sendException); return null; }); }).exceptionally(connectionException -> { addressFuture.completeExceptionally(connectionException); return null; }); return addressFuture; }
From source file:org.apache.pulsar.client.impl.BinaryProtoLookupService.java
private CompletableFuture<PartitionedTopicMetadata> getPartitionedTopicMetadata(InetSocketAddress socketAddress, TopicName topicName) {// w w w.j a v a 2s.co m CompletableFuture<PartitionedTopicMetadata> partitionFuture = new CompletableFuture<PartitionedTopicMetadata>(); client.getCnxPool().getConnection(socketAddress).thenAccept(clientCnx -> { long requestId = client.newRequestId(); ByteBuf request = Commands.newPartitionMetadataRequest(topicName.toString(), requestId); clientCnx.newLookup(request, requestId).thenAccept(lookupDataResult -> { try { partitionFuture.complete(new PartitionedTopicMetadata(lookupDataResult.partitions)); } catch (Exception e) { partitionFuture.completeExceptionally(new PulsarClientException.LookupException( format("Failed to parse partition-response redirect=%s , partitions with %s", lookupDataResult.redirect, lookupDataResult.partitions, e.getMessage()))); } }).exceptionally((e) -> { log.warn("[{}] failed to get Partitioned metadata : {}", topicName.toString(), e.getCause().getMessage(), e); partitionFuture.completeExceptionally(e); return null; }); }).exceptionally(connectionException -> { partitionFuture.completeExceptionally(connectionException); return null; }); return partitionFuture; }
From source file:org.apache.pulsar.client.impl.BinaryProtoLookupService.java
private void getTopicsUnderNamespace(InetSocketAddress socketAddress, NamespaceName namespace, Backoff backoff, AtomicLong remainingTime, CompletableFuture<List<String>> topicsFuture, Mode mode) { client.getCnxPool().getConnection(socketAddress).thenAccept(clientCnx -> { long requestId = client.newRequestId(); ByteBuf request = Commands.newGetTopicsOfNamespaceRequest(namespace.toString(), requestId, mode); clientCnx.newGetTopicsOfNamespace(request, requestId).thenAccept(topicsList -> { if (log.isDebugEnabled()) { log.debug("[namespace: {}] Success get topics list in request: {}", namespace.toString(), requestId);/*from w w w. j av a 2 s . com*/ } // do not keep partition part of topic name List<String> result = Lists.newArrayList(); topicsList.forEach(topic -> { String filtered = TopicName.get(topic).getPartitionedTopicName(); if (!result.contains(filtered)) { result.add(filtered); } }); topicsFuture.complete(result); }).exceptionally((e) -> { topicsFuture.completeExceptionally(e); return null; }); }).exceptionally((e) -> { long nextDelay = Math.min(backoff.next(), remainingTime.get()); if (nextDelay <= 0) { topicsFuture.completeExceptionally(new PulsarClientException.TimeoutException( "Could not getTopicsUnderNamespace within configured timeout.")); return null; } ((ScheduledExecutorService) executor).schedule(() -> { log.warn( "[namespace: {}] Could not get connection while getTopicsUnderNamespace -- Will try again in {} ms", namespace, nextDelay); remainingTime.addAndGet(-nextDelay); getTopicsUnderNamespace(socketAddress, namespace, backoff, remainingTime, topicsFuture, mode); }, nextDelay, TimeUnit.MILLISECONDS); return null; }); }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
@Override protected void handleLookupResponse(CommandLookupTopicResponse lookupResult) { if (log.isDebugEnabled()) { log.debug("Received Broker lookup response: {}", lookupResult.getResponse()); }// w w w. j a va 2 s .c o m long requestId = lookupResult.getRequestId(); CompletableFuture<LookupDataResult> requestFuture = getAndRemovePendingLookupRequest(requestId); if (requestFuture != null) { if (requestFuture.isCompletedExceptionally()) { if (log.isDebugEnabled()) { log.debug("{} Request {} already timed-out", ctx.channel(), lookupResult.getRequestId()); } return; } // Complete future with exception if : Result.response=fail/null if (!lookupResult.hasResponse() || CommandLookupTopicResponse.LookupType.Failed.equals(lookupResult.getResponse())) { if (lookupResult.hasError()) { checkServerError(lookupResult.getError(), lookupResult.getMessage()); requestFuture.completeExceptionally( getPulsarClientException(lookupResult.getError(), lookupResult.getMessage())); } else { requestFuture.completeExceptionally( new PulsarClientException.LookupException("Empty lookup response")); } } else { requestFuture.complete(new LookupDataResult(lookupResult)); } } else { log.warn("{} Received unknown request id from server: {}", ctx.channel(), lookupResult.getRequestId()); } }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
@Override protected void handlePartitionResponse(CommandPartitionedTopicMetadataResponse lookupResult) { if (log.isDebugEnabled()) { log.debug("Received Broker Partition response: {}", lookupResult.getPartitions()); }/*from w ww . j av a 2 s . c o m*/ long requestId = lookupResult.getRequestId(); CompletableFuture<LookupDataResult> requestFuture = getAndRemovePendingLookupRequest(requestId); if (requestFuture != null) { if (requestFuture.isCompletedExceptionally()) { if (log.isDebugEnabled()) { log.debug("{} Request {} already timed-out", ctx.channel(), lookupResult.getRequestId()); } return; } // Complete future with exception if : Result.response=fail/null if (!lookupResult.hasResponse() || CommandPartitionedTopicMetadataResponse.LookupType.Failed .equals(lookupResult.getResponse())) { if (lookupResult.hasError()) { checkServerError(lookupResult.getError(), lookupResult.getMessage()); requestFuture.completeExceptionally( getPulsarClientException(lookupResult.getError(), lookupResult.getMessage())); } else { requestFuture.completeExceptionally( new PulsarClientException.LookupException("Empty lookup response")); } } else { // return LookupDataResult when Result.response = success/redirect requestFuture.complete(new LookupDataResult(lookupResult.getPartitions())); } } else { log.warn("{} Received unknown request id from server: {}", ctx.channel(), lookupResult.getRequestId()); } }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
private void addPendingLookupRequests(long requestId, CompletableFuture<LookupDataResult> future) { pendingLookupRequests.put(requestId, future); eventLoopGroup.schedule(() -> {/*from w w w .j a v a 2 s .c o m*/ if (!future.isDone()) { future.completeExceptionally(new TimeoutException( requestId + " lookup request timedout after ms " + operationTimeoutMs)); } }, operationTimeoutMs, TimeUnit.MILLISECONDS); }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
private CompletableFuture<LookupDataResult> getAndRemovePendingLookupRequest(long requestId) { CompletableFuture<LookupDataResult> result = pendingLookupRequests.remove(requestId); if (result != null) { Pair<Long, Pair<ByteBuf, CompletableFuture<LookupDataResult>>> firstOneWaiting = waitingLookupRequests .poll();/* w ww . j a va 2 s . co m*/ if (firstOneWaiting != null) { // schedule a new lookup in. eventLoopGroup.submit(() -> { long newId = firstOneWaiting.getLeft(); CompletableFuture<LookupDataResult> newFuture = firstOneWaiting.getRight().getRight(); addPendingLookupRequests(newId, newFuture); ctx.writeAndFlush(firstOneWaiting.getRight().getLeft()).addListener(writeFuture -> { if (!writeFuture.isSuccess()) { log.warn("{} Failed to send request {} to broker: {}", ctx.channel(), newId, writeFuture.cause().getMessage()); getAndRemovePendingLookupRequest(newId); newFuture.completeExceptionally(writeFuture.cause()); } }); }); } else { pendingLookupRequestSemaphore.release(); } } return result; }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
@Override protected void handleError(CommandError error) { checkArgument(state == State.Ready); log.warn("{} Received error from server: {}", ctx.channel(), error.getMessage()); long requestId = error.getRequestId(); if (error.getError() == ServerError.ProducerBlockedQuotaExceededError) { log.warn("{} Producer creation has been blocked because backlog quota exceeded for producer topic", ctx.channel());//from ww w .j a va 2 s .c om } CompletableFuture<ProducerResponse> requestFuture = pendingRequests.remove(requestId); if (requestFuture != null) { requestFuture.completeExceptionally(getPulsarClientException(error.getError(), error.getMessage())); } else { log.warn("{} Received unknown request id from server: {}", ctx.channel(), error.getRequestId()); } }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
public CompletableFuture<LookupDataResult> newLookup(ByteBuf request, long requestId) { CompletableFuture<LookupDataResult> future = new CompletableFuture<>(); if (pendingLookupRequestSemaphore.tryAcquire()) { addPendingLookupRequests(requestId, future); ctx.writeAndFlush(request).addListener(writeFuture -> { if (!writeFuture.isSuccess()) { log.warn("{} Failed to send request {} to broker: {}", ctx.channel(), requestId, writeFuture.cause().getMessage()); getAndRemovePendingLookupRequest(requestId); future.completeExceptionally(writeFuture.cause()); }/*from w ww . j ava 2 s .com*/ }); } else { if (log.isDebugEnabled()) { log.debug("{} Failed to add lookup-request into pending queue", requestId); } if (!waitingLookupRequests.offer(Pair.of(requestId, Pair.of(request, future)))) { if (log.isDebugEnabled()) { log.debug("{} Failed to add lookup-request into waiting queue", requestId); } future.completeExceptionally(new PulsarClientException.TooManyRequestsException(String.format( "Requests number out of config: There are {%s} lookup requests outstanding and {%s} requests pending.", pendingLookupRequests.size(), waitingLookupRequests.size()))); } } return future; }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
public CompletableFuture<List<String>> newGetTopicsOfNamespace(ByteBuf request, long requestId) { CompletableFuture<List<String>> future = new CompletableFuture<>(); pendingGetTopicsRequests.put(requestId, future); ctx.writeAndFlush(request).addListener(writeFuture -> { if (!writeFuture.isSuccess()) { log.warn("{} Failed to send request {} to broker: {}", ctx.channel(), requestId, writeFuture.cause().getMessage()); pendingGetTopicsRequests.remove(requestId); future.completeExceptionally(writeFuture.cause()); }/*from w w w .j a v a 2 s. c om*/ }); return future; }