Example usage for java.util.concurrent CompletableFuture CompletableFuture

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

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

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;//from  w  w w  .  ja  v 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:ch.rasc.wampspring.testsupport.CompletableFutureWebSocketHandler.java

public void reset(int expectedNoOfResults) {
    this.noOfResults = expectedNoOfResults;
    this.messageFuture = new CompletableFuture<>();
    this.receivedMessages = new ArrayList<>();
}

From source file:com.devicehive.service.DeviceCommandService.java

public CompletableFuture<Optional<DeviceCommand>> findOne(Long id, String guid) {
    CommandSearchRequest searchRequest = new CommandSearchRequest();
    searchRequest.setId(id);/*  w  w w  .j a  va  2  s .  c  o m*/
    searchRequest.setGuid(guid);

    CompletableFuture<Response> future = new CompletableFuture<>();
    rpcClient.call(Request.newBuilder().withBody(searchRequest).build(), new ResponseConsumer(future));
    return future
            .thenApply(r -> r.getBody().cast(CommandSearchResponse.class).getCommands().stream().findFirst());
}

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

public CompletableFuture<Boolean> createSegment(final String scope, final String stream,
        final int segmentNumber, final ScalingPolicy policy, final HostControllerStore hostControllerStore,
        final ConnectionFactory clientCF) {
    final CompletableFuture<Boolean> result = new CompletableFuture<>();
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);

    final WireCommandType type = WireCommandType.CREATE_SEGMENT;

    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override/*from   w w  w  .  ja  v  a2  s  .  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 segmentAlreadyExists(WireCommands.SegmentAlreadyExists segmentAlreadyExists) {
            result.complete(true);
        }

        @Override
        public void segmentCreated(WireCommands.SegmentCreated segmentCreated) {
            result.complete(true);
        }

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

    Pair<Byte, Integer> extracted = extractFromPolicy(policy);

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

From source file:com.canoo.dolphin.client.ClientContextFactory.java

/**
 * Create a {@link ClientContext} based on the given configuration. This method doesn't block and returns a
 * {@link CompletableFuture} to receive its result. If the {@link ClientContext} can't be created the
 * {@link CompletableFuture#get()} will throw a {@link ClientInitializationException}.
 *
 * @param clientConfiguration the configuration
 * @return the future//from w w w.  j  a  v a  2 s  .  co  m
 */
public static CompletableFuture<ClientContext> connect(final ClientConfiguration clientConfiguration) {
    Assert.requireNonNull(clientConfiguration, "clientConfiguration");
    final CompletableFuture<ClientContext> result = new CompletableFuture<>();

    Level openDolphinLogLevel = clientConfiguration.getDolphinLogLevel();
    Logger openDolphinLogger = Logger.getLogger("org.opendolphin");
    openDolphinLogger.setLevel(openDolphinLogLevel);

    Executors.newSingleThreadExecutor().execute(() -> {
        try {
            final ForwardableCallback<DolphinRemotingException> remotingErrorHandler = new ForwardableCallback<>();
            final ClientDolphin clientDolphin = new ClientDolphin();
            clientDolphin.setClientModelStore(new ClientModelStore(clientDolphin));
            final HttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
            final ClientConnector clientConnector = new DolphinPlatformHttpClientConnector(clientDolphin,
                    new OptimizedJsonCodec(), httpClient, clientConfiguration.getServerEndpoint(),
                    remotingErrorHandler, clientConfiguration.getUiThreadHandler());
            clientDolphin.setClientConnector(clientConnector);
            final DolphinCommandHandler dolphinCommandHandler = new DolphinCommandHandler(clientDolphin);
            final EventDispatcher dispatcher = new ClientEventDispatcher(clientDolphin);
            final BeanRepository beanRepository = new BeanRepositoryImpl(clientDolphin, dispatcher);
            final Converters converters = new Converters(beanRepository);
            final PresentationModelBuilderFactory builderFactory = new ClientPresentationModelBuilderFactory(
                    clientDolphin);
            final ClassRepository classRepository = new ClassRepositoryImpl(clientDolphin, converters,
                    builderFactory);
            final ListMapper listMapper = new ListMapperImpl(clientDolphin, classRepository, beanRepository,
                    builderFactory, dispatcher);
            final BeanBuilder beanBuilder = new ClientBeanBuilderImpl(classRepository, beanRepository,
                    listMapper, builderFactory, dispatcher);
            final ClientPlatformBeanRepository platformBeanRepository = new ClientPlatformBeanRepository(
                    clientDolphin, beanRepository, dispatcher, converters);
            final ClientBeanManagerImpl clientBeanManager = new ClientBeanManagerImpl(beanRepository,
                    beanBuilder, clientDolphin);
            final ControllerProxyFactory controllerProxyFactory = new ControllerProxyFactoryImpl(
                    platformBeanRepository, dolphinCommandHandler, clientDolphin);
            final ClientContext clientContext = new ClientContextImpl(clientConfiguration, clientDolphin,
                    controllerProxyFactory, dolphinCommandHandler, platformBeanRepository, clientBeanManager,
                    remotingErrorHandler);
            clientDolphin.startPushListening(PlatformConstants.POLL_EVENT_BUS_COMMAND_NAME,
                    PlatformConstants.RELEASE_EVENT_BUS_COMMAND_NAME);
            clientConfiguration.getUiThreadHandler()
                    .executeInsideUiThread(() -> result.complete(clientContext));
        } catch (Exception e) {
            result.obtrudeException(new ClientInitializationException("Can not connect to server!", e));
            throw new ClientInitializationException(e);
        }
    });
    return result;
}

