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:edu.umich.si.inteco.minuku.dao.ImageDataRecordDAO.java

@Override
public Future<List<ImageDataRecord>> getAll() throws DAOException {
    final SettableFuture<List<ImageDataRecord>> settableFuture = SettableFuture.create();
    Firebase imageListRef = new Firebase(Constants.getInstance().getFirebaseUrlForImages()).child(myUserEmail)
            .child(new SimpleDateFormat("MMddyyyy").format(new Date()).toString());

    imageListRef.addValueEventListener(new ValueEventListener() {
        @Override/* ww  w .  j a  v  a 2  s. c  o  m*/
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, ImageDataRecord> imageListMap = (HashMap<String, ImageDataRecord>) dataSnapshot
                    .getValue();
            List<ImageDataRecord> values = (List) imageListMap.values();
            settableFuture.set(values);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            settableFuture.set(null);
        }
    });
    return settableFuture;
}

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

@Override
public ListenableFuture<ExploreExecutionResult> submit(Id.Namespace namespace, final String statement) {
    SettableFuture<ExploreExecutionResult> futureDelegate = SettableFuture.create();
    futureDelegate.set(new MockExploreExecutionResult(statementsToResults.get(statement).iterator(),
            statementsToMetadata.get(statement)));
    return new MockStatementExecutionFuture(futureDelegate, statement, statementsToMetadata,
            statementsToResults);//  w w  w  . j a  v  a  2s . co  m
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncTable.java

/**
 * Performs a query against the remote table and stores results.
 *
 * @param query    an optional query to filter results
 * @param queryKey key to identify the query
 * @return A ListenableFuture that is done when results have been pulled.
 *//*from   w w w .  j  a va  2s.  c o  m*/
public ListenableFuture<Void> pull(Query query, String queryId) {
    ListenableFuture<Void> pull = this.mInternalTable.pull(query, queryId);

    final SettableFuture<Void> result = SettableFuture.create();

    Futures.addCallback(pull, new FutureCallback<Void>() {

        @Override
        public void onFailure(Throwable throwable) {
            result.setException(throwable);
        }

        @Override
        public void onSuccess(Void value) {
            result.set(value);
        }
    });

    return result;
}

From source file:com.dogecoin.dogecoinj.net.BlockingClient.java

/**
 * <p>Creates a new client to the given server address using the given {@link StreamParser} to decode the data.
 * The given parser <b>MUST</b> be unique to this object. This does not block while waiting for the connection to
 * open, but will call either the {@link StreamParser#connectionOpened()} or
 * {@link StreamParser#connectionClosed()} callback on the created network event processing thread.</p>
 *
 * @param connectTimeoutMillis The connect timeout set on the connection (in milliseconds). 0 is interpreted as no
 *                             timeout./*from   w w  w  .  jav  a 2  s  .c o  m*/
 * @param socketFactory An object that creates {@link Socket} objects on demand, which may be customised to control
 *                      how this client connects to the internet. If not sure, use SocketFactory.getDefault()
 * @param clientSet A set which this object will add itself to after initialization, and then remove itself from
 */
public BlockingClient(final SocketAddress serverAddress, final StreamParser parser,
        final int connectTimeoutMillis, final SocketFactory socketFactory,
        @Nullable final Set<BlockingClient> clientSet) throws IOException {
    connectFuture = SettableFuture.create();
    // Try to fit at least one message in the network buffer, but place an upper and lower limit on its size to make
    // sure it doesnt get too large or have to call read too often.
    dbuf = ByteBuffer.allocateDirect(
            Math.min(Math.max(parser.getMaxMessageSize(), BUFFER_SIZE_LOWER_BOUND), BUFFER_SIZE_UPPER_BOUND));
    parser.setWriteTarget(this);
    socket = socketFactory.createSocket();
    Thread t = new Thread() {
        @Override
        public void run() {
            if (clientSet != null)
                clientSet.add(BlockingClient.this);
            try {
                socket.connect(serverAddress, connectTimeoutMillis);
                parser.connectionOpened();
                connectFuture.set(serverAddress);
                InputStream stream = socket.getInputStream();
                byte[] readBuff = new byte[dbuf.capacity()];

                while (true) {
                    // TODO Kill the message duplication here
                    checkState(dbuf.remaining() > 0 && dbuf.remaining() <= readBuff.length);
                    int read = stream.read(readBuff, 0,
                            Math.max(1, Math.min(dbuf.remaining(), stream.available())));
                    if (read == -1)
                        return;
                    dbuf.put(readBuff, 0, read);
                    // "flip" the buffer - setting the limit to the current position and setting position to 0
                    dbuf.flip();
                    // Use parser.receiveBytes's return value as a double-check that it stopped reading at the right
                    // location
                    int bytesConsumed = parser.receiveBytes(dbuf);
                    checkState(dbuf.position() == bytesConsumed);
                    // Now drop the bytes which were read by compacting dbuf (resetting limit and keeping relative
                    // position)
                    dbuf.compact();
                }
            } catch (Exception e) {
                if (!vCloseRequested) {
                    log.error("Error trying to open/read from connection: " + serverAddress, e);
                    connectFuture.setException(e);
                }
            } finally {
                try {
                    socket.close();
                } catch (IOException e1) {
                    // At this point there isn't much we can do, and we can probably assume the channel is closed
                }
                if (clientSet != null)
                    clientSet.remove(BlockingClient.this);
                parser.connectionClosed();
            }
        }
    };
    t.setName("BlockingClient network thread for " + serverAddress);
    t.setDaemon(true);
    t.start();
}

From source file:com.continuuity.weave.internal.ZKWeaveController.java

@Override
public ListenableFuture<State> stop() {
    final SettableFuture<State> result = SettableFuture.create();
    final ListenableFuture<State> future = super.stop();
    future.addListener(new Runnable() {
        @Override//from  www.  java2s .  c  o m
        public void run() {
            logPoller.interrupt();
            try {
                logPoller.join();
            } catch (InterruptedException e) {
                LOG.warn("Joining of log poller thread interrupted.", e);
            }
            Futures.addCallback(kafkaClient.stop(), new FutureCallback<Service.State>() {
                @Override
                public void onSuccess(Service.State state) {
                    try {
                        future.get();
                        result.set(State.TERMINATED);
                    } catch (Exception e) {
                        LOG.error("Failed when stopping local services", e);
                        result.setException(e);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    result.setException(t);
                }
            });
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    return result;
}

From source file:com.linecorp.armeria.internal.grpc.StreamRecorder.java

private StreamRecorder() {
    firstValue = SettableFuture.create();
    latch = new CountDownLatch(1);
    results = Collections.synchronizedList(new ArrayList<T>());
}

From source file:org.apache.beam.runners.fnexecution.control.FnApiControlClient.java

public synchronized ListenableFuture<BeamFnApi.InstructionResponse> handle(
        BeamFnApi.InstructionRequest request) {
    LOG.debug("Sending InstructionRequest {}", request);
    SettableFuture<BeamFnApi.InstructionResponse> resultFuture = SettableFuture.create();
    outstandingRequests.put(request.getInstructionId(), resultFuture);
    requestReceiver.onNext(request);/*from   w  w  w  . ja  v a  2  s  .  com*/
    return resultFuture;
}

From source file:io.joynr.messaging.http.operation.LongPollingMessageReceiver.java

@Override
public synchronized Future<Void> start(MessageArrivedListener messageListener,
        ReceiverStatusListener... receiverStatusListeners) {
    synchronized (shutdownSynchronizer) {
        if (shutdown) {
            throw new JoynrShutdownException("Cannot register Message Listener: " + messageListener
                    + ": LongPollingMessageReceiver is already shutting down");
        }/*from  w w  w .  ja  v a  2  s .com*/
    }

    if (isStarted()) {
        return Futures.immediateFailedFuture(new IllegalStateException("receiver is already started"));
    }

    final SettableFuture<Void> channelCreatedFuture = SettableFuture.create();
    ReceiverStatusListener[] statusListeners = ObjectArrays.concat(new ReceiverStatusListener() {

        @Override
        // Register the ChannelUrl once the receiver is started
        public void receiverStarted() {
            if (channelMonitor.isChannelCreated()) {
                for (ChannelCreatedListener listener : channelCreatedListeners) {
                    listener.channelCreated(channelMonitor.getChannelUrl());
                }
                // Signal that the channel is now created for anyone blocking on the future
                channelCreatedFuture.set(null);
            }
        }

        @Override
        // Shutdown the receiver if an exception is thrown
        public void receiverException(Throwable e) {
            channelCreatedFuture.setException(e);
            channelMonitor.shutdown();
        }
    }, receiverStatusListeners);

    channelMonitor.startLongPolling(messageListener, statusListeners);
    return channelCreatedFuture;
}

From source file:de.btobastian.javacord.utils.DiscordWebsocket.java

/**
 * Creates a new instance of this class.
 *
 * @param serverURI The uri of the gateway the socket should connect to.
 * @param api The api./*ww w  .j  a  v  a2  s . c o m*/
 * @param reconnect Whether it's a reconnect or not.
 */
public DiscordWebsocket(URI serverURI, ImplDiscordAPI api, boolean reconnect) {
    super(serverURI);
    this.api = api;
    this.ready = SettableFuture.create();
    registerHandlers();
    this.isReconnect = reconnect;
}

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

@Override
public Future<List<T>> getAll() throws DAOException {
    final SettableFuture<List<T>> settableFuture = SettableFuture.create();
    Firebase imageListRef = new Firebase(mFirebaseUrl).child(mUserEmail)
            .child(new SimpleDateFormat("MMddyyyy").format(new Date()).toString());

    imageListRef.addValueEventListener(new ValueEventListener() {
        @Override/* www  . j a  va2  s  .c o  m*/
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, T> imageListMap = (HashMap<String, T>) dataSnapshot.getValue();
            List<T> values = (List) imageListMap.values();
            settableFuture.set(values);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            settableFuture.set(null);
        }
    });
    return settableFuture;
}