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.opendaylight.controller.cluster.schema.provider.impl.RemoteSchemaProvider.java

@Override
public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(SourceIdentifier sourceIdentifier) {
    LOG.trace("Getting yang schema source for {}", sourceIdentifier.getName());

    Future<YangTextSchemaSourceSerializationProxy> result = remoteRepo
            .getYangTextSchemaSource(sourceIdentifier);

    final SettableFuture<YangTextSchemaSource> res = SettableFuture.create();
    result.onComplete(new OnComplete<YangTextSchemaSourceSerializationProxy>() {
        @Override/*  ww w.jav a 2s.  c  o m*/
        public void onComplete(Throwable throwable,
                YangTextSchemaSourceSerializationProxy yangTextSchemaSourceSerializationProxy) {
            if (yangTextSchemaSourceSerializationProxy != null) {
                res.set(yangTextSchemaSourceSerializationProxy.getRepresentation());
            }
            if (throwable != null) {
                res.setException(throwable);
            }
        }

    }, executionContext);

    return Futures.makeChecked(res, MAPPER);
}

From source file:org.usrz.libs.utils.concurrent.SimpleExecutor.java

public <T> NotifyingFuture<T> call(Callable<T> callable) {
    final SettableFuture<T> settableFuture = SettableFuture.create();

    final Future<T> executingFuture = executor.submit(() -> {
        try {// w w w.j  a v a  2s  .c om
            final T result = callable.call();
            settableFuture.set(result);
            return result;
        } catch (Throwable throwable) {
            settableFuture.setException(throwable);
            throw new Exception(throwable);
        }
    });

    return new NotifyingFuture<T>() {

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (executingFuture.cancel(mayInterruptIfRunning)) {
                settableFuture.cancel(mayInterruptIfRunning);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public boolean isCancelled() {
            return settableFuture.isCancelled();
        }

        @Override
        public boolean isDone() {
            return settableFuture.isCancelled();
        }

        @Override
        public T get() throws InterruptedException, ExecutionException {
            return settableFuture.get();
        }

        @Override
        public T get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return settableFuture.get(timeout, unit);
        }

        @Override
        public NotifyingFuture<T> withConsumer(Consumer<Future<T>> consumer) {
            settableFuture.addListener(() -> consumer.accept(settableFuture), notifier);
            return this;
        }

    };
}

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

public UpsertTask(TransportExecutor transportExecutor, UUID jobId, List<Task> subTasks) {
    super(jobId);
    this.transportExecutor = transportExecutor;
    this.subTasks = subTasks;

    if (subTasks.size() == 1 && subTasks.get(0) instanceof SymbolBasedUpsertByIdTask) {
        // just forward results from sub task because UpsertByIdTask already handles all
        SymbolBasedUpsertByIdTask upsertByIdTask = (SymbolBasedUpsertByIdTask) subTasks.get(0);
        resultList = upsertByIdTask.result();
        forwardResultsFromSubTask = true;
    } else {/*  ww  w .  ja  v  a2  s .  co  m*/
        final SettableFuture<TaskResult> futureResult = SettableFuture.create();
        resultList = new ArrayList<>(1);
        resultList.add(futureResult);
        forwardResultsFromSubTask = false;
    }
}

From source file:com.microsoft.sharepointservices.DocLibClient.java

/**
 * Gets children folder with a given path
 * //  w w  w .  j a  v a2  s .c  o m
 * @param path
 * @return OfficeFuture<FileSystemItem>
 */
public ListenableFuture<List<FileSystemItem>> getFileSystemItems(String path, String library) {

    final SettableFuture<List<FileSystemItem>> result = SettableFuture.create();

    String getPath;

    if (library == null) {
        if (path == null || path.length() == 0) {
            getPath = getSiteUrl() + "_api/Files";
        } else {
            getPath = getSiteUrl() + String.format("_api/Files('%s')/children", urlEncode(path));
        }
    } else {
        if (path == null || path.length() == 0) {
            getPath = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files", urlEncode(library));
        } else {
            getPath = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files('%s')/children",
                    urlEncode(library), urlEncode(path));
        }
    }

    ListenableFuture<JSONObject> request = executeRequestJson(getPath, "GET");

    Futures.addCallback(request, new FutureCallback<JSONObject>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(JSONObject json) {
            List<FileSystemItem> item;
            try {
                item = FileSystemItem.listFrom(json);
                result.set(item);
            } catch (Throwable e) {
                result.setException(e);
            }
        }
    });
    return result;
}

