Example usage for java.util.concurrent CompletableFuture complete

List of usage examples for java.util.concurrent CompletableFuture complete

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture complete.

Prototype

public boolean complete(T value) 

Source Link

Document

If not already completed, sets the value returned by #get() and related methods to the given value.

Usage

From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java

@Override
public CompletableFuture<Void> closeRegion(byte[] regionName, String serverName) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    getRegion(regionName).whenComplete((p, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }/*from   www.  j av a  2  s .c om*/
        if (p == null || p.getFirst() == null) {
            future.completeExceptionally(new UnknownRegionException(Bytes.toStringBinary(regionName)));
            return;
        }
        if (serverName != null) {
            closeRegion(ServerName.valueOf(serverName), p.getFirst()).whenComplete((p2, err2) -> {
                if (err2 != null) {
                    future.completeExceptionally(err2);
                } else {
                    future.complete(null);
                }
            });
        } else {
            if (p.getSecond() == null) {
                future.completeExceptionally(new NotServingRegionException(regionName));
            } else {
                closeRegion(p.getSecond(), p.getFirst()).whenComplete((p2, err2) -> {
                    if (err2 != null) {
                        future.completeExceptionally(err2);
                    } else {
                        future.complete(null);
                    }
                });
            }
        }
    });
    return future;
}

From source file:org.apache.pulsar.broker.authorization.PulsarAuthorizationProvider.java

@Override
public CompletableFuture<Void> grantPermissionAsync(NamespaceName namespaceName, Set<AuthAction> actions,
        String role, String authDataJson) {
    CompletableFuture<Void> result = new CompletableFuture<>();

    try {/*from  w  w  w  . j a  v  a  2  s. co m*/
        validatePoliciesReadOnlyAccess();
    } catch (Exception e) {
        result.completeExceptionally(e);
    }

    ZooKeeper globalZk = configCache.getZooKeeper();
    final String policiesPath = String.format("/%s/%s/%s", "admin", POLICIES, namespaceName.toString());

    try {
        Stat nodeStat = new Stat();
        byte[] content = globalZk.getData(policiesPath, null, nodeStat);
        Policies policies = getThreadLocal().readValue(content, Policies.class);
        policies.auth_policies.namespace_auth.put(role, actions);

        // Write back the new policies into zookeeper
        globalZk.setData(policiesPath, getThreadLocal().writeValueAsBytes(policies), nodeStat.getVersion());

        configCache.policiesCache().invalidate(policiesPath);

        log.info("[{}] Successfully granted access for role {}: {} - namespace {}", role, role, actions,
                namespaceName);
        result.complete(null);
    } catch (KeeperException.NoNodeException e) {
        log.warn("[{}] Failed to set permissions for namespace {}: does not exist", role, namespaceName);
        result.completeExceptionally(new IllegalArgumentException("Namespace does not exist" + namespaceName));
    } catch (KeeperException.BadVersionException e) {
        log.warn("[{}] Failed to set permissions for namespace {}: concurrent modification", role,
                namespaceName);
        result.completeExceptionally(new IllegalStateException(
                "Concurrent modification on zk path: " + policiesPath + ", " + e.getMessage()));
    } catch (Exception e) {
        log.error("[{}] Failed to get permissions for namespace {}", role, namespaceName, e);
        result.completeExceptionally(
                new IllegalStateException("Failed to get permissions for namespace " + namespaceName));
    }

    return result;
}

From source file:io.pravega.controller.store.stream.PersistentStreamBase.java

/**
 * If scale is ongoing, try to delete the epoch node.
 *
 * @param epoch epoch//  w  ww .ja v a2s  .c  o 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.bookkeeper.client.BookieWriteLedgerTest.java

@Test
@SuppressWarnings("unchecked")
public void testLedgerCreateByteBufRefCnt() throws Exception {
    final LedgerHandle lh = bkc.createLedger(5, 3, 2, digestType, ledgerPassword, null);

    final List<AbstractByteBufAllocator> allocs = Lists.newArrayList(new PooledByteBufAllocator(true),
            new PooledByteBufAllocator(false), new UnpooledByteBufAllocator(true),
            new UnpooledByteBufAllocator(false));

    int entryId = 0;
    for (AbstractByteBufAllocator alloc : allocs) {
        final ByteBuf data = alloc.buffer(10);
        data.writeBytes(("fragment0" + entryId).getBytes());
        assertEquals("ref count on ByteBuf should be 1", 1, data.refCnt());

        CompletableFuture<Integer> cf = new CompletableFuture<>();
        lh.asyncAddEntry(data, (rc, handle, eId, ctx) -> {
            CompletableFuture<Integer> future = (CompletableFuture<Integer>) ctx;
            future.complete(rc);
        }, cf);/*from   w  w w .j ava 2 s .  co  m*/

        int rc = cf.get();
        assertEquals("rc code is OK", BKException.Code.OK, rc);

        for (int i = 0; i < 10; i++) {
            if (data.refCnt() == 0) {
                break;
            }
            TimeUnit.MILLISECONDS.sleep(250); // recycler runs asynchronously
        }
        assertEquals("writing entry with id " + entryId + ", ref count on ByteBuf should be 0 ", 0,
                data.refCnt());

        org.apache.bookkeeper.client.api.LedgerEntry e = lh.read(entryId, entryId).getEntry(entryId);
        assertEquals("entry data is correct", "fragment0" + entryId, new String(e.getEntryBytes()));
        entryId++;
    }

    bkc.deleteLedger(lh.ledgerId);
}

