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

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

Introduction

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

Prototype

@Override
    public boolean set(@Nullable V value) 

Source Link

Usage

From source file:c5db.control.SimpleControlClient.java

public ListenableFuture<CommandReply> sendRequest(CommandRpcRequest<?> request,
        InetSocketAddress remoteAddress) {
    SettableFuture<CommandReply> replyMessageFuture = SettableFuture.create();
    ChannelFuture connectFuture = client.connect(remoteAddress);
    connectFuture.addListener(new ChannelFutureListener() {
        @Override/*from   w  w w. ja  v  a  2 s  . co  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().pipeline().addLast(new SimpleChannelInboundHandler<CommandReply>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, CommandReply msg) throws Exception {
                        replyMessageFuture.set(msg);
                        ctx.channel().close();
                    }
                });

                // connected is fine, flush message:
                future.channel().writeAndFlush(request);
            } else {
                replyMessageFuture.setException(future.cause());
                future.channel().close();
            }
        }
    });

    return replyMessageFuture;
}

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

/**
 * Looks up an item from the local table.
 *
 * @param itemId the id of the item to look up
 * @return A ListenableFuture that is done when the item has been looked up.
 *//*w w  w  .  j a v a2  s.  c  o m*/
public ListenableFuture<JsonObject> lookUp(final String itemId) {
    final MobileServiceJsonSyncTable thisTable = this;
    final SettableFuture<JsonObject> result = SettableFuture.create();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                JsonObject item = thisTable.lookUpContext(itemId);

                result.set(item);
            } catch (Throwable throwable) {
                result.setException(throwable);
            }
        }
    }).start();

    return result;
}

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

/**
 * Insert an item into the local table and enqueue the operation to be
 * synchronized on context push.// ww w  . j a va  2  s  .  c  o  m
 *
 * @param item the item to be inserted
 * @return A ListenableFuture that is done when the item has been inserted,
 * returning a copy of the inserted item including id.
 */
public ListenableFuture<JsonObject> insert(final JsonObject item) {
    final MobileServiceJsonSyncTable thisTable = this;
    final SettableFuture<JsonObject> result = SettableFuture.create();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                JsonObject newItem = thisTable.insertContext(item);

                result.set(newItem);
            } catch (Throwable throwable) {
                result.setException(throwable);
            }
        }
    }).start();

    return result;
}

From source file:io.crate.executor.transport.task.SymbolBasedUpsertByIdTask.java

private List<ListenableFuture<TaskResult>> initializeBulkShardProcessor(Settings settings) {
    bulkShardProcessor = new SymbolBasedBulkShardProcessor(clusterService, settings,
            transportShardUpsertActionDelegate, transportCreateIndexAction, node.isPartitionedTable(), false, // overwrite Duplicates
            node.items().size(), node.isBulkRequest() || node.updateColumns() != null, // continue on error on bulk and/or update
            node.updateColumns(), node.insertColumns());

    if (!node.isBulkRequest()) {
        final SettableFuture<TaskResult> futureResult = SettableFuture.create();
        List<ListenableFuture<TaskResult>> resultList = new ArrayList<>(1);
        resultList.add(futureResult);// w ww.ja v a  2s  .c  o m
        Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
            @Override
            public void onSuccess(@Nullable BitSet result) {
                if (result == null) {
                    futureResult.set(TaskResult.ROW_COUNT_UNKNOWN);
                } else {
                    futureResult.set(new RowCountResult(result.cardinality()));
                }
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                futureResult.setException(t);
            }
        });
        return resultList;
    } else {
        final int numResults = node.items().size();
        final List<ListenableFuture<TaskResult>> resultList = new ArrayList<>(numResults);
        for (int i = 0; i < numResults; i++) {
            resultList.add(SettableFuture.<TaskResult>create());
        }

        Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
            @Override
            public void onSuccess(@Nullable BitSet result) {
                if (result == null) {
                    setAllToFailed(null);
                    return;
                }

                for (int i = 0; i < numResults; i++) {
                    SettableFuture<TaskResult> future = (SettableFuture<TaskResult>) resultList.get(i);
                    future.set(result.get(i) ? TaskResult.ONE_ROW : TaskResult.FAILURE);
                }
            }

            private void setAllToFailed(@Nullable Throwable throwable) {
                if (throwable == null) {
                    for (ListenableFuture<TaskResult> future : resultList) {
                        ((SettableFuture<TaskResult>) future).set(TaskResult.FAILURE);
                    }
                } else {
                    for (ListenableFuture<TaskResult> future : resultList) {
                        ((SettableFuture<TaskResult>) future).set(RowCountResult.error(throwable));
                    }
                }
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                setAllToFailed(t);
            }
        });
        return resultList;
    }
}

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

