List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
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);//from w w w . j a va 2 s . c o 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.hadoop.hbase.client.RawAsyncHBaseAdmin.java
private CompletableFuture<Void> compactRegion(byte[] regionName, byte[] columnFamily, boolean major) { CompletableFuture<Void> future = new CompletableFuture<>(); addListener(getRegionLocation(regionName), (location, err) -> { if (err != null) { future.completeExceptionally(err); return; }/*from w ww .j a v a 2 s. c o m*/ ServerName serverName = location.getServerName(); if (serverName == null) { future.completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName))); return; } addListener(compact(location.getServerName(), location.getRegion(), major, columnFamily), (ret, err2) -> { if (err2 != null) { future.completeExceptionally(err2); } else { future.complete(ret); } }); }); return future; }
From source file:org.apache.pulsar.client.impl.ConsumerImpl.java
CompletableFuture<MessageId> getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); }/* w w w . ja v a2 s. com*/ AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0, TimeUnit.MILLISECONDS); CompletableFuture<MessageId> getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; }
From source file:org.apache.pulsar.broker.admin.impl.PersistentTopicsBase.java
public static CompletableFuture<PartitionedTopicMetadata> getPartitionedTopicMetadata(PulsarService pulsar, String clientAppId, String originalPrincipal, AuthenticationDataSource authenticationData, TopicName topicName) {/* w w w.j a v a 2 s .c o m*/ CompletableFuture<PartitionedTopicMetadata> metadataFuture = new CompletableFuture<>(); try { // (1) authorize client try { checkAuthorization(pulsar, topicName, clientAppId, authenticationData); } catch (RestException e) { try { validateAdminAccessForTenant(pulsar, clientAppId, originalPrincipal, topicName.getTenant()); } catch (RestException authException) { log.warn("Failed to authorize {} on cluster {}", clientAppId, topicName.toString()); throw new PulsarClientException( String.format("Authorization failed %s on topic %s with error %s", clientAppId, topicName.toString(), authException.getMessage())); } } catch (Exception ex) { // throw without wrapping to PulsarClientException that considers: unknown error marked as internal // server error log.warn("Failed to authorize {} on cluster {} with unexpected exception {}", clientAppId, topicName.toString(), ex.getMessage(), ex); throw ex; } String path = path(PARTITIONED_TOPIC_PATH_ZNODE, topicName.getNamespace(), topicName.getDomain().toString(), topicName.getEncodedLocalName()); // validates global-namespace contains local/peer cluster: if peer/local cluster present then lookup can // serve/redirect request else fail partitioned-metadata-request so, client fails while creating // producer/consumer checkLocalOrGetPeerReplicationCluster(pulsar, topicName.getNamespaceObject()) .thenCompose(res -> fetchPartitionedTopicMetadataAsync(pulsar, path)).thenAccept(metadata -> { if (log.isDebugEnabled()) { log.debug("[{}] Total number of partitions for topic {} is {}", clientAppId, topicName, metadata.partitions); } metadataFuture.complete(metadata); }).exceptionally(ex -> { metadataFuture.completeExceptionally(ex.getCause()); return null; }); } catch (Exception ex) { metadataFuture.completeExceptionally(ex); } return metadataFuture; }
From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java
/** * List all region locations for the specific table. */// ww w . j av a 2s . c om private CompletableFuture<List<HRegionLocation>> getTableHRegionLocations(TableName tableName) { if (TableName.META_TABLE_NAME.equals(tableName)) { CompletableFuture<List<HRegionLocation>> future = new CompletableFuture<>(); // For meta table, we use zk to fetch all locations. AsyncRegistry registry = AsyncRegistryFactory.getRegistry(connection.getConfiguration()); addListener(registry.getMetaRegionLocation(), (metaRegions, err) -> { if (err != null) { future.completeExceptionally(err); } else if (metaRegions == null || metaRegions.isEmpty() || metaRegions.getDefaultRegionLocation() == null) { future.completeExceptionally(new IOException("meta region does not found")); } else { future.complete(Collections.singletonList(metaRegions.getDefaultRegionLocation())); } // close the registry. IOUtils.closeQuietly(registry); }); return future; } else { // For non-meta table, we fetch all locations by scanning hbase:meta table return AsyncMetaTableAccessor.getTableHRegionLocations(metaTable, Optional.of(tableName)); } }
From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java
/** * Compact column family of a table, Asynchronous operation even if CompletableFuture.get() *///from ww w . j a va2 s.co m private CompletableFuture<Void> compact(TableName tableName, byte[] columnFamily, boolean major, CompactType compactType) { CompletableFuture<Void> future = new CompletableFuture<>(); switch (compactType) { case MOB: addListener(connection.registry.getMasterAddress(), (serverName, err) -> { if (err != null) { future.completeExceptionally(err); return; } RegionInfo regionInfo = RegionInfo.createMobRegionInfo(tableName); addListener(compact(serverName, regionInfo, major, columnFamily), (ret, err2) -> { if (err2 != null) { future.completeExceptionally(err2); } else { future.complete(ret); } }); }); break; case NORMAL: addListener(getTableHRegionLocations(tableName), (locations, err) -> { if (err != null) { future.completeExceptionally(err); return; } if (locations == null || locations.isEmpty()) { future.completeExceptionally(new TableNotFoundException(tableName)); } CompletableFuture<?>[] compactFutures = locations.stream().filter(l -> l.getRegion() != null) .filter(l -> !l.getRegion().isOffline()).filter(l -> l.getServerName() != null) .map(l -> compact(l.getServerName(), l.getRegion(), major, columnFamily)) .toArray(CompletableFuture<?>[]::new); // future complete unless all of the compact futures are completed. addListener(CompletableFuture.allOf(compactFutures), (ret, err2) -> { if (err2 != null) { future.completeExceptionally(err2); } else { future.complete(ret); } }); }); break; default: throw new IllegalArgumentException("Unknown compactType: " + compactType); } return future; }
From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.java
CompletableFuture<ReadHandle> getLedgerHandle(long ledgerId) { CompletableFuture<ReadHandle> ledgerHandle = ledgerCache.get(ledgerId); if (ledgerHandle != null) { return ledgerHandle; }// w ww . j a v a2 s . co m // If not present try again and create if necessary return ledgerCache.computeIfAbsent(ledgerId, lid -> { // Open the ledger for reading if it was not already opened if (log.isDebugEnabled()) { log.debug("[{}] Asynchronously opening ledger {} for read", name, ledgerId); } mbean.startDataLedgerOpenOp(); CompletableFuture<ReadHandle> promise = new CompletableFuture<>(); LedgerInfo info = ledgers.get(ledgerId); CompletableFuture<ReadHandle> openFuture = new CompletableFuture<>(); if (info != null && info.hasOffloadContext() && info.getOffloadContext().getComplete()) { UUID uid = new UUID(info.getOffloadContext().getUidMsb(), info.getOffloadContext().getUidLsb()); // TODO: improve this to load ledger offloader by driver name recorded in metadata openFuture = config.getLedgerOffloader().readOffloaded(ledgerId, uid, OffloadUtils.getOffloadDriverMetadata(info)); } else { openFuture = bookKeeper.newOpenLedgerOp().withRecovery(!isReadOnly()).withLedgerId(ledgerId) .withDigestType(config.getDigestType()).withPassword(config.getPassword()).execute(); } openFuture.whenCompleteAsync((res, ex) -> { mbean.endDataLedgerOpenOp(); if (ex != null) { ledgerCache.remove(ledgerId, promise); promise.completeExceptionally(createManagedLedgerException(ex)); } else { if (log.isDebugEnabled()) { log.debug("[{}] Successfully opened ledger {} for reading", name, ledgerId); } promise.complete(res); } }, executor.chooseThread(name)); return promise; }); }
From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java
private CompletableFuture<TableName> checkRegionsAndGetTableName(byte[][] encodedRegionNames) { AtomicReference<TableName> tableNameRef = new AtomicReference<>(); CompletableFuture<TableName> future = new CompletableFuture<>(); for (byte[] encodedRegionName : encodedRegionNames) { checkAndGetTableName(encodedRegionName, tableNameRef, future); }/* w ww . ja v a2 s. c om*/ return future; }
From source file:org.apache.pulsar.broker.admin.impl.PersistentTopicsBase.java
private CompletableFuture<Void> updatePartitionedTopic(TopicName topicName, int numPartitions) { final String path = ZkAdminPaths.partitionedTopicPath(topicName); CompletableFuture<Void> updatePartition = new CompletableFuture<>(); createSubscriptions(topicName, numPartitions).thenAccept(res -> { try {//from www.ja v a2s . c o m byte[] data = jsonMapper().writeValueAsBytes(new PartitionedTopicMetadata(numPartitions)); globalZk().setData(path, data, -1, (rc, path1, ctx, stat) -> { if (rc == KeeperException.Code.OK.intValue()) { updatePartition.complete(null); } else { updatePartition.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), "failed to create update partitions")); } }, null); } catch (Exception e) { updatePartition.completeExceptionally(e); } }).exceptionally(ex -> { updatePartition.completeExceptionally(ex); return null; }); return updatePartition; }
From source file:org.apache.pulsar.broker.admin.impl.PersistentTopicsBase.java
/** * It creates subscriptions for new partitions of existing partitioned-topics * * @param topicName//from w w w .j a v a 2 s . c om * : topic-name: persistent://prop/cluster/ns/topic * @param numPartitions * : number partitions for the topics */ private CompletableFuture<Void> createSubscriptions(TopicName topicName, int numPartitions) { String path = path(PARTITIONED_TOPIC_PATH_ZNODE, topicName.getPersistenceNamingEncoding()); CompletableFuture<Void> result = new CompletableFuture<>(); fetchPartitionedTopicMetadataAsync(pulsar(), path).thenAccept(partitionMetadata -> { if (partitionMetadata.partitions <= 1) { result.completeExceptionally(new RestException(Status.CONFLICT, "Topic is not partitioned topic")); return; } if (partitionMetadata.partitions >= numPartitions) { result.completeExceptionally(new RestException(Status.CONFLICT, "number of partitions must be more than existing " + partitionMetadata.partitions)); return; } PulsarAdmin admin; try { admin = pulsar().getAdminClient(); } catch (PulsarServerException e1) { result.completeExceptionally(e1); return; } admin.topics().getStatsAsync(topicName.getPartition(0).toString()).thenAccept(stats -> { stats.subscriptions.keySet().forEach(subscription -> { List<CompletableFuture<Void>> subscriptionFutures = new ArrayList<>(); for (int i = partitionMetadata.partitions; i < numPartitions; i++) { final String topicNamePartition = topicName.getPartition(i).toString(); subscriptionFutures.add(admin.topics().createSubscriptionAsync(topicNamePartition, subscription, MessageId.latest)); } FutureUtil.waitForAll(subscriptionFutures).thenRun(() -> { log.info("[{}] Successfully created new partitions {}", clientAppId(), topicName); result.complete(null); }).exceptionally(ex -> { log.warn("[{}] Failed to create subscriptions on new partitions for {}", clientAppId(), topicName, ex); result.completeExceptionally(ex); return null; }); }); }).exceptionally(ex -> { if (ex.getCause() instanceof PulsarAdminException.NotFoundException) { // The first partition doesn't exist, so there are currently to subscriptions to recreate result.complete(null); } else { log.warn("[{}] Failed to get list of subscriptions of {}", clientAppId(), topicName.getPartition(0), ex); result.completeExceptionally(ex); } return null; }); }).exceptionally(ex -> { log.warn("[{}] Failed to get partition metadata for {}", clientAppId(), topicName.toString()); result.completeExceptionally(ex); return null; }); return result; }