From source file:org.onosproject.store.consistent.impl.DistributedLeadershipManager.java

private void doRunForLeadership(String path, CompletableFuture<Leadership> future) {
    try {/*from   w  w w .ja  va2 s .c  o m*/
        Versioned<List<NodeId>> candidates = candidateMap.computeIf(path,
                currentList -> currentList == null || !currentList.contains(localNodeId),
                (topic, currentList) -> {
                    if (currentList == null) {
                        return ImmutableList.of(localNodeId);
                    } else {
                        List<NodeId> newList = Lists.newLinkedList();
                        newList.addAll(currentList);
                        newList.add(localNodeId);
                        return newList;
                    }
                });
        log.debug("In the leadership race for topic {} with candidates {}", path, candidates);
        activeTopics.add(path);
        Leadership leadership = electLeader(path, candidates.value());
        if (leadership == null) {
            pendingFutures.put(path, future);
        } else {
            future.complete(leadership);
        }
    } catch (ConsistentMapException e) {
        log.debug("Failed to enter topic leader race for {}. Retrying.", path, e);
        rerunForLeadership(path, future);
    }
}

From source file:io.pravega.controller.server.SegmentHelper.java

public CompletableFuture<TxnStatus> abortTransaction(final String scope, final String stream,
        final int segmentNumber, final UUID txId, final HostControllerStore hostControllerStore,
        final ConnectionFactory clientCF) {
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);
    final CompletableFuture<TxnStatus> result = new CompletableFuture<>();
    final WireCommandType type = WireCommandType.ABORT_TRANSACTION;
    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override// ww  w  .j a va  2s  .  c o m
        public void connectionDropped() {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped));
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost));
        }

        @Override
        public void transactionCommitted(WireCommands.TransactionCommitted transactionCommitted) {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.PreconditionFailed));
        }

        @Override
        public void transactionAborted(WireCommands.TransactionAborted transactionDropped) {
            result.complete(TxnStatus.newBuilder().setStatus(TxnStatus.Status.SUCCESS).build());
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };

    WireCommands.AbortTransaction request = new WireCommands.AbortTransaction(idGenerator.get(),
            Segment.getScopedName(scope, stream, segmentNumber), txId);
    sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri));
    return result;
}

From source file:org.apache.bookkeeper.client.BookieWriteLedgerTest.java

@Test
@SuppressWarnings("unchecked")
public void testLedgerCreateAdvByteBufRefCnt() throws Exception {
    long ledgerId = rng.nextLong();
    ledgerId &= Long.MAX_VALUE;
    if (!baseConf.getLedgerManagerFactoryClass().equals(LongHierarchicalLedgerManagerFactory.class)) {
        // since LongHierarchicalLedgerManager supports ledgerIds of
        // decimal length upto 19 digits but other
        // LedgerManagers only upto 10 decimals
        ledgerId %= 9999999999L;//from  www  .  j  a  v  a2s  .  c  o  m
    }

    final LedgerHandle lh = bkc.createLedgerAdv(ledgerId, 5, 3, 2, digestType, ledgerPassword, null);

    final List<AbstractByteBufAllocator> allocs = Lists.newArrayList(new PooledByteBufAllocator(true),
            new PooledByteBufAllocator(false), new UnpooledByteBufAllocator(true),
            new UnpooledByteBufAllocator(false));

    long entryId = 0;
    for (AbstractByteBufAllocator alloc : allocs) {
        final ByteBuf data = alloc.buffer(10);
        data.writeBytes(("fragment0" + entryId).getBytes());
        assertEquals("ref count on ByteBuf should be 1", 1, data.refCnt());

        CompletableFuture<Integer> cf = new CompletableFuture<>();
        lh.asyncAddEntry(entryId, data, (rc, handle, eId, qwcLatency, ctx) -> {
            CompletableFuture<Integer> future = (CompletableFuture<Integer>) ctx;
            future.complete(rc);
        }, cf);

        int rc = cf.get();
        assertEquals("rc code is OK", BKException.Code.OK, rc);

        for (int i = 0; i < 10; i++) {
            if (data.refCnt() == 0) {
                break;
            }
            TimeUnit.MILLISECONDS.sleep(250); // recycler runs asynchronously
        }
        assertEquals("writing entry with id " + entryId + ", ref count on ByteBuf should be 0 ", 0,
                data.refCnt());

        org.apache.bookkeeper.client.api.LedgerEntry e = lh.read(entryId, entryId).getEntry(entryId);
        assertEquals("entry data is correct", "fragment0" + entryId, new String(e.getEntryBytes()));
        entryId++;
    }

    bkc.deleteLedger(lh.ledgerId);
}