/**
 * Retrieve results from the local table.
 *
 * @param query an optional query to filter results
 * @return A ListenableFuture that is done when the results have been
 * retrieved./*from www  .  j a va 2 s.  c om*/
 */
public ListenableFuture<JsonElement> read(final Query query) {
    final MobileServiceJsonSyncTable thisTable = this;
    final SettableFuture<JsonElement> result = SettableFuture.create();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                JsonElement results = thisTable.readContext(query);

                result.set(results);
            } catch (Throwable throwable) {
                result.setException(throwable);
            }
        }
    }).start();

    return result;
}

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

private final void getLastNValues(final int N, final String userEmail, final Date someDate,
        final List<MoodDataRecord> synchronizedListOfRecords, final SettableFuture settableFuture) {
    Firebase firebaseRef = new Firebase(Constants.getInstance().getFirebaseUrlForMoods()).child(userEmail)
            .child(new SimpleDateFormat("MMddyyyy").format(someDate).toString());

    Log.d(TAG, "Checking the value of N " + N);

    if (N <= 0) {
        // The first element in the list is actually the last in the database.
        // Reverse the list before setting the future with a result.
        Collections.reverse(synchronizedListOfRecords);

        settableFuture.set(synchronizedListOfRecords);
        return;//from   ww  w .j  a va2s .c om
    }

    firebaseRef.limitToLast(N).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int newN = N;

            // dataSnapshot.exists returns false when the
            // <root>/<datarecord>/<userEmail>/<date> location does not exist.
            // What it means is that no entries were added for this date, i.e.
            // all the historic information has been exhausted.
            if (!dataSnapshot.exists()) {
                // The first element in the list is actually the last in the database.
                // Reverse the list before setting the future with a result.
                Collections.reverse(synchronizedListOfRecords);

                settableFuture.set(synchronizedListOfRecords);
                return;
            }

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                synchronizedListOfRecords.add(snapshot.getValue(MoodDataRecord.class));
                newN--;
            }
            Date newDate = new Date(someDate.getTime() - 26 * 60 * 60 * 1000); /* -1 Day */
            getLastNValues(newN, userEmail, newDate, synchronizedListOfRecords, settableFuture);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            /* TODO(neerajkumar): Get this f***up fixed! */

            // The first element in the list is actually the last in the database.
            // Reverse the list before setting the future with a result.
            Collections.reverse(synchronizedListOfRecords);

            // This would mean that the firebase ref does not exist thereby meaning that
            // the number of entries for all dates are over before we could get the last N
            // results
            settableFuture.set(synchronizedListOfRecords);
        }
    });
}

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

/**
 * Performs a query against the local table and deletes the results.
 *
 * @param query an optional query to filter results
 * @return A ListenableFuture that is done when results have been purged.
 *///from   w  w w .ja va2  s  .com
public ListenableFuture<Void> purge(final Query query) {
    final MobileServiceJsonSyncTable thisTable = this;
    final SettableFuture<Void> result = SettableFuture.create();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                thisTable.mClient.getSyncContext().purge(thisTable.mName, query);

                result.set(null);
            } catch (Throwable throwable) {
                result.setException(throwable);
            }
        }
    }).start();

    return result;
}

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

