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:com.ikanow.aleph2.analytics.storm.utils.StormControllerUtil.java

/**
 * Stops a storm job, uses the bucket.id to try and find the job to stop
 * //from  www  .j av  a2s .co  m
 * @param bucket
 * @return
 */
public static CompletableFuture<BasicMessageBean> stopJob(IStormController storm_controller,
        DataBucketBean bucket, final Optional<String> sub_job) {
    CompletableFuture<BasicMessageBean> stop_future = new CompletableFuture<BasicMessageBean>();
    try {
        storm_controller.stopJob(bucketPathToTopologyName(bucket, sub_job));
    } catch (Exception ex) {
        stop_future.complete(ErrorUtils.buildErrorMessage(StormControllerUtil.class, "stopJob",
                ErrorUtils.getLongForm("Error stopping storm job: {0}", ex)));
        return stop_future;
    }
    stop_future.complete(ErrorUtils.buildSuccessMessage(StormControllerUtil.class, "stopJob",
            "Stopped storm job succesfully"));
    return stop_future;
}

From source file:enmasse.queue.scheduler.Artemis.java

public static Future<Broker> create(Vertx vertx, ProtonConnection connection) {
    CompletableFuture<Broker> promise = new CompletableFuture<>();
    connection.sessionOpenHandler(ProtonSession::open);
    BlockingQueue<Message> replies = new LinkedBlockingDeque<>();
    ProtonSender sender = connection.createSender("activemq.management");
    sender.openHandler(result -> {//from  w  ww. ja  v  a2  s.c  om
        ProtonReceiver receiver = connection.createReceiver("activemq.management");
        Source source = new Source();
        source.setDynamic(true);
        receiver.setSource(source);
        receiver.openHandler(h -> {
            promise.complete(new Artemis(vertx, sender, h.result().getRemoteSource().getAddress(), replies));
        });
        receiver.handler(((protonDelivery, message) -> {
            try {
                replies.put(message);
                ProtonHelper.accepted(protonDelivery, true);
            } catch (Exception e) {
                ProtonHelper.rejected(protonDelivery, true);
            }
        }));
        receiver.open();
    });
    sender.open();
    return promise;
}

From source file:org.apache.bookkeeper.mledger.offload.OffloaderUtils.java

/**
 * Extract the Pulsar offloader class from a offloader archive.
 *
 * @param narPath nar package path//from   w ww.  j  a v  a  2s  .  c  o  m
 * @return the offloader class name
 * @throws IOException when fail to retrieve the pulsar offloader class
 */
static Pair<NarClassLoader, LedgerOffloaderFactory> getOffloaderFactory(String narPath) throws IOException {
    NarClassLoader ncl = NarClassLoader.getFromArchive(new File(narPath), Collections.emptySet());
    String configStr = ncl.getServiceDefinition(PULSAR_OFFLOADER_SERVICE_NAME);

    OffloaderDefinition conf = ObjectMapperFactory.getThreadLocalYaml().readValue(configStr,
            OffloaderDefinition.class);
    if (StringUtils.isEmpty(conf.getOffloaderFactoryClass())) {
        throw new IOException(String.format(
                "The '%s' offloader does not provide an offloader factory implementation", conf.getName()));
    }

    try {
        // Try to load offloader factory class and check it implements Offloader interface
        Class factoryClass = ncl.loadClass(conf.getOffloaderFactoryClass());
        CompletableFuture<LedgerOffloaderFactory> loadFuture = new CompletableFuture<>();
        Thread loadingThread = new Thread(() -> {
            Thread.currentThread().setContextClassLoader(ncl);

            log.info("Loading offloader factory {} using class loader {}", factoryClass, ncl);
            try {
                Object offloader = factoryClass.newInstance();
                if (!(offloader instanceof LedgerOffloaderFactory)) {
                    throw new IOException("Class " + conf.getOffloaderFactoryClass()
                            + " does not implement interface " + LedgerOffloaderFactory.class.getName());
                }
                loadFuture.complete((LedgerOffloaderFactory) offloader);
            } catch (Throwable t) {
                loadFuture.completeExceptionally(t);
            }
        }, "load-factory-" + factoryClass);
        try {
            loadingThread.start();
            return Pair.of(ncl, loadFuture.get());
        } finally {
            loadingThread.join();
        }
    } catch (Throwable t) {
        rethrowIOException(t);
    }
    return null;
}

