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:org.opendaylight.openflowplugin.impl.services.SalTableServiceImpl.java

@Override
public Future<RpcResult<UpdateTableOutput>> updateTable(final UpdateTableInput input) {
    final ListenableFuture<RpcResult<List<MultipartReply>>> multipartFuture = handleServiceCall(input);
    final SettableFuture<RpcResult<UpdateTableOutput>> finalFuture = SettableFuture.create();

    class CallBackImpl implements FutureCallback<RpcResult<List<MultipartReply>>> {
        @Override//w w  w .ja  va2  s. c o  m
        public void onSuccess(final RpcResult<List<MultipartReply>> result) {

            if (result.isSuccessful()) {
                final List<MultipartReply> multipartReplies = result.getResult();
                if (multipartReplies.isEmpty()) {
                    LOG.debug("Multipart reply to table features request shouldn't be empty list.");
                    finalFuture.set(RpcResultBuilder.<UpdateTableOutput>failed()
                            .withError(ErrorType.RPC, "Multipart reply list is empty.").build());
                } else {
                    final Long xid = multipartReplies.get(0).getXid();
                    LOG.debug(
                            "OnSuccess, rpc result successful, multipart response for rpc update-table with xid {} obtained.",
                            xid);
                    final UpdateTableOutputBuilder updateTableOutputBuilder = new UpdateTableOutputBuilder();
                    updateTableOutputBuilder.setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
                    finalFuture.set(RpcResultBuilder.success(updateTableOutputBuilder.build()).build());
                    writeResponseToOperationalDatastore(multipartReplies);
                }
            } else {
                LOG.debug(
                        "OnSuccess, rpc result unsuccessful, multipart response for rpc update-table was unsuccessful.");
                finalFuture.set(
                        RpcResultBuilder.<UpdateTableOutput>failed().withRpcErrors(result.getErrors()).build());
            }
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.debug("Failure multipart response for table features request. Exception: {}", t);
            finalFuture.set(RpcResultBuilder.<UpdateTableOutput>failed()
                    .withError(ErrorType.RPC, "Future error", t).build());
        }
    }

    Futures.addCallback(multipartFuture, new CallBackImpl());

    return finalFuture;
}

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

/**
 * Delete an item from the local table and enqueue the operation to be
 * synchronized on context push./*from w w  w  . j a v a  2s  .  c  o  m*/
 *
 * @param itemId the id of the item to be deleted
 * @return A ListenableFuture that is done when the item has been deleted.
 */
public ListenableFuture<Void> delete(final String itemId) {
    final SettableFuture<Void> future = SettableFuture.create();

    ListenableFuture<Void> internalFuture = mInternalTable.delete(itemId);

    Futures.addCallback(internalFuture, new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable throwable) {
            future.setException(throwable);
        }

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

    return future;
}

From source file:com.github.jsdossier.RenderTaskExecutor.java

/**
 * Signals that no further tasks will be submitted and the executor should wait for existing tasks
 * to complete./*ww  w.j a  va2  s .c om*/
 *
 * @return a future that will resolve to a list of all rendered files.
 */
public ListenableFuture<List<Path>> awaitTermination() {
    executorService.shutdown();

    final SettableFuture<List<Path>> completedTasks = SettableFuture.create();
    final int numTasks = submittedTasks.size();
    FutureCallback<Path> callback = new FutureCallback<Path>() {
        private final AtomicBoolean loggedError = new AtomicBoolean(false);
        private final List<Path> completed = new ArrayList<>();

        @Override
        public synchronized void onSuccess(Path result) {
            completed.add(result);
            if (completed.size() >= numTasks) {
                completedTasks.set(completed);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            // Only log an error once since the hard shutdown will likely cause other failures.
            if (loggedError.compareAndSet(false, true)) {
                logger.log(Level.SEVERE, "An error occurred", t);
                completedTasks.setException(t);
            }
            executorService.shutdownNow();
        }
    };

    for (ListenableFuture<Path> task : submittedTasks) {
        Futures.addCallback(task, callback);
    }

    return transformAsync(completedTasks, new AsyncFunction<List<Path>, List<Path>>() {
        @Override
        public ListenableFuture<List<Path>> apply(@Nonnull List<Path> input) throws IOException {
            input.add(typeIndexTask.call());
            return Futures.immediateFuture(input);
        }
    }, directExecutor());
}

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

public Future<UserSubmissionStats> get() {
    final SettableFuture<UserSubmissionStats> future = SettableFuture.create();
    if (myUserEmail != null) {
        Firebase userStatsRef = new Firebase(Constants.getInstance().getFirebaseUrlForUserSubmissionStats())
                .child(myUserEmail).child(new SimpleDateFormat("MMddyyyy").format(new Date()).toString());

        userStatsRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override//from  www  . j a v a 2 s  .c om
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    UserSubmissionStats stats = dataSnapshot.getValue(UserSubmissionStats.class);
                    future.set(stats);
                } else {
                    future.set(new UserSubmissionStats());
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });
    }
    return future;
}

From source file:co.cask.cdap.internal.app.runtime.AbstractProgramController.java

@Override
public final ListenableFuture<ProgramController> command(final String name, final Object value) {
    final SettableFuture<ProgramController> result = SettableFuture.create();
    executor("command").execute(new Runnable() {

        @Override//from   w  w  w  .  ja  v a  2 s.co m
        public void run() {
            try {
                doCommand(name, value);
                result.set(AbstractProgramController.this);
            } catch (Throwable t) {
                error(t, result);
            }
        }
    });
    return result;
}

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

