Example usage for com.google.common.util.concurrent SettableFuture create

List of usage examples for com.google.common.util.concurrent SettableFuture create

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SettableFuture create.

Prototype

public static <V> SettableFuture<V> create() 

Source Link

Document

Creates a new SettableFuture that can be completed or cancelled by a later method call.

Usage

From source file:com.kixeye.janus.client.http.async.AsyncHttpClient.java

/**
 * Executes the given request./*ww  w . ja  v a 2s. c om*/
 * 
 * @param request the HttpRequest to execute
 * @param path the path to send the request to.  the path variables should be enclosed with "{}" Ex. /stores/{storeId}/items/{itemId}
 * @param urlVariables variables that will be substituted into the given path. Order of the given urlVariables is significant. For example,
  *                     variables 5, 10 will be substituted into /stores/{storeId}/items/{itemId} with a result of /stores/5/items/10.
  *
 * @return ListenableFuture clients can register a listener to be notified when the http request has been completed.
 * @throws IOException
 */
public ListenableFuture<HttpResponse> execute(HttpRequest request, String path, Object... urlVariables)
        throws IOException {
    SettableFuture<HttpResponse> response = SettableFuture.create();
    executor.submit(
            new ExecuteTask(response, request, path, urlVariables, janus, httpClient, executor, numRetries));
    return response;
}

From source file:edu.umich.si.inteco.minuku.dao.AnnotatedImageDataRecordDAO.java

@Override
public Future<List<T>> getLast(int N) throws DAOException {
    final SettableFuture<List<T>> settableFuture = SettableFuture.create();
    final Date today = new Date();

    final List<T> lastNRecords = Collections.synchronizedList(new ArrayList<T>());

    getLastNValues(N, myUserEmail, today, lastNRecords, settableFuture, this.mFirebaseUrl);

    return settableFuture;
}

From source file:com.uber.sdk.rides.client.internal.RetrofitAdapter.java

@Override
public Response<Promotion> getPromotions(float startLatitude, float startLongitude, float endLatitude,
        float endLongitude) throws ApiException, NetworkException {
    final SettableFuture<ResponseOrException<Promotion>> future = SettableFuture.create();

    getPromotions(startLatitude, startLongitude, endLatitude, endLongitude,
            new SettableFutureCallback<>(future));

    return transformFuture(future);
}

From source file:com.pingcap.tikv.RegionManager.java

private boolean putRegion(Region region) {
    if (!region.hasStartKey() || !region.hasEndKey())
        return false;

    SettableFuture<Region> regionFuture = SettableFuture.create();
    regionFuture.set(region);//  ww  w  .  java 2  s  . com
    regionCache.put(region.getId(), regionFuture);

    lock.writeLock().lock();
    try {
        keyToRegionIdCache.put(makeRange(region.getStartKey(), region.getEndKey()), region.getId());
    } finally {
        lock.writeLock().lock();
    }
    return true;
}

From source file:co.cask.cdap.explore.jdbc.MockExploreClient.java

@Override
public ListenableFuture<ExploreExecutionResult> schemas(@Nullable String catalog,
        @Nullable String schemaPattern) {
    SettableFuture<ExploreExecutionResult> futureDelegate = SettableFuture.create();
    futureDelegate.set(new MockExploreExecutionResult(statementsToResults.get("schemas_stmt").iterator(),
            statementsToMetadata.get("schemas_stmt")));
    return new MockStatementExecutionFuture(futureDelegate, "schemas_stmt", statementsToMetadata,
            statementsToResults);/*from w  w w.  jav  a 2 s . c  o  m*/
}

From source file:se.sics.sweep.webservice.SweepLaunch.java

private void connectComponents() {
    config = ConfigFactory.load();/*from   www.j a v  a 2 s  .  c o m*/

    SystemConfig systemConfig = new SystemConfig(config);
    GradientConfig gradientConfig = new GradientConfig(config);
    CroupierConfig croupierConfig = new CroupierConfig(config);
    ElectionConfig electionConfig = new ElectionConfig(config);
    ChunkManagerConfig chunkManagerConfig = new ChunkManagerConfig(config);

    timer = create(JavaTimer.class, Init.NONE);
    network = create(NettyNetwork.class, new NettyInit(systemConfig.self));

    //TODO Abhi - why aren't you building this applicationSelf in SearchPeer and instead risk me handing this reference to someone else - shared object problem
    ApplicationSelf applicationSelf = new ApplicationSelf(systemConfig.self);
    //TODO send to searchPeer to populate it so the RestAPI can start
    //TODO - make sure to set the settable future in the constructor of SearchPeer or else you will might deadlock
    SettableFuture<SweepSyncI> sweepSyncI = SettableFuture.create();
    searchPeer = create(SearchPeer.class,
            new SearchPeerInit(applicationSelf, systemConfig, croupierConfig, SearchConfiguration.build(),
                    GradientConfiguration.build(), ElectionConfiguration.build(), chunkManagerConfig,
                    gradientConfig, electionConfig));

    connect(timer.getPositive(Timer.class), searchPeer.getNegative(Timer.class));
    connect(network.getPositive(Network.class), searchPeer.getNegative(Network.class));

    sweepWS = new SweepWS(sweepSyncI);
}