From source file:org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.java

/**
 * It returns map of broker and count of namespace that are belong to the same anti-affinity group as given
 * {@param namespaceName}/*from  w  ww  . ja  v  a 2s  . c  o m*/
 *
 * @param pulsar
 * @param namespaceName
 * @param brokerToNamespaceToBundleRange
 * @return
 */
public static CompletableFuture<Map<String, Integer>> getAntiAffinityNamespaceOwnedBrokers(
        final PulsarService pulsar, String namespaceName,
        Map<String, Map<String, Set<String>>> brokerToNamespaceToBundleRange) {

    CompletableFuture<Map<String, Integer>> antiAffinityNsBrokersResult = new CompletableFuture<>();
    ZooKeeperDataCache<Policies> policiesCache = pulsar.getConfigurationCache().policiesCache();

    policiesCache.getAsync(path(POLICIES, namespaceName)).thenAccept(policies -> {
        if (!policies.isPresent() || StringUtils.isBlank(policies.get().antiAffinityGroup)) {
            antiAffinityNsBrokersResult.complete(null);
            return;
        }
        final String antiAffinityGroup = policies.get().antiAffinityGroup;
        final Map<String, Integer> brokerToAntiAffinityNamespaceCount = new ConcurrentHashMap<>();
        final List<CompletableFuture<Void>> futures = Lists.newArrayList();
        brokerToNamespaceToBundleRange.forEach((broker, nsToBundleRange) -> {
            nsToBundleRange.forEach((ns, bundleRange) -> {
                CompletableFuture<Void> future = new CompletableFuture<>();
                futures.add(future);
                policiesCache.getAsync(path(POLICIES, ns)).thenAccept(nsPolicies -> {
                    if (nsPolicies.isPresent()
                            && antiAffinityGroup.equalsIgnoreCase(nsPolicies.get().antiAffinityGroup)) {
                        brokerToAntiAffinityNamespaceCount.compute(broker,
                                (brokerName, count) -> count == null ? 1 : count + 1);
                    }
                    future.complete(null);
                }).exceptionally(ex -> {
                    future.complete(null);
                    return null;
                });
            });
        });
        FutureUtil.waitForAll(futures)
                .thenAccept(r -> antiAffinityNsBrokersResult.complete(brokerToAntiAffinityNamespaceCount));
    }).exceptionally(ex -> {
        // namespace-policies has not been created yet
        antiAffinityNsBrokersResult.complete(null);
        return null;
    });
    return antiAffinityNsBrokersResult;
}

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

private static <REQ, PREQ, PRESP, RESP> CompletableFuture<RESP> call(HBaseRpcController controller,
        HRegionLocation loc, ClientService.Interface stub, REQ req, Converter<PREQ, byte[], REQ> reqConvert,
        RpcCall<PRESP, PREQ> rpcCall, Converter<RESP, HBaseRpcController, PRESP> respConverter) {
    CompletableFuture<RESP> future = new CompletableFuture<>();
    try {//from  w  ww. j  ava 2  s  .c o  m
        rpcCall.call(stub, controller, reqConvert.convert(loc.getRegionInfo().getRegionName(), req),
                new RpcCallback<PRESP>() {

                    @Override
                    public void run(PRESP resp) {
                        if (controller.failed()) {
                            future.completeExceptionally(controller.getFailed());
                        } else {
                            try {
                                future.complete(respConverter.convert(controller, resp));
                            } catch (IOException e) {
                                future.completeExceptionally(e);
                            }
                        }
                    }
                });
    } catch (IOException e) {
        future.completeExceptionally(e);
    }
    return future;
}

From source file:com.opopov.cloud.image.utils.Utils.java

