List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Subscribes to a topic on the given connection, but does not alter the subscriber list. * * @param topic The topic to subscribe to. * @return Completes with true if successful. Exceptionally otherwise. *//*ww w .j ava 2 s .co m*/ protected CompletableFuture<Boolean> subscribeRaw(String topic) { logger.trace("subscribeRaw message consumer for topic '{}' from broker '{}'", topic, host); CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); try { MqttAsyncClient client = this.client; if (client != null && client.isConnected()) { client.subscribe(topic, qos, future, actionCallback); } else { future.complete(false); } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error subscribing to topic {}", topic, e); future.completeExceptionally(e); } return future; }
From source file:io.pravega.controller.store.stream.PersistentStreamBase.java
/** * If scale is ongoing, try to delete the epoch node. * * @param epoch epoch// w w w. j av a 2 s . co m * @return true if we are able to delete the epoch, false otherwise. */ @Override public CompletableFuture<Boolean> scaleTryDeleteEpoch(final int epoch) { return getHistoryTableFromStore() .thenCompose(historyTable -> getSegmentTableFromStore() .thenApply(segmentTable -> new ImmutablePair<>(historyTable, segmentTable))) .thenCompose(pair -> { Data<T> segmentTable = pair.getRight(); Data<T> historyTable = pair.getLeft(); CompletableFuture<Boolean> result = new CompletableFuture<>(); if (TableHelper.isScaleOngoing(historyTable.getData(), segmentTable.getData())) { deleteEpochNode(epoch).whenComplete((r, e) -> { if (e != null) { Throwable ex = ExceptionHelpers.getRealException(e); if (ex instanceof StoreException.DataNotEmptyException) { // cant delete as there are transactions still running under epoch node result.complete(false); } else { result.completeExceptionally(ex); } } else { result.complete(true); } }); } else { result.complete(false); } return result; }); }
From source file:org.apache.distributedlog.lock.ZKSessionLock.java
/** * Get client id and its ephemeral owner. * * @param zkClient//ww w .ja v a 2 s.c om * zookeeper client * @param lockPath * lock path * @param nodeName * node name * @return client id and its ephemeral owner. */ static CompletableFuture<Pair<String, Long>> asyncParseClientID(ZooKeeper zkClient, String lockPath, String nodeName) { String[] parts = nodeName.split("_"); // member_<clientid>_s<owner_session>_ if (4 == parts.length && parts[2].startsWith("s")) { long sessionOwner = Long.parseLong(parts[2].substring(1)); String clientId; try { clientId = URLDecoder.decode(parts[1], UTF_8.name()); return FutureUtils.value(Pair.of(clientId, sessionOwner)); } catch (UnsupportedEncodingException e) { // if failed to parse client id, we have to get client id by zookeeper#getData. } } final CompletableFuture<Pair<String, Long>> promise = new CompletableFuture<Pair<String, Long>>(); zkClient.getData(lockPath + "/" + nodeName, false, new AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (KeeperException.Code.OK.intValue() != rc) { promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc))); } else { promise.complete(Pair.of(deserializeClientId(data), stat.getEphemeralOwner())); } } }, null); return promise; }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> updateMarkerData(int segmentNumber, Data<Integer> data) { CompletableFuture<Void> result = new CompletableFuture<>(); synchronized (markersLock) { if (!markers.containsKey(segmentNumber)) { result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Stream: " + getName() + " Segment number: " + segmentNumber)); } else {// www . j av a 2 s . co m markers.compute(segmentNumber, (x, y) -> { if (y.getVersion().equals(data.getVersion())) { result.complete(null); return new Data<>(Arrays.copyOf(data.getData(), data.getData().length), data.getVersion() + 1); } else { result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT, "Stream: " + getName() + " Segment number: " + segmentNumber)); return y; } }); } } return result; }
From source file:org.apache.bookkeeper.mledger.impl.OffloadPrefixTest.java
@Test public void testOffloadConflict() throws Exception { Set<Pair<Long, UUID>> deleted = ConcurrentHashMap.newKeySet(); CompletableFuture<Set<Long>> errorLedgers = new CompletableFuture<>(); Set<Pair<Long, UUID>> failedOffloads = ConcurrentHashMap.newKeySet(); MockLedgerOffloader offloader = new MockLedgerOffloader() { @Override/*from w w w. ja va2s .com*/ public CompletableFuture<Void> offload(ReadHandle ledger, UUID uuid, Map<String, String> extraMetadata) { return errorLedgers.thenCompose((errors) -> { if (errors.remove(ledger.getId())) { failedOffloads.add(Pair.of(ledger.getId(), uuid)); CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new Exception("Some kind of error")); return future; } else { return super.offload(ledger, uuid, extraMetadata); } }); } @Override public CompletableFuture<Void> deleteOffloaded(long ledgerId, UUID uuid, Map<String, String> offloadDriverMetadata) { deleted.add(Pair.of(ledgerId, uuid)); return super.deleteOffloaded(ledgerId, uuid, offloadDriverMetadata); } }; ManagedLedgerConfig config = new ManagedLedgerConfig(); config.setMaxEntriesPerLedger(10); config.setMinimumRolloverTime(0, TimeUnit.SECONDS); config.setRetentionTime(10, TimeUnit.MINUTES); config.setLedgerOffloader(offloader); ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("my_test_ledger", config); for (int i = 0; i < 15; i++) { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } Set<Long> errorSet = ConcurrentHashMap.newKeySet(); errorSet.add(ledger.getLedgersInfoAsList().get(0).getLedgerId()); errorLedgers.complete(errorSet); try { ledger.offloadPrefix(ledger.getLastConfirmedEntry()); } catch (ManagedLedgerException e) { // expected } Assert.assertTrue(errorSet.isEmpty()); Assert.assertEquals(failedOffloads.size(), 1); Assert.assertEquals(deleted.size(), 0); long expectedFailedLedger = ledger.getLedgersInfoAsList().get(0).getLedgerId(); UUID expectedFailedUUID = new UUID(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidMsb(), ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidLsb()); Assert.assertEquals(failedOffloads.stream().findFirst().get(), Pair.of(expectedFailedLedger, expectedFailedUUID)); Assert.assertFalse(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); // try offload again ledger.offloadPrefix(ledger.getLastConfirmedEntry()); Assert.assertEquals(failedOffloads.size(), 1); Assert.assertEquals(deleted.size(), 1); Assert.assertEquals(deleted.stream().findFirst().get(), Pair.of(expectedFailedLedger, expectedFailedUUID)); UUID successUUID = new UUID(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidMsb(), ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidLsb()); Assert.assertFalse(successUUID.equals(expectedFailedUUID)); Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); }
From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java
@Override public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) { try {/* ww w. j a v a 2 s . c om*/ ClientResponse response = apply(request); callback.response(response); return CompletableFuture.completedFuture(response); } catch (Throwable t) { callback.failure(t); CompletableFuture<Object> future = new CompletableFuture<>(); future.completeExceptionally(t); return future; } }
From source file:com.yahoo.pulsar.broker.service.BrokerService.java
public CompletableFuture<ManagedLedgerConfig> getManagedLedgerConfig(DestinationName topicName) { CompletableFuture<ManagedLedgerConfig> future = new CompletableFuture<>(); // Execute in background thread, since getting the policies might block if the z-node wasn't already cached pulsar.getOrderedExecutor().submitOrdered(topicName, safeRun(() -> { NamespaceName namespace = topicName.getNamespaceObject(); ServiceConfiguration serviceConfig = pulsar.getConfiguration(); // Get persistence policy for this destination Policies policies;/*from w w w . java 2 s . com*/ try { policies = pulsar .getConfigurationCache().policiesCache().get(AdminResource.path("policies", namespace.getProperty(), namespace.getCluster(), namespace.getLocalName())) .orElse(null); } catch (Throwable t) { // Ignoring since if we don't have policies, we fallback on the default log.warn("Got exception when reading persistence policy for {}: {}", topicName, t.getMessage(), t); future.completeExceptionally(t); return; } PersistencePolicies persistencePolicies = policies != null ? policies.persistence : null; RetentionPolicies retentionPolicies = policies != null ? policies.retention_policies : null; if (persistencePolicies == null) { // Apply default values persistencePolicies = new PersistencePolicies(serviceConfig.getManagedLedgerDefaultEnsembleSize(), serviceConfig.getManagedLedgerDefaultWriteQuorum(), serviceConfig.getManagedLedgerDefaultAckQuorum(), serviceConfig.getManagedLedgerDefaultMarkDeleteRateLimit()); } if (retentionPolicies == null) { retentionPolicies = new RetentionPolicies(serviceConfig.getDefaultRetentionTimeInMinutes(), serviceConfig.getDefaultRetentionSizeInMB()); } ManagedLedgerConfig config = new ManagedLedgerConfig(); config.setEnsembleSize(persistencePolicies.getBookkeeperEnsemble()); config.setWriteQuorumSize(persistencePolicies.getBookkeeperWriteQuorum()); config.setAckQuorumSize(persistencePolicies.getBookkeeperAckQuorum()); config.setThrottleMarkDelete(persistencePolicies.getManagedLedgerMaxMarkDeleteRate()); config.setDigestType(DigestType.CRC32); config.setMaxEntriesPerLedger(serviceConfig.getManagedLedgerMaxEntriesPerLedger()); config.setMinimumRolloverTime(serviceConfig.getManagedLedgerMinLedgerRolloverTimeMinutes(), TimeUnit.MINUTES); config.setMaximumRolloverTime(serviceConfig.getManagedLedgerMaxLedgerRolloverTimeMinutes(), TimeUnit.MINUTES); config.setMaxSizePerLedgerMb(2048); config.setMetadataEnsembleSize(serviceConfig.getManagedLedgerDefaultEnsembleSize()); config.setMetadataWriteQuorumSize(serviceConfig.getManagedLedgerDefaultWriteQuorum()); config.setMetadataAckQuorumSize(serviceConfig.getManagedLedgerDefaultAckQuorum()); config.setMetadataMaxEntriesPerLedger(serviceConfig.getManagedLedgerCursorMaxEntriesPerLedger()); config.setLedgerRolloverTimeout(serviceConfig.getManagedLedgerCursorRolloverTimeInSeconds()); config.setRetentionTime(retentionPolicies.getRetentionTimeInMinutes(), TimeUnit.MINUTES); config.setRetentionSizeInMB(retentionPolicies.getRetentionSizeInMB()); future.complete(config); }, (exception) -> future.completeExceptionally(exception))); return future; }
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Unsubscribes from a topic on the given connection, but does not alter the subscriber list. * * @param client The client connection/* w w w .j a va2s . c om*/ * @param topic The topic to unsubscribe from * @return Completes with true if successful. Completes with false if no broker connection is established. * Exceptionally otherwise. */ protected CompletableFuture<Boolean> unsubscribeRaw(MqttAsyncClient client, String topic) { logger.trace("Unsubscribing message consumer for topic '{}' from broker '{}'", topic, host); CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); try { if (client.isConnected()) { client.unsubscribe(topic, future, actionCallback); } else { future.complete(false); } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error unsubscribing topic from broker", e); future.completeExceptionally(e); } return future; }
From source file:org.apache.bookkeeper.mledger.offload.jcloud.impl.BlobStoreManagedLedgerOffloader.java
@Override public CompletableFuture<ReadHandle> readOffloaded(long ledgerId, UUID uid, Map<String, String> offloadDriverMetadata) { String readBucket = getReadBucket(offloadDriverMetadata); BlobStore readBlobstore = getReadBlobStore(offloadDriverMetadata); CompletableFuture<ReadHandle> promise = new CompletableFuture<>(); String key = dataBlockOffloadKey(ledgerId, uid); String indexKey = indexBlockOffloadKey(ledgerId, uid); scheduler.chooseThread(ledgerId).submit(() -> { try {/*from w ww.j ava2 s . c om*/ promise.complete(BlobStoreBackedReadHandleImpl.open(scheduler.chooseThread(ledgerId), readBlobstore, readBucket, key, indexKey, VERSION_CHECK, ledgerId, readBufferSize)); } catch (Throwable t) { log.error("Failed readOffloaded: ", t); promise.completeExceptionally(t); } }); return promise; }
From source file:org.apache.pulsar.broker.admin.impl.PersistentTopicsBase.java
protected void internalDeletePartitionedTopic(boolean authoritative, boolean force) { validateAdminAccessForTenant(topicName.getTenant()); PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(topicName, authoritative); int numPartitions = partitionMetadata.partitions; if (numPartitions > 0) { final CompletableFuture<Void> future = new CompletableFuture<>(); final AtomicInteger count = new AtomicInteger(numPartitions); try {//w ww . j av a2 s . co m for (int i = 0; i < numPartitions; i++) { TopicName topicNamePartition = topicName.getPartition(i); pulsar().getAdminClient().persistentTopics().deleteAsync(topicNamePartition.toString(), force) .whenComplete((r, ex) -> { if (ex != null) { if (ex instanceof NotFoundException) { // if the sub-topic is not found, the client might not have called create // producer or it might have been deleted earlier, so we ignore the 404 error. // For all other exception, we fail the delete partition method even if a single // partition is failed to be deleted if (log.isDebugEnabled()) { log.debug("[{}] Partition not found: {}", clientAppId(), topicNamePartition); } } else { future.completeExceptionally(ex); log.error("[{}] Failed to delete partition {}", clientAppId(), topicNamePartition, ex); return; } } else { log.info("[{}] Deleted partition {}", clientAppId(), topicNamePartition); } if (count.decrementAndGet() == 0) { future.complete(null); } }); } future.get(); } catch (Exception e) { Throwable t = e.getCause(); if (t instanceof PreconditionFailedException) { throw new RestException(Status.PRECONDITION_FAILED, "Topic has active producers/subscriptions"); } else { throw new RestException(t); } } } // Only tries to delete the znode for partitioned topic when all its partitions are successfully deleted String path = path(PARTITIONED_TOPIC_PATH_ZNODE, namespaceName.toString(), domain(), topicName.getEncodedLocalName()); try { globalZk().delete(path, -1); globalZkCache().invalidate(path); // we wait for the data to be synced in all quorums and the observers Thread.sleep(PARTITIONED_TOPIC_WAIT_SYNC_TIME_MS); log.info("[{}] Deleted partitioned topic {}", clientAppId(), topicName); } catch (KeeperException.NoNodeException nne) { throw new RestException(Status.NOT_FOUND, "Partitioned topic does not exist"); } catch (KeeperException.BadVersionException e) { log.warn("[{}] Failed to delete partitioned topic {}: concurrent modification", clientAppId(), topicName); throw new RestException(Status.CONFLICT, "Concurrent modification"); } catch (Exception e) { log.error("[{}] Failed to delete partitioned topic {}", clientAppId(), topicName, e); throw new RestException(e); } }