From source file:io.airlift.discovery.client.CachingServiceSelector.java

private static <V> ListenableFuture<V> chainedCallback(ListenableFuture<V> future,
        final FutureCallback<? super V> callback, Executor executor) {
    final SettableFuture<V> done = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<V>() {
        @Override// ww w . j  a  v  a2  s.  c om
        public void onSuccess(V result) {
            try {
                callback.onSuccess(result);
            } finally {
                done.set(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            try {
                callback.onFailure(t);
            } finally {
                done.setException(t);
            }
        }
    }, executor);
    return done;
}

From source file:org.apache.twill.internal.container.TwillContainerService.java

@Override
public ListenableFuture<String> onReceived(final String messageId, final Message message) {
    LOG.debug("Message received: {} {}.", messageId, message);

    if (handleSecureStoreUpdate(message)) {
        return Futures.immediateFuture(messageId);
    }//from  www  .ja va 2s  .c o  m

    final SettableFuture<String> result = SettableFuture.create();
    Command command = message.getCommand();
    if (message.getType() == Message.Type.SYSTEM && "instances".equals(command.getCommand())
            && command.getOptions().containsKey("count")) {
        context.setInstanceCount(Integer.parseInt(command.getOptions().get("count")));
    }

    String commandStr = command.getCommand();
    if (message.getType() == Message.Type.SYSTEM) {
        boolean handled = false;
        if (SystemMessages.SET_LOG_LEVEL.equals(commandStr)) {
            // The options is a map from logger name to log level.
            setLogLevels(command.getOptions());
            handled = true;
        } else if (SystemMessages.RESET_LOG_LEVEL.equals(commandStr)) {
            // The options is a set of loggers to reset in the form of loggerName -> loggerName map.
            resetLogLevels(command.getOptions().keySet());
            handled = true;
        }

        if (handled) {
            updateLiveNode();
            return Futures.immediateFuture(messageId);
        }
    }

    commandExecutor.execute(new Runnable() {

        @Override
        public void run() {
            try {
                runnable.handleCommand(message.getCommand());
                result.set(messageId);
            } catch (Exception e) {
                result.setException(e);
            }
        }
    });
    return result;
}

From source file:io.crate.operation.fetch.NodeFetchOperation.java

public ListenableFuture<IntObjectMap<StreamBucket>> doFetch(final FetchContext fetchContext,
        @Nullable IntObjectMap<? extends IntContainer> toFetch) throws Exception {
    if (toFetch == null) {
        return Futures.<IntObjectMap<StreamBucket>>immediateFuture(new IntObjectHashMap<StreamBucket>(0));
    }//ww  w .  ja  v a 2  s. com

    final IntObjectHashMap<StreamBucket> fetched = new IntObjectHashMap<>(toFetch.size());
    HashMap<TableIdent, TableFetchInfo> tableFetchInfos = getTableFetchInfos(fetchContext);
    final AtomicReference<Throwable> lastThrowable = new AtomicReference<>(null);
    final AtomicInteger threadLatch = new AtomicInteger(toFetch.size());

    final SettableFuture<IntObjectMap<StreamBucket>> resultFuture = SettableFuture.create();
    for (IntObjectCursor<? extends IntContainer> toFetchCursor : toFetch) {
        final int readerId = toFetchCursor.key;
        final IntContainer docIds = toFetchCursor.value;

        TableIdent ident = fetchContext.tableIdent(readerId);
        final TableFetchInfo tfi = tableFetchInfos.get(ident);
        assert tfi != null;

        CollectRunnable runnable = new CollectRunnable(tfi.createCollector(readerId), docIds, fetched, readerId,
                lastThrowable, threadLatch, resultFuture);
        try {
            executor.execute(runnable);
        } catch (EsRejectedExecutionException | RejectedExecutionException e) {
            runnable.run();
        }
    }
    return resultFuture;
}

From source file:io.viewserver.network.netty.NettyNetworkAdapter.java

@Override
public ListenableFuture<IChannel> connect(IEndpoint endpoint) {
    SettableFuture<IChannel> promise = SettableFuture.create();
    final INettyEndpoint.IClient client = ((INettyEndpoint) endpoint).getClient(getClientWorkerGroup(),
            new NettyPipelineInitialiser(networkMessageWheel));
    ChannelFuture channelFuture = client.connect();
    channelFuture.addListener(new ChannelFutureListener() {
        @Override/*from   w  ww.j  av a  2  s .c  om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                NettyChannel channel = new NettyChannel(future.channel());
                promise.set(channel);
            } else {
                promise.setException(future.cause());
            }
        }
    });
    return promise;
}