public final void getLastNValues(final int N, final String userEmail, final Date someDate,
        final List<T> synchronizedListOfRecords, final SettableFuture settableFuture,
        final String databaseURL) {
    Firebase firebaseRef = new Firebase(databaseURL).child(userEmail)
            .child(new SimpleDateFormat("MMddyyyy").format(someDate).toString());

    Log.d(TAG, "Checking the value of N " + N);

    if (N <= 0) {
        // The first element in the list is actually the last in the database.
        // Reverse the list before setting the future with a result.
        Collections.reverse(synchronizedListOfRecords);

        settableFuture.set(synchronizedListOfRecords);
        return;/*from   w w w.  j av a  2s.  c o m*/
    }

    firebaseRef.limitToLast(N).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int newN = N;

            // dataSnapshot.exists returns false when the
            // <root>/<datarecord>/<userEmail>/<date> location does not exist.
            // What it means is that no entries were added for this date, i.e.
            // all the historic information has been exhausted.
            if (!dataSnapshot.exists()) {
                // The first element in the list is actually the last in the database.
                // Reverse the list before setting the future with a result.
                Collections.reverse(synchronizedListOfRecords);

                settableFuture.set(synchronizedListOfRecords);
                return;
            }

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                synchronizedListOfRecords.add(snapshot.getValue(mDataRecordType));
                newN--;
            }
            Date newDate = new Date(someDate.getTime() - 26 * 60 * 60 * 1000); /* -1 Day */
            getLastNValues(newN, userEmail, newDate, synchronizedListOfRecords, settableFuture, databaseURL);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            /* TODO(neerajkumar): Get this f***up fixed! */

            // The first element in the list is actually the last in the database.
            // Reverse the list before setting the future with a result.
            Collections.reverse(synchronizedListOfRecords);

            // This would mean that the firebase ref does not exist thereby meaning that
            // the number of entries for all dates are over before we could get the last N
            // results
            settableFuture.set(synchronizedListOfRecords);
        }
    });
}

From source file:com.facebook.presto.operator.OperatorContext.java

public void reserveMemory(long bytes) {
    ListenableFuture<?> future = driverContext.reserveMemory(bytes);
    if (!future.isDone()) {
        SettableFuture<?> currentMemoryFuture = memoryFuture.get();
        while (currentMemoryFuture.isDone()) {
            SettableFuture<?> settableFuture = SettableFuture.create();
            // We can't replace one that's not done, because the task may be blocked on that future
            if (memoryFuture.compareAndSet(currentMemoryFuture, settableFuture)) {
                currentMemoryFuture = settableFuture;
            } else {
                currentMemoryFuture = memoryFuture.get();
            }//w  w w  . j  a  va2  s.c om
        }

        SettableFuture<?> finalMemoryFuture = currentMemoryFuture;
        // Create a new future, so that this operator can un-block before the pool does, if it's moved to a new pool
        Futures.addCallback(future, new FutureCallback<Object>() {
            @Override
            public void onSuccess(Object result) {
                finalMemoryFuture.set(null);
            }

            @Override
            public void onFailure(Throwable t) {
                finalMemoryFuture.set(null);
            }
        });
    }
    long newReservation = memoryReservation.addAndGet(bytes);
    if (newReservation > maxMemoryReservation) {
        memoryReservation.getAndAdd(-bytes);
        throw exceededLocalLimit(new DataSize(maxMemoryReservation, BYTE));
    }
}

From source file:org.apache.storm.cassandra.executor.AsyncExecutor.java

/**
 * Asynchronously executes the specified batch statement. Inputs will be passed to
 * the {@link #handler} once query succeed or failed.
 *//*from  w  ww  .  j  av  a 2  s .  com*/
public SettableFuture<T> execAsync(final Statement statement, final T inputs,
        final AsyncResultHandler<T> handler) {
    final SettableFuture<T> settableFuture = SettableFuture.create();
    pending.incrementAndGet();
    ResultSetFuture future = session.executeAsync(statement);
    Futures.addCallback(future, new FutureCallback<ResultSet>() {
        public void release() {
            pending.decrementAndGet();
        }

        @Override
        public void onSuccess(ResultSet result) {
            release();
            settableFuture.set(inputs);
            handler.success(inputs);
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error(String.format("Failed to execute statement '%s' ", statement), t);
            release();
            settableFuture.setException(t);
            handler.failure(t, inputs);
        }
    }, executorService);
    return settableFuture;
}