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:io.prestosql.operator.Driver.java

private ListenableFuture<?> updateDriverBlockedFuture(ListenableFuture<?> sourceBlockedFuture) {
    // driverBlockedFuture will be completed as soon as the sourceBlockedFuture is completed
    // or any of the operators gets a memory revocation request
    SettableFuture<?> newDriverBlockedFuture = SettableFuture.create();
    driverBlockedFuture.set(newDriverBlockedFuture);
    sourceBlockedFuture.addListener(() -> newDriverBlockedFuture.set(null), directExecutor());

    // it's possible that memory revoking is requested for some operator
    // before we update driverBlockedFuture above and we don't want to miss that
    // notification, so we check to see whether that's the case before returning.
    boolean memoryRevokingRequested = activeOperators.stream()
            .filter(operator -> !revokingOperators.containsKey(operator)).map(Operator::getOperatorContext)
            .anyMatch(OperatorContext::isMemoryRevokingRequested);

    if (memoryRevokingRequested) {
        newDriverBlockedFuture.set(null);
    }//w w w.j a  v  a  2 s .c o  m

    return newDriverBlockedFuture;
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncTable.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.
 *//*from   w  ww  .  j  a  v  a  2s .  c  om*/
public ListenableFuture<E> lookUp(String itemId) {
    final SettableFuture<E> future = SettableFuture.create();

    ListenableFuture<JsonObject> internalFuture = mInternalTable.lookUp(itemId);
    Futures.addCallback(internalFuture, new FutureCallback<JsonObject>() {
        @Override
        public void onFailure(Throwable throwable) {
            future.setException(throwable);
        }

        @Override
        public void onSuccess(JsonObject result) {
            try {

                if (result == null) {
                    future.set(null);
                }

                future.set(parseResults(result).get(0));
            } catch (Exception e) {
                future.setException(e);
            }
        }
    });

    return future;
}

From source file:org.opendaylight.controller.cluster.datastore.admin.ClusterAdminRpcService.java

@Override
public Future<RpcResult<Void>> addShardReplica(final AddShardReplicaInput input) {
    final String shardName = input.getShardName();
    if (Strings.isNullOrEmpty(shardName)) {
        return newFailedRpcResultFuture("A valid shard name must be specified");
    }//from   w  w  w.j a va  2s  .  c om

    DataStoreType dataStoreType = input.getDataStoreType();
    if (dataStoreType == null) {
        return newFailedRpcResultFuture("A valid DataStoreType must be specified");
    }

    LOG.info("Adding replica for shard {}", shardName);

    final SettableFuture<RpcResult<Void>> returnFuture = SettableFuture.create();
    ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType, new AddShardReplica(shardName));
    Futures.addCallback(future, new FutureCallback<Success>() {
        @Override
        public void onSuccess(Success success) {
            LOG.info("Successfully added replica for shard {}", shardName);
            returnFuture.set(newSuccessfulResult());
        }

        @Override
        public void onFailure(Throwable failure) {
            onMessageFailure(String.format("Failed to add replica for shard %s", shardName), returnFuture,
                    failure);
        }
    });

    return returnFuture;
}

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

/**
 * Update an item in the local table and enqueue the operation to be
 * synchronized on context push./* ww  w .j av  a 2  s. c o m*/
 *
 * @param item the item to be updated
 * @return A ListenableFuture that is done when the item has been updated.
 */
