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.groupon.mesos.executor.ExecutorDriverContext.java

synchronized ListenableFuture<Status> waitForStateChange(final Status expectedStatus) {
    final SettableFuture<Status> future = SettableFuture.create();
    if (!isStateMachine(expectedStatus)) {
        // Current status is not the expected status. Return
        // it immediately.
        future.set(stateMachine.get());// ww w.j ava 2  s.  c  o m
    } else {
        // Current status is expected status: Queue up for a status change.
        stateMachineFutures.add(future);
    }
    return future;
}

From source file:io.grpc.cronet.CronetClientTransport.java

@Override
public ListenableFuture<TransportStats> getStats() {
    SettableFuture<TransportStats> f = SettableFuture.create();
    f.set(null);
    return f;
}

From source file:com.microsoft.office365.starter.helpers.AuthenticationController.java

/**
 * Description: Calls AuthenticationContext.acquireToken(...) once to initialize with
 * user's credentials and avoid interactive prompt on later calls.
 * If all tokens expire, app must call initialize() again to prompt user interactively and
 * set up authentication context./*  w w w  .  ja v a 2 s. c o  m*/
 *
 * @return A signal to wait on before continuing execution.
 */
public SettableFuture<Boolean> initialize() {

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

    if (verifyAuthenticationContext()) {
        getAuthenticationContext().acquireToken(this.contextActivity, this.resourceId, Constants.CLIENT_ID,
                Constants.REDIRECT_URI, PromptBehavior.Auto,
                new AuthenticationCallback<AuthenticationResult>() {

                    @Override
                    public void onSuccess(final AuthenticationResult authenticationResult) {

                        if (authenticationResult != null
                                && authenticationResult.getStatus() == AuthenticationStatus.Succeeded) {
                            dependencyResolver = new ADALDependencyResolver(getAuthenticationContext(),
                                    resourceId, Constants.CLIENT_ID);
                            storeUserId(contextActivity, authenticationResult);
                            result.set(true);
                        }
                    }

                    @Override
                    public void onError(Exception t) {
                        result.setException(t);
                    }

                    private void storeUserId(final Activity rootActivity,
                            final AuthenticationResult authenticationResult) {

                        UserInfo userInfo = authenticationResult.getUserInfo();
                        SharedPreferences sharedPref = rootActivity.getPreferences(Context.MODE_PRIVATE);

                        if (userInfo != null) {
                            mLoggedInUser = userInfo.getUserId();
                            Editor editor = sharedPref.edit();
                            editor.putString("UserId", mLoggedInUser);
                            editor.putString("DisplayName",
                                    userInfo.getGivenName() + " " + userInfo.getFamilyName());
                            editor.apply();
                        } else {
                            mLoggedInUser = sharedPref.getString("UserId", "");
                        }
                    }
                });
    } else {
        result.setException(new Throwable("Auth context verification failed. Did you set a context activity?"));
    }
    return result;
}

From source file:org.opendaylight.netvirt.vpnmanager.VpnRpcServiceImpl.java

/**
 * Generate label for the given ip prefix from the associated VPN.
 *//*  www .  j  a va2 s .  c om*/
@Override
public Future<RpcResult<GenerateVpnLabelOutput>> generateVpnLabel(GenerateVpnLabelInput input) {
    String vpnName = input.getVpnName();
    String ipPrefix = input.getIpPrefix();
    SettableFuture<RpcResult<GenerateVpnLabelOutput>> futureResult = SettableFuture.create();
    String rd = VpnUtil.getVpnRd(dataBroker, vpnName);
    long label = VpnUtil.getUniqueId(idManager, VpnConstants.VPN_IDPOOL_NAME,
            VpnUtil.getNextHopLabelKey((rd != null) ? rd : vpnName, ipPrefix));
    if (label == 0) {
        String msg = "Could not retrieve the label for prefix " + ipPrefix + " in VPN " + vpnName;
        LOG.error(msg);
        futureResult.set(RpcResultBuilder.<GenerateVpnLabelOutput>failed().withError(ErrorType.APPLICATION, msg)
                .build());
    } else {
        GenerateVpnLabelOutput output = new GenerateVpnLabelOutputBuilder().setLabel(label).build();
        futureResult.set(RpcResultBuilder.success(output).build());
    }
    return futureResult;
}

From source file:com.navercorp.nbasearc.gcp.GatewayConnectionPool.java

private SettableFuture<?> closeVirtualConnections() {
    final SettableFuture<?> future = SettableFuture.create();

    if (vcConcurrentSet.isEmpty()) {
        future.set(null);/*w ww. j a v a  2  s . c  o  m*/
    } else {
        for (VirtualConnection vc : vcConcurrentSet) {
            vc.close().addListener(new Runnable() {
                @Override
                public void run() {
                    if (vcConcurrentSet.isEmpty()) {
                        future.set(null);
                    }
                }
            }, MoreExecutors.directExecutor());
        }
    }

    return future;
}

From source file:org.apache.bookkeeper.bookie.LedgerDescriptorImpl.java

synchronized SettableFuture<Boolean> fenceAndLogInJournal(Journal journal) throws IOException {
    boolean success = this.setFenced();
    if (success) {
        // fenced for first time, we should add the key to journal ensure we can rebuild.
        return logFenceEntryInJournal(journal);
    } else {// w  w w.  j  av  a 2  s .  c  o m
        // If we reach here, it means the fence state in FileInfo has been set (may not be persisted yet).
        // However, writing the fence log entry to the journal might still be in progress. This can happen
        // when a bookie receives two fence requests almost at the same time. The subsequent logic is used
        // to check the fencing progress.
        if (logFenceResult == null || fenceEntryPersisted.get()) {
            // Either ledger's fenced state is recovered from Journal
            // Or Log fence entry in Journal succeed
            SettableFuture<Boolean> result = SettableFuture.create();
            result.set(true);
            return result;
        } else if (logFenceResult.isDone()) {
            // We failed to log fence entry in Journal, try again.
            return logFenceEntryInJournal(journal);
        }
        // Fencing is in progress
        return logFenceResult;
    }
}