@Override
public void start() {
    if (subTasks.size() == 0) {
        ((SettableFuture) resultList.get(0)).set(RowCountResult.EMPTY_RESULT);
        return;/*from   ww w.  ja  v a2 s  .  c om*/
    } else if (forwardResultsFromSubTask) {
        // result list is bind to sub task results, no further action/listener required
        transportExecutor.execute(subTasks);
    } else {
        final SettableFuture<TaskResult> result = (SettableFuture) resultList.get(0);

        final List<ListenableFuture<TaskResult>> subTasksResult = transportExecutor.execute(subTasks);
        Futures.addCallback(Futures.allAsList(subTasksResult), new FutureCallback<List<TaskResult>>() {
            @Override
            public void onSuccess(@Nullable List<TaskResult> results) {
                if (results == null) {
                    result.setException(new NullPointerException());
                    return;
                }
                assert results.size() == 1 : "Last sub-task is expected to have 1 result only";
                result.set(new RowCountResult(
                        ((Number) results.get(0).rows().iterator().next().get(0)).longValue()));
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                if (t == null) {
                    t = new NullPointerException();
                }
                result.setException(t);
            }
        });

    }
}

From source file:com.github.xose.persona.verifier.RemoteVerifier.java

@Override
public ListenableFuture<VerifyResult> verify(String assertion, String audience) {
    final SettableFuture<VerifyResult> future = SettableFuture.create();

    Request request = new RequestBuilder("POST").setUrl(verifyUrl).addParameter("assertion", assertion)
            .addParameter("audience", audience).build();

    try {/*from  ww  w.  j av  a2s.c  om*/
        client.executeRequest(request, new AsyncCompletionHandler<Response>() {
            @Override
            public Response onCompleted(Response response) throws IOException {
                if (200 != response.getStatusCode()) {
                    future.setException(new Exception("HTTP Code " + response.getStatusCode()));
                    return response;
                }

                try {
                    future.set(VerifyResultParser.fromJSONString(response.getResponseBody()));
                } catch (Throwable e) {
                    future.setException(new Exception("JSON parsing error", e));
                }

                return response;
            }

            @Override
            public void onThrowable(Throwable t) {
                future.setException(t);
            }
        });
    } catch (IOException e) {
        future.setException(e);
    }

    return future;
}

From source file:com.google.cloud.dataflow.sdk.util.state.WindmillStateReader.java

private <T> void consumeTagList(TagList list, StateTag stateTag) {
    @SuppressWarnings("unchecked")
    SettableFuture<Iterable<T>> future = (SettableFuture<Iterable<T>>) futures.get(stateTag);
    if (future == null) {
        throw new IllegalStateException("Missing future for " + stateTag);
    } else if (future.isDone()) {
        LOG.error("Future for {} is already done", stateTag);
    }//from   ww w  .  j  a v a2  s.  co  m

    if (list.getValuesCount() == 0) {
        future.set(Collections.<T>emptyList());
        return;
    }

    @SuppressWarnings("unchecked")
    Coder<T> elemCoder = (Coder<T>) coders.remove(stateTag);
    if (elemCoder == null) {
        throw new IllegalStateException("Missing element coder for " + stateTag);
    }

    List<T> valueList = new ArrayList<>(list.getValuesCount());
    for (Windmill.Value value : list.getValuesList()) {
        if (value.hasData() && !value.getData().isEmpty()) {
            // Drop the first byte of the data; it's the zero byte we prependend to avoid writing
            // empty data.
            InputStream inputStream = value.getData().substring(1).newInput();
            try {
                valueList.add(elemCoder.decode(inputStream, Coder.Context.OUTER));
            } catch (IOException e) {
                throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e);
            }
        }
    }

    future.set(Collections.unmodifiableList(valueList));
}

From source file:io.v.todos.persistence.syncbase.SyncbasePersistence.java

/**
 * This constructor is blocking for simplicity.
 *//*from  w w w. j a va  2s  .co m*/
public SyncbasePersistence(final Activity activity, Bundle savedInstanceState)
        throws VException, SyncbaseServer.StartException {
    mVAndroidContext = VAndroidContexts.withDefaults(activity, savedInstanceState);

    FragmentManager mgr = activity.getFragmentManager();
    if (savedInstanceState == null) {
        FragmentTransaction t = mgr.beginTransaction();
        addFeatureFragments(mgr, t);
        t.commit();
    } else {
        addFeatureFragments(mgr, null);
    }

    // We might not actually have to seek blessings each time, but getBlessings does not
    // block if we already have blessings and this has better-behaved lifecycle
    // implications than trying to seek blessings in the static code.
    final SettableFuture<ListenableFuture<Blessings>> blessings = SettableFuture.create();
    if (activity.getMainLooper().getThread() == Thread.currentThread()) {
        blessings.set(BlessingsManager.getBlessings(getVContext(), activity, BLESSINGS_KEY, true));
    } else {
        new Handler(activity.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                blessings.set(BlessingsManager.getBlessings(getVContext(), activity, BLESSINGS_KEY, true));
            }
        });
    }

    VFutures.sync(Futures.dereference(blessings));
    appVInit(activity.getApplicationContext());
    final SyncbasePersistence self = this;
    /*final Future<?> ensureCloudDatabaseExists = sExecutor.submit(new Runnable() {
    @Override
    public void run() {
        ensureCloudDatabaseExists();
    }
    });*/
    ensureSyncbaseStarted(activity);
    ensureDatabaseExists();
    ensureUserCollectionExists();
    // TODO(alexfandrianto): If the cloud is dependent on me, then we must do this too.
    // VFutures.sync(ensureCloudDatabaseExists); // must finish before syncgroup setup
    ensureUserSyncgroupExists();
    Sharing.initDiscovery(sDatabase); // requires that db and collection exist
    sInitialized = true;
}

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//ww  w  . j a  v a2 s .  c  o m
        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;
}