public ListenableFuture<Void> update(E item) {
    final SettableFuture<Void> future = SettableFuture.create();

    JsonObject json = mClient.getGsonBuilder().create().toJsonTree(item).getAsJsonObject();

    ListenableFuture<Void> internalFuture = mInternalTable.update(json);

    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.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   ww w  . j  a  v  a2 s.  co m
 *
 * @param item the item to be deleted
 * @return A ListenableFuture that is done when the item has been deleted.
 */
public ListenableFuture<Void> delete(E item) {
    final SettableFuture<Void> future = SettableFuture.create();

    JsonObject json = mClient.getGsonBuilder().create().toJsonTree(item).getAsJsonObject();

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

    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:co.cask.cdap.internal.app.runtime.AbstractProgramController.java

@Override
public final ListenableFuture<ProgramController> suspend() {
    if (!state.compareAndSet(State.ALIVE, State.SUSPENDING)) {
        return Futures
                .immediateFailedFuture(new IllegalStateException("Suspension not allowed").fillInStackTrace());
    }// w w  w  .ja  v a2s. c  om
    final SettableFuture<ProgramController> result = SettableFuture.create();
    executor(State.SUSPENDING).execute(new Runnable() {
        @Override
        public void run() {
            try {
                caller.suspending();
                doSuspend();
                state.set(State.SUSPENDED);
                result.set(AbstractProgramController.this);
                caller.suspended();
            } catch (Throwable t) {
                error(t, result);
            }
        }
    });

    return result;
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java

@SuppressWarnings("FutureReturnValueIgnored")
private void getAfterCredentialRefresh(DownloadCommand cmd, SettableFuture<Boolean> outerF) {
    acquireDownloadChannel().addListener((Future<Channel> chP) -> {
        if (!chP.isSuccess()) {
            outerF.setException(chP.cause());
            return;
        }//  w  w w. j a v  a  2s  .  co  m

        Channel ch = chP.getNow();
        ch.writeAndFlush(cmd).addListener((f) -> {
            try {
                if (f.isSuccess()) {
                    outerF.set(true);
                } else {
                    Throwable cause = f.cause();
                    if (cause instanceof HttpException) {
                        HttpResponse response = ((HttpException) cause).response();
                        if (cacheMiss(response.status())) {
                            outerF.set(false);
                            return;
                        }
                    }
                    outerF.setException(cause);
                }
            } finally {
                releaseDownloadChannel(ch);
            }
        });
    });
}

From source file:com.google.devtools.build.lib.remote.AbstractRemoteActionCache.java

/**
 * Download a file (that is not a directory). If the {@code content} is not given, the content is
 * fetched from the digest.//www . j  a va 2s. c om
 */
public ListenableFuture<Void> downloadFile(Path path, Digest digest, @Nullable ByteString content)
        throws IOException {
    Preconditions.checkNotNull(path.getParentDirectory()).createDirectoryAndParents();
    if (digest.getSizeBytes() == 0) {
        // Handle empty file locally.
        FileSystemUtils.writeContent(path, new byte[0]);
        return COMPLETED_SUCCESS;
    }

    if (content != null && !content.isEmpty()) {
        try (OutputStream stream = path.getOutputStream()) {
            content.writeTo(stream);
        }
        return COMPLETED_SUCCESS;
    }

    OutputStream out = new LazyFileOutputStream(path);
    SettableFuture<Void> outerF = SettableFuture.create();
    ListenableFuture<Void> f = downloadBlob(digest, out);
    Futures.addCallback(f, new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            try {
                out.close();
                outerF.set(null);
            } catch (IOException e) {
                outerF.setException(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            outerF.setException(t);
            try {
                out.close();
            } catch (IOException e) {
                // Intentionally left empty. The download already failed, so we can ignore
                // the error on close().
            }
        }
    }, MoreExecutors.directExecutor());
    return outerF;
}

From source file:org.opendaylight.controller.md.statistics.manager.impl.StatRpcMsgManagerImpl.java

@Override
public Future<Boolean> isExpectedStatistics(final TransactionId id, final NodeId nodeId) {
    Preconditions.checkArgument(id != null, "TransactionId can not be null!");
    Preconditions.checkArgument(nodeId != null, "NodeId can not be null!");

    final String key = buildCacheKey(id, nodeId);
    final SettableFuture<Boolean> checkStatId = SettableFuture.create();

    final RpcJobsQueue isExpecedStatistics = new RpcJobsQueue() {

        @Override/*from w w  w  .  j  a v  a 2  s  .com*/
        public Void call() throws Exception {
            final Optional<TransactionCacheContainer<?>> result = Optional
                    .<TransactionCacheContainer<?>>fromNullable(txCache.getIfPresent(key));
            checkStatId.set(Boolean.valueOf(result.isPresent()));
            return null;
        }
    };
    addStatJob(isExpecedStatistics);
    return checkStatId;
}

From source file:org.opendaylight.vpnservice.itm.rpc.ItmManagerRpcService.java

@Override
public Future<RpcResult<Void>> removeExternalTunnelEndpoint(RemoveExternalTunnelEndpointInput input) {
    //Ignore the Futures for now
    final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
    List<DPNTEPsInfo> meshedDpnList = ItmUtils.getTunnelMeshInfo(dataBroker);
    ItmExternalTunnelDeleteWorker.deleteTunnels(dataBroker, idManagerService, meshedDpnList,
            input.getDestinationIp(), input.getTunnelType());
    result.set(RpcResultBuilder.<Void>success().build());
    return result;
}