From source file:io.crate.executor.task.LocalMergeTask.java

/**
 *
 * @param implementationSymbolVisitor symbol visitor (on cluster level)
 *///  ww  w. ja v  a2  s.  com
public LocalMergeTask(ThreadPool threadPool, ClusterService clusterService, Settings settings,
        TransportActionProvider transportActionProvider,
        ImplementationSymbolVisitor implementationSymbolVisitor, MergeNode mergeNode, StatsTables statsTables,
        CircuitBreaker circuitBreaker) {
    this.threadPool = threadPool;
    this.clusterService = clusterService;
    this.settings = settings;
    this.transportActionProvider = transportActionProvider;
    this.symbolVisitor = implementationSymbolVisitor;
    this.mergeNode = mergeNode;
    this.statsTables = statsTables;
    this.circuitBreaker = circuitBreaker;
    this.result = SettableFuture.create();
    this.resultList = Arrays.<ListenableFuture<TaskResult>>asList(this.result);
}

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

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

    imageListRef.addValueEventListener(new ValueEventListener() {
        @Override//  www .j  a va 2s. co  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;
}

From source file:com.facebook.buck.remoteexecution.grpc.GrpcRemoteExecutionService.java

@Override
public ExecutionResult execute(Protocol.Digest actionDigest) throws IOException, InterruptedException {
    SettableFuture<Operation> future = SettableFuture.create();

    getStubWithTraceInfo(actionDigest).execute(
            ExecuteRequest.newBuilder().setInstanceName(instanceName)
                    .setActionDigest(GrpcProtocol.get(actionDigest)).setSkipCacheLookup(false).build(),
            new StreamObserver<Operation>() {
                @Nullable//from  w  ww  .jav a  2  s .c  om
                Operation op = null;

                @Override
                public void onNext(Operation value) {
                    op = value;
                }

                @Override
                public void onError(Throwable t) {
                    future.setException(t);
                }

                @Override
                public void onCompleted() {
                    future.set(op);
                }
            });

    try {
        Operation operation = future.get();
        if (operation.hasError()) {
            throw new RuntimeException("Execution failed: " + operation.getError().getMessage());
        }

        if (!operation.hasResponse()) {
            throw new RuntimeException("Invalid operation response: missing ExecutionResponse object");
        }

        ActionResult actionResult = operation.getResponse().unpack(ExecuteResponse.class).getResult();
        return new ExecutionResult() {
            @Override
            public List<OutputDirectory> getOutputDirectories() {
                return actionResult.getOutputDirectoriesList().stream().map(GrpcOutputDirectory::new)
                        .collect(Collectors.toList());
            }

            @Override
            public List<OutputFile> getOutputFiles() {
                return actionResult.getOutputFilesList().stream().map(GrpcOutputFile::new)
                        .collect(Collectors.toList());
            }

            @Override
            public int getExitCode() {
                return actionResult.getExitCode();
            }

            @Override
            public Optional<String> getStderr() {
                ByteString stderrRaw = actionResult.getStderrRaw();
                if (stderrRaw == null
                        || (stderrRaw.isEmpty() && actionResult.getStderrDigest().getSizeBytes() > 0)) {
                    System.err.println("Got stderr digest.");
                    try {
                        ByteString data = ByteString.EMPTY;
                        GrpcRemoteExecutionClients.readByteStream(instanceName,
                                new GrpcDigest(actionResult.getStderrDigest()), byteStreamStub, data::concat)
                                .get();
                        return Optional.of(data.toStringUtf8());
                    } catch (InterruptedException | ExecutionException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.err.println("Got raw stderr: " + stderrRaw.toStringUtf8());
                    return Optional.of(stderrRaw.toStringUtf8());
                }
            }
        };
    } catch (ExecutionException e) {
        Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
        Throwables.throwIfInstanceOf(e.getCause(), InterruptedException.class);
        e.printStackTrace();
        throw new BuckUncheckedExecutionException(e.getCause());
    }
}

From source file:com.spotify.folsom.client.DefaultRawMemcacheClient.java

public static ListenableFuture<RawMemcacheClient> connect(final HostAndPort address,
        final int outstandingRequestLimit, final boolean binary, final Executor executor,
        final long timeoutMillis, final Charset charset, final Metrics metrics, final int maxSetLength) {

    final ChannelInboundHandler decoder;
    if (binary) {
        decoder = new BinaryMemcacheDecoder();
    } else {/*from ww w  .  j a  va2s  .c  o m*/
        decoder = new AsciiMemcacheDecoder(charset);
    }

    final ChannelHandler initializer = new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpTuningHandler(), decoder,

                    // Downstream
                    new MemcacheEncoder());
        }
    };

    final SettableFuture<RawMemcacheClient> clientFuture = SettableFuture.create();

    final Bootstrap bootstrap = new Bootstrap().group(EVENT_LOOP_GROUP).handler(initializer)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, SimpleSizeEstimator.INSTANCE);

    final ChannelFuture connectFuture = bootstrap
            .connect(new InetSocketAddress(address.getHostText(), address.getPort()));

    connectFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Create client
                final RawMemcacheClient client = new DefaultRawMemcacheClient(address, future.channel(),
                        outstandingRequestLimit, executor, timeoutMillis, metrics, maxSetLength);
                clientFuture.set(client);
            } else {
                clientFuture.setException(future.cause());
            }
        }
    });

    return onExecutor(clientFuture, executor);
}