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:org.apache.omid.tso.client.TSOClientRaw.java

public Future<Response> getResponse() throws InterruptedException {
    SettableFuture<Response> future = SettableFuture.create();
    responseQueue.put(future);/*from w  w  w.  j a v  a 2s  . c  om*/
    return future;
}

From source file:org.opendaylight.controller.clustering.it.provider.impl.PrefixShardHandler.java

public ListenableFuture<RpcResult<Void>> onCreatePrefixShard(final CreatePrefixShardInput input) {

    final SettableFuture<RpcResult<Void>> future = SettableFuture.create();

    final CompletionStage<DistributedShardRegistration> completionStage;
    final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());

    try {/*ww w  .j a v a 2 s.c o m*/
        completionStage = shardFactory.createDistributedShard(
                new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, identifier),
                input.getReplicas().stream().map(MemberName::forName).collect(Collectors.toList()));

        completionStage.thenAccept(registration -> {
            LOG.debug("Shard[{}] created successfully.", identifier);
            registrations.put(identifier, registration);

            final ListenableFuture<Void> ensureFuture = ensureListExists();
            Futures.addCallback(ensureFuture, new FutureCallback<Void>() {
                @Override
                public void onSuccess(@Nullable final Void result) {
                    LOG.debug("Initial list write successful.");
                    future.set(RpcResultBuilder.<Void>success().build());
                }

                @Override
                public void onFailure(final Throwable throwable) {
                    LOG.warn("Shard[{}] creation failed:", identifier, throwable);

                    final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION,
                            "create-shard-failed", "Shard creation failed", "cluster-test-app", "", throwable);
                    future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
                }
            }, MoreExecutors.directExecutor());
        });
        completionStage.exceptionally(throwable -> {
            LOG.warn("Shard[{}] creation failed:", identifier, throwable);

            final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION,
                    "create-shard-failed", "Shard creation failed", "cluster-test-app", "", throwable);
            future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
            return null;
        });
    } catch (final DOMDataTreeShardingConflictException e) {
        LOG.warn("Unable to register shard for: {}.", identifier);

        final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "create-shard-failed",
                "Sharding conflict", "cluster-test-app", "", e);
        future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
    }

    return future;
}

From source file:net.sourceforge.fullsync.ui.GuiController.java

private Future<Boolean> showQuestion(String question) {
    SettableFuture<Boolean> answer = SettableFuture.create();
    if (display == Display.findDisplay(Thread.currentThread())) {
        answer.set(doShowQuestion(question));
    } else {/*from w w w . j a v a 2 s . c  o  m*/
        display.asyncExec(() -> answer.set(doShowQuestion(question)));
    }
    return answer;
}

From source file:org.opendaylight.controller.cluster.datastore.SimpleShardDataTreeCohort.java

@Override
public ListenableFuture<Void> abort() {
    dataTree.startAbort(this);
    state = State.ABORTED;/* w w w .j  av a  2  s  .  c  om*/

    final Optional<Future<Iterable<Object>>> maybeAborts = userCohorts.abort();
    if (!maybeAborts.isPresent()) {
        return VOID_FUTURE;
    }

    final Future<Iterable<Object>> aborts = maybeAborts.get();
    if (aborts.isCompleted()) {
        return VOID_FUTURE;
    }

    final SettableFuture<Void> ret = SettableFuture.create();
    aborts.onComplete(new OnComplete<Iterable<Object>>() {
        @Override
        public void onComplete(final Throwable failure, final Iterable<Object> objs) {
            if (failure != null) {
                ret.setException(failure);
            } else {
                ret.set(null);
            }
        }
    }, ExecutionContexts.global());

    return ret;
}

From source file:org.opendaylight.ocpplugin.impl.services.SalObjectStateMgmtServiceImpl.java

@Override
public Future<RpcResult<ModifyStateOutput>> modifyState(final ModifyStateInput input) {
    ListenableFuture<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.ModifyStateOutput>> future = modifyState
            .handleServiceCall(input);//from   w w w  . j a va 2  s. c o  m
    final SettableFuture<RpcResult<ModifyStateOutput>> finalFuture = SettableFuture.create();
    Futures.addCallback(future,
            new FutureCallback<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.ModifyStateOutput>>() {
                @Override
                public void onSuccess(
                        final RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.ModifyStateOutput> result) {
                    org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.ModifyStateOutput output = result
                            .getResult();
                    ModifyStateOutputBuilder builder = new ModifyStateOutputBuilder();
                    builder.setObjId(output.getObjId());
                    builder.setStateType(output.getStateType());
                    builder.setStateValue(output.getStateValue());
                    builder.setResult(output.getResult());
                    RpcResultBuilder<ModifyStateOutput> rpcResultBuilder = RpcResultBuilder.success(builder);
                    finalFuture.set(rpcResultBuilder.build());
                }

                @Override
                public void onFailure(final Throwable t) {
                    RpcResultBuilder<ModifyStateOutput> rpcResultBuilder = RpcResultBuilder.failed();
                    finalFuture.set(rpcResultBuilder.build());
                }
            });

    return finalFuture;
}

From source file:com.android.builder.internal.aapt.AbstractProcessExecutionAapt.java