public static <T> CompletableFuture<T> fromListenableFuture(ListenableFuture<T> listenable) {
    CompletableFuture<T> completable = new CompletableFuture<T>() {

        @Override//from  w ww .  ja  v  a  2s . c  o m
        public boolean isCancelled() {
            return listenable.isCancelled();
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            //delegate cancel to the wrapped listenable
            boolean cancelledStatus = listenable.cancel(mayInterruptIfRunning);
            super.cancel(mayInterruptIfRunning);
            return cancelledStatus;
        }
    };

    //now delegate the callbacks
    ListenableFutureCallback<T> callback = new ListenableFutureCallback<T>() {
        @Override
        public void onFailure(Throwable ex) {
            //delegate exception
            completable.completeExceptionally(ex);
        }

        @Override
        public void onSuccess(T result) {
            //delegate success
            completable.complete(result);
        }
    };

    listenable.addCallback(callback);

    return completable;

}

From source file:org.apache.hadoop.hbase.AsyncMetaTableAccessor.java

public static CompletableFuture<Pair<HRegionInfo, ServerName>> getRegion(RawAsyncTable metaTable,
        byte[] regionName) {
    CompletableFuture<Pair<HRegionInfo, ServerName>> future = new CompletableFuture<>();
    byte[] row = regionName;
    HRegionInfo parsedInfo = null;// ww w. j av a  2  s  .c  om
    try {
        parsedInfo = MetaTableAccessor.parseRegionInfoFromRegionName(regionName);
        row = MetaTableAccessor.getMetaKeyForRegion(parsedInfo);
    } catch (Exception parseEx) {
        // Ignore if regionName is a encoded region name.
    }

    final HRegionInfo finalHRI = parsedInfo;
    metaTable.get(new Get(row).addFamily(HConstants.CATALOG_FAMILY)).whenComplete((r, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }
        RegionLocations locations = MetaTableAccessor.getRegionLocations(r);
        HRegionLocation hrl = locations == null ? null
                : locations.getRegionLocation(finalHRI == null ? 0 : finalHRI.getReplicaId());
        if (hrl == null) {
            future.complete(null);
        } else {
            future.complete(new Pair<>(hrl.getRegionInfo(), hrl.getServerName()));
        }
    });

    return future;
}

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

CompletableFuture<HRegionLocation> getRegionLocation(TableName tableName, byte[] row, boolean reload) {
    CompletableFuture<HRegionLocation> future = new CompletableFuture<>();
    try {//ww w .j  a  v  a 2s  .co m
        future.complete(conn.getRegionLocation(tableName, row, reload));
    } catch (IOException e) {
        future.completeExceptionally(e);
    }
    return future;
}

From source file:org.apache.trafficcontrol.client.trafficops.TOSessionTest.java

@Test(expected = LoginException.class)
public void test401Response() throws Throwable {
    HttpResponse resp = Mockito.mock(HttpResponse.class);
    Mockito.when(resp.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_0, 401, "Not Auth"));

    final CompletableFuture<HttpResponse> f = new CompletableFuture<>();
    f.complete(resp);

    Mockito.doReturn(f).when(sessionMock).execute(Mockito.any(RequestBuilder.class));

    TOSession session = TOSession.builder().fromURI(baseUri).setRestClient(sessionMock).build();

    try {/*  w w  w. jav a 2 s .  c  o m*/
        session.getDeliveryServices().get();
    } catch (Throwable e) {
        throw e.getCause();
    }
}

From source file:org.apache.trafficcontrol.client.trafficops.TOSessionTest.java

@Test
public void deliveryServices() throws Throwable {
    final HttpResponse resp = Mockito.mock(HttpResponse.class);
    Mockito.doReturn(new BasicStatusLine(HttpVersion.HTTP_1_0, 200, "Ok")).when(resp).getStatusLine();
    Mockito.doReturn(new StringEntity(DeliveryService_Good_Response)).when(resp).getEntity();

    final CompletableFuture<HttpResponse> f = new CompletableFuture<>();
    f.complete(resp);

    Mockito.doReturn(f).when(sessionMock).execute(Mockito.any(RequestBuilder.class));

    final TOSession session = TOSession.builder().fromURI(baseUri).setRestClient(sessionMock).build();

    CollectionResponse cResp = session.getDeliveryServices().get();

    assertNotNull(cResp);// ww  w. j a v a2s  .c om
    assertNotNull(cResp.getResponse());
    assertEquals(1, cResp.getResponse().size());

    final Map<String, ?> service = cResp.getResponse().get(0);
    assertEquals("us-co-denver", service.get("cachegroup"));
    LOG.debug("Service: {}", service);
}