Example usage for com.google.common.util.concurrent Futures immediateFuture

List of usage examples for com.google.common.util.concurrent Futures immediateFuture

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures immediateFuture.

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) 

Source Link

Document

Creates a ListenableFuture which has its value set immediately upon construction.

Usage

From source file:utils.teamcity.wallt.controller.api.ApiController.java

@Override
public ListenableFuture<Void> loadProjectList() {
    if (!getApiVersion().isSupported(ApiFeature.PROJECT_STATUS, ApiFeature.BUILD_TYPE_STATUS))
        return Futures.immediateFuture(null);

    final SettableFuture<Void> ackFuture = SettableFuture.create();

    runInWorkerThread(() -> {/*  w ww . j  a v a  2  s  .com*/
        final ListenableFuture<ProjectList> projectListFuture = _apiRequestController
                .sendRequest(getApiVersion(), "projects", ProjectList.class);
        addCallback(projectListFuture, new FutureCallback<ProjectList>() {
            @Override
            public void onSuccess(final ProjectList result) {
                final List<ProjectData> projects = result.getProjects().stream()
                        .map((project) -> _projectProvider.get(getApiVersion()).apply(project))
                        .collect(Collectors.toList());
                _projectManager.registerProjects(projects);
                _eventBus.post(_projectManager);
                ackFuture.set(null);

                for (final ProjectData project : _projectManager.getProjects()) {
                    LOGGER.info("Discovering project " + project.getId() + " (" + project.getName() + ")");
                }
            }

            @Override
            public void onFailure(final Throwable t) {
                LOGGER.error("Error during loading project list:", t);
                ackFuture.setException(t);
            }
        });
    });

    return ackFuture;
}

From source file:org.opendaylight.nemo.user.UserManager.java

@Override
public Future<RpcResult<AdvancedNemoQueryOutput>> advancedNemoQuery(AdvancedNemoQueryInput input) {
    RpcResult<AdvancedNemoQueryOutput> advancedNemoQueryOutputRpcResult = null;
    AdvancedNemoQueryOutputBuilder advancedNemoQueryOutputBuilder = new AdvancedNemoQueryOutputBuilder();

    String errorInfo = advancedQuery.advancedQuery(aaa, input);
    if (errorInfo != null) {
        advancedNemoQueryOutputBuilder.setResultCode(CommonRpcResult.ResultCode.Error).setMessage(errorInfo);
    } else {//from   w  w  w. j a v a 2 s .c  o  m
        advancedNemoQueryOutputBuilder.setResultCode(CommonRpcResult.ResultCode.Ok)
                .setMessage(advancedQuery.getAdvancedQueryReuslt(input));
    }
    advancedNemoQueryOutputRpcResult = RpcResultBuilder
            .<AdvancedNemoQueryOutput>success(advancedNemoQueryOutputBuilder.build()).build();

    return Futures.immediateFuture(advancedNemoQueryOutputRpcResult);
}

From source file:com.rhythm.louie.util.FutureList.java

@Override
public boolean add(E e) {
    return futures.add(Futures.immediateFuture(e));
}

From source file:org.apache.cassandra.streaming.ConnectionHandler.java

public ListenableFuture<?> close() {
    logger.debug("[Stream #{}] Closing stream connection handler on {}", session.planId(), session.peer);

    ListenableFuture<?> inClosed = incoming == null ? Futures.immediateFuture(null) : incoming.close();
    ListenableFuture<?> outClosed = outgoing == null ? Futures.immediateFuture(null) : outgoing.close();

    return Futures.allAsList(inClosed, outClosed);
}

From source file:org.opendaylight.lispflowmapping.southbound.LispSouthboundRPC.java

@Override
public Future<RpcResult<Void>> sendMapRequest(SendMapRequestInput mapRequestInput) {
    LOG.trace("sendMapRequest called!!");
    if (mapRequestInput != null) {
        ByteBuffer outBuffer = MapRequestSerializer.getInstance().serialize(mapRequestInput.getMapRequest());
        lispSbPlugin.handleSerializedLispBuffer(mapRequestInput.getTransportAddress(), outBuffer,
                MessageType.MapRequest);
    } else {/*from w w w .  j a  v  a  2 s  .co m*/
        LOG.debug("MapRequest was null");
        return Futures.immediateFuture(RpcResultBuilder.<Void>failed().build());
    }
    return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
}

From source file:com.google.gapid.server.Client.java

public ListenableFuture<Message> getSchema() {
    LOG.log(FINE, "RPC->getSchema()");
    return Futures.transformAsync(client.getSchema(GetSchemaRequest.newBuilder().build()),
            in -> Futures.immediateFuture(decode(throwIfError(in.getObject(), in.getError()))));
}

From source file:com.google.api.server.spi.config.datastore.testing.FakeAsyncMemcacheService.java

@Override
public <T> Future<Map<T, Long>> incrementAll(Collection<T> keys, long delta) {
    return Futures.immediateFuture(memcacheService.incrementAll(keys, delta));
}

From source file:com.facebook.watchman.WatchmanClientImpl.java