From source file:org.apache.distributedlog.impl.ZKLogMetadataStore.java

@Override
public CompletableFuture<Iterator<String>> getLogs(String logNamePrefix) {
    final CompletableFuture<Iterator<String>> promise = new CompletableFuture<Iterator<String>>();
    final String nsRootPath;
    if (StringUtils.isEmpty(logNamePrefix)) {
        nsRootPath = namespace.getPath();
    } else {//  w ww .  jav  a  2s  .c o m
        nsRootPath = namespace.getPath() + "/" + logNamePrefix;
    }
    try {
        final ZooKeeper zk = zkc.get();
        zk.sync(nsRootPath, new AsyncCallback.VoidCallback() {
            @Override
            public void processResult(int syncRc, String syncPath, Object ctx) {
                if (KeeperException.Code.OK.intValue() == syncRc) {
                    zk.getChildren(nsRootPath, false, new AsyncCallback.Children2Callback() {
                        @Override
                        public void processResult(int rc, String path, Object ctx, List<String> children,
                                Stat stat) {
                            if (KeeperException.Code.OK.intValue() == rc) {
                                List<String> results = Lists.newArrayListWithExpectedSize(children.size());
                                for (String child : children) {
                                    if (!isReservedStreamName(child)) {
                                        results.add(child);
                                    }
                                }
                                promise.complete(results.iterator());
                            } else if (KeeperException.Code.NONODE.intValue() == rc) {
                                List<String> streams = Lists.newLinkedList();
                                promise.complete(streams.iterator());
                            } else {
                                promise.completeExceptionally(new ZKException(
                                        "Error reading namespace " + nsRootPath, KeeperException.Code.get(rc)));
                            }
                        }
                    }, null);
                } else if (KeeperException.Code.NONODE.intValue() == syncRc) {
                    List<String> streams = Lists.newLinkedList();
                    promise.complete(streams.iterator());
                } else {
                    promise.completeExceptionally(new ZKException("Error reading namespace " + nsRootPath,
                            KeeperException.Code.get(syncRc)));
                }
            }
        }, null);
        zkc.get();
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.completeExceptionally(e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        promise.completeExceptionally(e);
    }
    return promise;
}

From source file:com.ikanow.aleph2.analytics.storm.services.RemoteStormController.java

/**
 * Submits a job to the remote storm cluster.  Sends the input jar to the server and then
 * submits the supplied topology w/ the given job_name.
 * //w  w w  .  j a v  a2 s.  c o m
 */
@Override
public CompletableFuture<BasicMessageBean> submitJob(String job_name, String input_jar_location,
        StormTopology topology, Map<String, Object> config_override) {
    final CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>();
    logger.info("Submitting job: " + job_name + " jar: " + input_jar_location);
    logger.info("submitting jar");

    final String remote_jar_location = StormSubmitter.submitJar(remote_config, input_jar_location);
    //      final String json_conf = JSONValue.toJSONString(ImmutableMap.builder()
    //               .putAll(remote_config)
    //               .putAll(config_override)
    //            .build());
    final String json_conf = JSONValue.toJSONString(mergeMaps(Arrays.asList(remote_config, config_override)));
    logger.info("submitting topology");
    try {
        synchronized (client) {
            client.submitTopology(job_name, remote_jar_location, json_conf, topology);
        }
        //verify job was assigned some executors
        final TopologyInfo info = getJobStats(job_name);
        logger.info("submitted job received: " + info.get_executors_size() + " executors");
        if (info.get_executors_size() == 0) {
            logger.info("received 0 executors, killing job, reporting failure");
            //no executors were available for this job, stop the job, throw an error
            stopJob(job_name);

            future.complete(ErrorUtils.buildErrorMessage(this, "submitJob",
                    "No executors were assigned to this job, typically this is because too many jobs are currently running, kill some other jobs and resubmit."));
            return future;
        }
    } catch (Exception ex) {
        logger.info(ErrorUtils.getLongForm("Error submitting job: " + job_name + ": {0}", ex));
        return FutureUtils.returnError(ex);
    }

    future.complete(
            ErrorUtils.buildSuccessMessage(this, "submitJob", "Submitted job successfully: " + job_name));
    return future;
}

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  w  w .j  av  a  2 s  .c  o  m
            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;
}