From source file:com.devicehive.handler.notification.NotificationSearchHandlerTest.java

@Test
public void shouldNotFindSingleNotificationByIdAndGuid() throws Exception {
    NotificationSearchRequest searchRequest = new NotificationSearchRequest();
    searchRequest.setId(Long.MAX_VALUE); // nonexistent id
    searchRequest.setGuid(UUID.randomUUID().toString()); // random guid

    Request request = Request.newBuilder().withPartitionKey(searchRequest.getGuid()).withBody(searchRequest)
            .build();/*from  ww  w  . java 2  s.c  om*/
    CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(request, future::complete);

    Response response = future.get(10, TimeUnit.SECONDS);
    NotificationSearchResponse responseBody = (NotificationSearchResponse) response.getBody();
    assertTrue(responseBody.getNotifications().isEmpty());
}

From source file:com.devicehive.service.DeviceNotificationService.java

public CompletableFuture<Optional<DeviceNotification>> findOne(Long id, String guid) {
    NotificationSearchRequest searchRequest = new NotificationSearchRequest();
    searchRequest.setId(id);//from   w ww .  ja va 2s. co m
    searchRequest.setGuid(guid);

    CompletableFuture<Response> future = new CompletableFuture<>();
    rpcClient.call(
            Request.newBuilder().withBody(searchRequest).withPartitionKey(searchRequest.getGuid()).build(),
            new ResponseConsumer(future));
    return future
            .thenApply(r -> ((NotificationSearchResponse) r.getBody()).getNotifications().stream().findFirst());
}

From source file:opensnap.repository.MongoRepository.java

public CompletableFuture<T> getOne(String key, Object value) {
    CompletableFuture<T> future = new CompletableFuture<>();

    collection.find(new Document(key, value)).one().register((document, e) -> {
        try {//from  ww w .  j a  v a  2s  . com
            if (document != null) {
                future.complete(mapper.readValue(toJson(document), clazz));
            } else {
                logger.error("No document with attribute " + key + "=" + value + " found", e);
                future.cancel(true);
            }
        } catch (IOException ex) {
            logger.error("Error while parsing document in getOne() : " + document.toString(), ex);
            future.cancel(true);
        }
    });
    return future;
}

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 {/*ww w.j  av 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.devicehive.rpcclient.RpcClientActionTest.java

@Test
public void testCommandSearchAction() throws Exception {
    CommandSearchRequest searchRequest = new CommandSearchRequest();
    searchRequest.setId(Long.MAX_VALUE); // nonexistent id
    searchRequest.setGuid(UUID.randomUUID().toString()); // random guid

    Request request = Request.newBuilder().withPartitionKey(searchRequest.getGuid()).withBody(searchRequest)
            .build();//  w  w  w.jav a2 s.  com
    CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(request, future::complete);

    Response response = future.get(10, TimeUnit.SECONDS);
    CommandSearchResponse responseBody = (CommandSearchResponse) response.getBody();
    assertTrue(responseBody.getCommands().isEmpty());
}