List of usage examples for java.util.concurrent CompletableFuture completeExceptionally
public boolean completeExceptionally(Throwable ex)
From source file:org.apache.pulsar.client.impl.ConsumerImpl.java
/** * Notify waiting asyncReceive request with the received message * * @param message/*from w ww . j a va2s . c om*/ */ void notifyPendingReceivedCallback(final Message<T> message, Exception exception) { if (pendingReceives.isEmpty()) { return; } // fetch receivedCallback from queue final CompletableFuture<Message<T>> receivedFuture = pendingReceives.poll(); if (receivedFuture == null) { return; } if (exception != null) { listenerExecutor.execute(() -> receivedFuture.completeExceptionally(exception)); return; } if (message == null) { IllegalStateException e = new IllegalStateException("received message can't be null"); listenerExecutor.execute(() -> receivedFuture.completeExceptionally(e)); return; } if (conf.getReceiverQueueSize() == 0) { // call interceptor and complete received callback interceptAndComplete(message, receivedFuture); return; } // increase permits for available message-queue messageProcessed(message); // call interceptor and complete received callback interceptAndComplete(message, receivedFuture); }
From source file:org.apache.pulsar.client.impl.ConsumerImpl.java
@Override public CompletableFuture<Void> seekAsync(MessageId messageId) { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); }//w ww .j av a 2 s.c om if (!isConnected()) { return FutureUtil.failedFuture(new PulsarClientException("Not connected to broker")); } final CompletableFuture<Void> seekFuture = new CompletableFuture<>(); long requestId = client.newRequestId(); MessageIdImpl msgId = (MessageIdImpl) messageId; ByteBuf seek = Commands.newSeek(consumerId, requestId, msgId.getLedgerId(), msgId.getEntryId()); ClientCnx cnx = cnx(); log.info("[{}][{}] Seek subscription to message id {}", topic, subscription, messageId); cnx.sendRequestWithId(seek, requestId).thenRun(() -> { log.info("[{}][{}] Successfully reset subscription to message id {}", topic, subscription, messageId); seekFuture.complete(null); }).exceptionally(e -> { log.error("[{}][{}] Failed to reset subscription: {}", topic, subscription, e.getCause().getMessage()); seekFuture.completeExceptionally(e.getCause()); return null; }); return seekFuture; }
From source file:org.apache.pulsar.client.impl.ConsumerImpl.java
public CompletableFuture<Boolean> hasMessageAvailableAsync() { final CompletableFuture<Boolean> booleanFuture = new CompletableFuture<>(); if (lastMessageIdInBroker.compareTo(lastDequeuedMessage) > 0 && ((MessageIdImpl) lastMessageIdInBroker).getEntryId() != -1) { booleanFuture.complete(true);/* ww w . java 2 s .co m*/ } else { getLastMessageIdAsync().thenAccept(messageId -> { lastMessageIdInBroker = messageId; if (lastMessageIdInBroker.compareTo(lastDequeuedMessage) > 0 && ((MessageIdImpl) lastMessageIdInBroker).getEntryId() != -1) { booleanFuture.complete(true); } else { booleanFuture.complete(false); } }).exceptionally(e -> { log.error("[{}][{}] Failed getLastMessageId command", topic, subscription); booleanFuture.completeExceptionally(e.getCause()); return null; }); } return booleanFuture; }
From source file:org.apache.pulsar.client.impl.ConsumerImpl.java
private void internalGetLastMessageIdAsync(final Backoff backoff, final AtomicLong remainingTime, CompletableFuture<MessageId> future) { ClientCnx cnx = cnx();// www. j a va 2 s . co m if (isConnected() && cnx != null) { if (!Commands.peerSupportsGetLastMessageId(cnx.getRemoteEndpointProtocolVersion())) { future.completeExceptionally(new PulsarClientException.NotSupportedException( "GetLastMessageId Not supported for ProtocolVersion: " + cnx.getRemoteEndpointProtocolVersion())); } long requestId = client.newRequestId(); ByteBuf getLastIdCmd = Commands.newGetLastMessageId(consumerId, requestId); log.info("[{}][{}] Get topic last message Id", topic, subscription); cnx.sendGetLastMessageId(getLastIdCmd, requestId).thenAccept((result) -> { log.info("[{}][{}] Successfully getLastMessageId {}:{}", topic, subscription, result.getLedgerId(), result.getEntryId()); future.complete( new MessageIdImpl(result.getLedgerId(), result.getEntryId(), result.getPartition())); }).exceptionally(e -> { log.error("[{}][{}] Failed getLastMessageId command", topic, subscription); future.completeExceptionally(e.getCause()); return null; }); } else { long nextDelay = Math.min(backoff.next(), remainingTime.get()); if (nextDelay <= 0) { future.completeExceptionally(new PulsarClientException.TimeoutException( "Could not getLastMessageId within configured timeout.")); return; } ((ScheduledExecutorService) listenerExecutor).schedule(() -> { log.warn("[{}] [{}] Could not get connection while getLastMessageId -- Will try again in {} ms", topic, getHandlerName(), nextDelay); remainingTime.addAndGet(-nextDelay); internalGetLastMessageIdAsync(backoff, remainingTime, future); }, nextDelay, TimeUnit.MILLISECONDS); } }
From source file:org.apache.pulsar.client.impl.HttpLookupService.java
@Override public CompletableFuture<List<String>> getTopicsUnderNamespace(NamespaceName namespace, Mode mode) { CompletableFuture<List<String>> future = new CompletableFuture<>(); String format = namespace.isV2() ? "admin/v2/namespaces/%s/topics?mode=%s" : "admin/namespaces/%s/destinations?mode=%s"; httpClient.get(String.format(format, namespace, mode.toString()), String[].class).thenAccept(topics -> { List<String> result = Lists.newArrayList(); // do not keep partition part of topic name Arrays.asList(topics).forEach(topic -> { String filtered = TopicName.get(topic).getPartitionedTopicName(); if (!result.contains(filtered)) { result.add(filtered);/*from w w w . j ava2 s .c o m*/ } }); future.complete(result); }).exceptionally(ex -> { log.warn("Failed to getTopicsUnderNamespace namespace: {}.", namespace, ex.getMessage()); future.completeExceptionally(ex); return null; }); return future; }
From source file:org.apache.pulsar.client.impl.HttpLookupService.java
@Override public CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName) { CompletableFuture<Optional<SchemaInfo>> future = new CompletableFuture<>(); String schemaName = topicName.getSchemaName(); String path = String.format("admin/v2/schemas/%s/schema", schemaName); httpClient.get(path, GetSchemaResponse.class).thenAccept(response -> { future.complete(Optional.of(SchemaInfoUtil.newSchemaInfo(schemaName, response))); }).exceptionally(ex -> {/*from w ww .j a v a2 s .c om*/ if (ex.getCause() instanceof NotFoundException) { future.complete(Optional.empty()); } else { log.warn("Failed to get schema for topic {} : {}", topicName, ex.getCause().getClass()); future.completeExceptionally(ex); } return null; }); return future; }
From source file:org.apache.pulsar.client.impl.PulsarClientImpl.java
@Override public CompletableFuture<Consumer> subscribeAsync(final String topic, final String subscription, final ConsumerConfiguration conf) { if (state.get() != State.Open) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed")); }/*from ww w . j a va 2 s. co m*/ if (!DestinationName.isValid(topic)) { return FutureUtil .failedFuture(new PulsarClientException.InvalidTopicNameException("Invalid topic name")); } if (subscription == null) { return FutureUtil.failedFuture( new PulsarClientException.InvalidConfigurationException("Invalid subscription name")); } if (conf == null) { return FutureUtil.failedFuture( new PulsarClientException.InvalidConfigurationException("Consumer configuration undefined")); } CompletableFuture<Consumer> consumerSubscribedFuture = new CompletableFuture<>(); getPartitionedTopicMetadata(topic).thenAccept(metadata -> { if (log.isDebugEnabled()) { log.debug("[{}] Received topic metadata. partitions: {}", topic, metadata.partitions); } ConsumerBase consumer; // gets the next single threaded executor from the list of executors ExecutorService listenerThread = externalExecutorProvider.getExecutor(); if (metadata.partitions > 1) { consumer = new PartitionedConsumerImpl(PulsarClientImpl.this, topic, subscription, conf, metadata.partitions, listenerThread, consumerSubscribedFuture); } else { consumer = new ConsumerImpl(PulsarClientImpl.this, topic, subscription, conf, listenerThread, -1, consumerSubscribedFuture); } synchronized (consumers) { consumers.put(consumer, Boolean.TRUE); } }).exceptionally(ex -> { log.warn("[{}] Failed to get partitioned topic metadata", topic, ex); consumerSubscribedFuture.completeExceptionally(ex); return null; }); return consumerSubscribedFuture; }
From source file:org.apache.pulsar.client.impl.PulsarClientImpl.java
@Override public CompletableFuture<Reader> createReaderAsync(String topic, MessageId startMessageId, ReaderConfiguration conf) {// ww w. j a va2 s. com if (state.get() != State.Open) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed")); } if (!DestinationName.isValid(topic)) { return FutureUtil .failedFuture(new PulsarClientException.InvalidTopicNameException("Invalid topic name")); } if (startMessageId == null) { return FutureUtil.failedFuture( new PulsarClientException.InvalidConfigurationException("Invalid startMessageId")); } if (conf == null) { return FutureUtil.failedFuture( new PulsarClientException.InvalidConfigurationException("Consumer configuration undefined")); } CompletableFuture<Reader> readerFuture = new CompletableFuture<>(); getPartitionedTopicMetadata(topic).thenAccept(metadata -> { if (log.isDebugEnabled()) { log.debug("[{}] Received topic metadata. partitions: {}", topic, metadata.partitions); } if (metadata.partitions > 1) { readerFuture.completeExceptionally( new PulsarClientException("Topic reader cannot be created on a partitioned topic")); return; } CompletableFuture<Consumer> consumerSubscribedFuture = new CompletableFuture<>(); // gets the next single threaded executor from the list of executors ExecutorService listenerThread = externalExecutorProvider.getExecutor(); ReaderImpl reader = new ReaderImpl(PulsarClientImpl.this, topic, startMessageId, conf, listenerThread, consumerSubscribedFuture); synchronized (consumers) { consumers.put(reader.getConsumer(), Boolean.TRUE); } consumerSubscribedFuture.thenRun(() -> { readerFuture.complete(reader); }).exceptionally(ex -> { log.warn("[{}] Failed to get create topic reader", topic, ex); readerFuture.completeExceptionally(ex); return null; }); }).exceptionally(ex -> { log.warn("[{}] Failed to get partitioned topic metadata", topic, ex); readerFuture.completeExceptionally(ex); return null; }); return readerFuture; }
From source file:org.apache.pulsar.compaction.CompactedTopicTest.java
/** * Build a compacted ledger, and return the id of the ledger, the position of the different * entries in the ledger, and a list of gaps, and the entry which should be returned after the gap. *//*w w w. jav a 2 s.c o m*/ private Triple<Long, List<Pair<MessageIdData, Long>>, List<Pair<MessageIdData, Long>>> buildCompactedLedger( BookKeeper bk, int count) throws Exception { LedgerHandle lh = bk.createLedger(1, 1, Compactor.COMPACTED_TOPIC_LEDGER_DIGEST_TYPE, Compactor.COMPACTED_TOPIC_LEDGER_PASSWORD); List<Pair<MessageIdData, Long>> positions = new ArrayList<>(); List<Pair<MessageIdData, Long>> idsInGaps = new ArrayList<>(); AtomicLong ledgerIds = new AtomicLong(10L); AtomicLong entryIds = new AtomicLong(0L); CompletableFuture.allOf(IntStream.range(0, count).mapToObj((i) -> { List<MessageIdData> idsInGap = new ArrayList<MessageIdData>(); if (r.nextInt(10) == 1) { long delta = r.nextInt(10) + 1; idsInGap.add(MessageIdData.newBuilder().setLedgerId(ledgerIds.get()).setEntryId(entryIds.get() + 1) .build()); ledgerIds.addAndGet(delta); entryIds.set(0); } long delta = r.nextInt(5); if (delta != 0) { idsInGap.add(MessageIdData.newBuilder().setLedgerId(ledgerIds.get()).setEntryId(entryIds.get() + 1) .build()); } MessageIdData id = MessageIdData.newBuilder().setLedgerId(ledgerIds.get()) .setEntryId(entryIds.addAndGet(delta + 1)).build(); @Cleanup RawMessage m = new RawMessageImpl(id, Unpooled.EMPTY_BUFFER); CompletableFuture<Void> f = new CompletableFuture<>(); ByteBuf buffer = m.serialize(); lh.asyncAddEntry(buffer, (rc, ledger, eid, ctx) -> { if (rc != BKException.Code.OK) { f.completeExceptionally(BKException.create(rc)); } else { positions.add(Pair.of(id, eid)); idsInGap.forEach((gid) -> idsInGaps.add(Pair.of(gid, eid))); f.complete(null); } }, null); return f; }).toArray(CompletableFuture[]::new)).get(); lh.close(); return Triple.of(lh.getId(), positions, idsInGaps); }
From source file:org.apache.pulsar.compaction.TwoPhaseCompactor.java
private CompletableFuture<PhaseOneResult> phaseOne(RawReader reader) { Map<String, MessageId> latestForKey = new HashMap<>(); CompletableFuture<PhaseOneResult> loopPromise = new CompletableFuture<>(); reader.getLastMessageIdAsync().whenComplete((lastMessageId, exception) -> { if (exception != null) { loopPromise.completeExceptionally(exception); } else {//ww w.j a va 2 s . c om log.info("Commencing phase one of compaction for {}, reading to {}", reader.getTopic(), lastMessageId); phaseOneLoop(reader, Optional.empty(), Optional.empty(), lastMessageId, latestForKey, loopPromise); } }); return loopPromise; }