@NonNull
@Override/*from w  w  w  .  j a  va  2  s  .c  o  m*/
public ListenableFuture<File> compile(@NonNull File file, @NonNull File output) throws AaptException {
    Preconditions.checkArgument(file.isFile(), "!file.isFile()");
    Preconditions.checkArgument(output.isDirectory(), "!output.isDirectory()");

    SettableFuture<File> result = SettableFuture.create();

    CompileInvocation compileInvocation = makeCompileProcessBuilder(file, output);
    if (compileInvocation == null) {
        result.set(null);
        return result;
    }

    ProcessInfo processInfo = compileInvocation.builder.createProcess();
    ListenableFuture<ProcessResult> execResult = mProcessExecutor.submit(processInfo, mProcessOutputHandler);

    Futures.addCallback(execResult, new FutureCallback<ProcessResult>() {
        @Override
        public void onSuccess(ProcessResult processResult) {
            try {
                processResult.rethrowFailure().assertNormalExitValue();
                result.set(compileInvocation.outputFile);
            } catch (Exception e) {
                result.setException(e);
            }
        }

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

    return result;
}

From source file:io.prestosql.operator.PagesSpatialIndexFactory.java

/**
 * Called by {@link SpatialJoinOperator}.
 * <p>// ww w.jav a 2s  .co  m
 * {@link SpatialJoinOperator} must call {@link #probeOperatorFinished()} on completion
 * to signal that spatial index is no longer needed.
 */
public synchronized ListenableFuture<PagesSpatialIndex> createPagesSpatialIndex() {
    activeProbeOperators.retain();

    if (pagesSpatialIndex != null) {
        return immediateFuture(pagesSpatialIndex.get());
    }

    SettableFuture<PagesSpatialIndex> future = SettableFuture.create();
    pagesSpatialIndexFutures.add(future);
    return future;
}

From source file:org.robotninjas.barge.state.ReplicaManager.java

private ListenableFuture<AppendEntriesResponse> sendUpdate() {

    running++;/*from  w  ww  .j a va  2 s  .com*/
    requested = false;

    // if the last rpc call was successful then try to send
    // as many updates as we can, otherwise, if we're
    // probing backwards, only send one entry as a probe, as
    // soon as we have a successful call forwards will become
    // true and we can catch up quickly
    GetEntriesResult result = log.getEntriesFrom(nextIndex, forwards ? BATCH_SIZE : 1);

    final AppendEntries request = AppendEntries.newBuilder().setTerm(log.currentTerm())
            .setLeaderId(log.self().toString()).setPrevLogIndex(result.lastLogIndex())
            .setPrevLogTerm(result.lastLogTerm()).setCommitIndex(log.commitIndex())
            .addAllEntries(result.entries()).build();

    LOGGER.debug("Sending update to {} prevLogIndex {} prevLogTerm {}", remote, result.lastLogIndex(),
            result.lastLogTerm());
    final ListenableFuture<AppendEntriesResponse> response = client.appendEntries(remote, request);

    final SettableFuture<AppendEntriesResponse> previousResponse = nextResponse;

    Futures.addCallback(response, new FutureCallback<AppendEntriesResponse>() {

        @Override
        public void onSuccess(@Nullable AppendEntriesResponse result) {
            running--;
            updateNextIndex(request, result);
            if (result.getSuccess()) {
                previousResponse.set(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            running--;
            requested = false;
            previousResponse.setException(t);
        }

    });

    nextResponse = SettableFuture.create();

    return response;

}

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

/**
 * Executes given MapReduce Program and block until it completed. On completion, return the MapReduceContext.
 *
 * @throws Exception if execution failed.
 *//*from   ww  w. java 2  s  . co m*/
private MapReduceContext runAndWait(Program program, ProgramOptions options) throws Exception {
    ProgramController controller = programRunner.run(program, options);
    final MapReduceContext context = (controller instanceof MapReduceProgramController)
            ? ((MapReduceProgramController) controller).getContext()
            : null;
    // Execute the program.
    final SettableFuture<MapReduceContext> completion = SettableFuture.create();
    controller.addListener(new AbstractListener() {
        @Override
        public void stopped() {
            completion.set(context);
        }

        @Override
        public void error(Throwable cause) {
            completion.setException(cause);
        }
    }, Threads.SAME_THREAD_EXECUTOR);

    // Block for completion.
    try {
        return completion.get();
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof Exception) {
            throw (Exception) cause;
        }
        throw Throwables.propagate(cause);
    }
}

From source file:io.mandrel.endpoints.internal.FrontierResource.java

@Override
public ListenableFuture<Next> next(Long id) {
    FrontierContainer frontier = FrontierContainers.get(id).orElseThrow(frontierNotFound);
    SettableFuture<Next> result = SettableFuture.create();
    frontier.frontier().pool((uri, name) -> {
        result.set(new Next().setUri(uri).setFromStore(name));
    });/* ww  w .  ja  va 2s  .co m*/
    try {
        return result;
    } catch (Exception e) {
        log.debug("Well...", e);
        throw RemoteException.of(RemoteException.Error.G_UNKNOWN, e.getMessage());
    }
}