@Override
public ListenableFuture<Boolean> unsubscribe(final SubscriptionDescriptor descriptor) {
    if (!subscriptions.containsKey(descriptor)) {
        return Futures.immediateFuture(false);
    }/*from w w w .ja va2  s  . c  o  m*/

    List<String> request = ImmutableList.of("unsubscribe", descriptor.root(), descriptor.name());

    return Futures.transform(connection.run(request), new Function<Map<String, Object>, Boolean>() {
        @Nullable
        @Override
        public Boolean apply(@Nullable Map<String, Object> input) {
            checkNotNull(input);

            boolean wasDeleted = (Boolean) input.get("deleted");
            if (wasDeleted) {
                if (subscriptions.remove(descriptor) == null) {
                    return false;
                }
            }
            return wasDeleted;
        }
    });
}

From source file:de.dfki.kiara.impl.ServiceMethodExecutorImpl.java

@Override
public ListenableFuture<Message> performLocalCall(InvocationEnvironment env, final Message requestMessage)
        throws IOException, IllegalAccessException, IllegalArgumentException, ExecutionException,
        InterruptedException {//from   www.jav  a  2s  .  com
    if (requestMessage.getMessageKind() != Message.Kind.REQUEST) {
        throw new IllegalArgumentException("message is not a request");
    }
    final String methodName = requestMessage.getMethodName();
    final Protocol protocol = requestMessage.getProtocol();
    final ServiceMethodBinder serviceMethodBinder = getServiceMethodBinder(methodName);

    Object result;
    boolean isException = false;

    if (serviceMethodBinder == null) {
        isException = true;
        result = new GenericRemoteException("unbound method '" + methodName + "'",
                GenericRemoteException.METHOD_NOT_FOUND);

        Message responseMessage = protocol.createResponseMessage(requestMessage,
                new Message.ResponseObject(result, isException));
        return Futures.immediateFuture(responseMessage);
    } else {
        final MethodEntry methodEntry = serviceMethodBinder.getMethodEntry();

        final List<Object> args = requestMessage.getRequestObject(methodEntry.serializationParamTypes).args;

        //methodEntry.hasFutureParams
        final int numArgs = args.size();
        for (int i = 0; i < numArgs; ++i) {
            if (methodEntry.isFutureParam.get(i)) {
                final Function<Object, Object> f = ((Function<Object, Object>) methodEntry.serializationToParamConverters[i]);
                args.set(i, f.apply(args.get(i)));
            } else if (methodEntry.specialParamTypes[i] != null && env != null) {
                final TypeToken<?> ptype = methodEntry.specialParamTypes[i];
                if (ptype.isAssignableFrom(de.dfki.kiara.ServerConnection.class)) {
                    args.set(i, env.getServiceConnection());
                }
            }
        }

        AsyncFunction<List<Object>, Message> ff = new AsyncFunction<List<Object>, Message>() {

            @Override
            public ListenableFuture<Message> apply(final List<Object> input) throws Exception {
                return Global.executor.submit(new Callable<Message>() {
                    @Override
                    public Message call() throws Exception {
                        Object result;
                        boolean isException = false;

                        try {
                            result = serviceMethodBinder.getBoundMethod()
                                    .invoke(serviceMethodBinder.getImplementedClass(), args.toArray());

                            if (methodEntry.futureParamOfReturnType != null) {
                                ListenableFuture<?> futureResult = (ListenableFuture<?>) (methodEntry.returnTypeConverter != null
                                        ? ((Function<Object, Object>) (methodEntry.returnTypeConverter))
                                                .apply(result)
                                        : result);
                                result = futureResult.get();
                            }

                        } catch (InvocationTargetException ex) {
                            isException = true;
                            result = ex.getTargetException();
                        }

                        Message responseMessage = protocol.createResponseMessage(requestMessage,
                                new Message.ResponseObject(result, isException));
                        return responseMessage;
                    }
                });
            }
        };
        return Futures.transform(Futures.immediateFuture(args), ff);
    }
}

From source file:io.crate.operation.collect.HandlerSideDataCollectOperation.java

private ListenableFuture<Object[][]> handleCluster(CollectNode collectNode,
        RamAccountingContext ramAccountingContext) {
    collectNode = collectNode.normalize(clusterNormalizer);
    if (collectNode.whereClause().noMatch()) {
        return Futures.immediateFuture(TaskResult.EMPTY_RESULT.rows());
    }//  w  w w . j  av  a  2 s .  com
    assert collectNode.toCollect().size() > 0;

    // resolve Implementations
    ImplementationSymbolVisitor.Context ctx = implementationVisitor.process(collectNode);
    List<Input<?>> inputs = ctx.topLevelInputs();
    Set<CollectExpression<?>> collectExpressions = ctx.collectExpressions();

    FlatProjectorChain projectorChain = new FlatProjectorChain(collectNode.projections(), projectorVisitor,
            ramAccountingContext);
    SimpleOneRowCollector collector = new SimpleOneRowCollector(inputs, collectExpressions,
            projectorChain.firstProjector());

    projectorChain.startProjections();
    try {
        collector.doCollect(ramAccountingContext);
    } catch (CollectionAbortedException e) {
        // ignore
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }
    return projectorChain.result();
}