From source file:com.facebook.buck.util.concurrent.ListeningSemaphore.java

public synchronized ListenableFuture<Void> acquire(int permits) {

    // If the semaphore isn't full, acquire it now.  Since an immediate future cannot be canceled,
    // there's no extra handling we have to do here.
    if (canFit(permits)) {
        size += permits;/*  w  w w . ja  v a2s .  c o m*/
        return Futures.immediateFuture(null);
    }

    // Otherwise, queue it up for later.
    SettableFuture<Void> future = SettableFuture.create();
    pending.add(new AbstractMap.SimpleEntry<>(permits, future));
    return future;
}

From source file:org.apache.hadoop.hive.druid.security.KerberosHttpClient.java

@Override
public <Intermediate, Final> ListenableFuture<Final> go(Request request,
        HttpResponseHandler<Intermediate, Final> httpResponseHandler, Duration duration) {
    final SettableFuture<Final> retVal = SettableFuture.create();
    innerGo(request, httpResponseHandler, duration, retVal);
    return retVal;
}

From source file:org.apache.beam.sdk.io.kinesis.KinesisProducerMock.java

@Override
public ListenableFuture<UserRecordResult> addUserRecord(String stream, String partitionKey,
        String explicitHashKey, ByteBuffer data) {
    SettableFuture<UserRecordResult> f = SettableFuture.create();
    if (kinesisService.getExistedStream().equals(stream)) {
        addedRecords.add(new UserRecord(stream, partitionKey, explicitHashKey, data));
    }/*from  w ww  .jav  a 2 s. com*/
    return f;
}

From source file:io.radiowitness.kinesis.producer.KinesisRecordProducer.java

private PutRecordTask nextTask() {
    Futures.addCallback(queuedFuture, this);
    PutRecordTask task = taskFactory.create(queuedFuture, partitionKey, sequenceNumber);
    queuedFuture = SettableFuture.create();
    return task;/* w w  w .j a v a2  s.  co m*/
}

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

@Override
public Future<RpcResult<GetParamOutput>> getParam(final GetParamInput input) {
    ListenableFuture<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.GetParamOutput>> future = getParam
            .handleServiceCall(input);/*from w  w  w .ja  va 2 s  .c om*/
    final SettableFuture<RpcResult<GetParamOutput>> finalFuture = SettableFuture.create();
    Futures.addCallback(future,
            new FutureCallback<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.GetParamOutput>>() {
                @Override
                public void onSuccess(
                        final RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.GetParamOutput> result) {
                    org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.GetParamOutput output = result
                            .getResult();
                    GetParamOutputBuilder builder = new GetParamOutputBuilder();
                    builder.setObj(output.getObj());
                    builder.setResult(output.getResult());
                    RpcResultBuilder<GetParamOutput> rpcResultBuilder = RpcResultBuilder.success(builder);
                    finalFuture.set(rpcResultBuilder.build());
                }

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

    return finalFuture;
}

From source file:com.microsoft.office365.SharepointClient.java

protected ListenableFuture<String> getFormDigest() {

    HttpConnection connection = Platform.createHttpConnection();
    Request request = new Request("POST");
    request.setUrl(getSiteUrl() + "_api/contextinfo");
    prepareRequest(request);/*ww  w .  ja v  a  2 s.c  o  m*/

    log("Generate request for getFormDigest", LogLevel.Verbose);
    request.log(getLogger());

    final SettableFuture<String> result = SettableFuture.create();
    ListenableFuture<Response> future = connection.execute(request);

    Futures.addCallback(future, new FutureCallback<Response>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(Response response) {
            try {
                int statusCode = response.getStatus();
                if (isValidStatus(statusCode)) {
                    String responseContent = response.readToEnd();

                    JSONObject json = new JSONObject(responseContent);

                    result.set(json.getJSONObject("d").getJSONObject("GetContextWebInformation")
                            .getString("FormDigestValue"));
                } else {
                    result.setException(
                            new Exception("Invalid status code " + statusCode + ": " + response.readToEnd()));
                }
            } catch (Exception e) {
                log(e);
            }
        }
    });

    return result;
}