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:org.apache.qpid.server.security.auth.manager.AbstractAuthenticationManager.java

@StateTransition(currentState = { State.UNINITIALIZED, State.QUIESCED,
        State.QUIESCED }, desiredState = State.ACTIVE)
protected ListenableFuture<Void> activate() {
    try {/*from  w  ww .ja v a2s .com*/
        setState(State.ACTIVE);
    } catch (RuntimeException e) {
        setState(State.ERRORED);
        if (getAncestor(SystemConfig.class).isManagementMode()) {
            LOGGER.warn("Failed to activate authentication provider: " + getName(), e);
        } else {
            throw e;
        }
    }
    return Futures.immediateFuture(null);
}

From source file:com.facebook.buck.parser.ParserLeaseVendor.java

private synchronized ListenableFuture<P> obtainParser(Cell cell) {
    Preconditions.checkState(!closed.get());

    Deque<P> parserQueue = parkedParsers.get(cell);
    if (parserQueue != null && !parserQueue.isEmpty()) {
        P parser = Preconditions.checkNotNull(parserQueue.pop());
        return Futures.immediateFuture(parser);
    }// w w w.  jav a 2 s. co m
    Optional<P> possiblyCreated = createIfAllowed(cell);
    if (possiblyCreated.isPresent()) {
        return Futures.immediateFuture(possiblyCreated.get());
    }
    SettableFuture<P> parserFututre = SettableFuture.create();
    Deque<SettableFuture<P>> requestsQueue = parserRequests.get(cell);
    if (requestsQueue == null) {
        requestsQueue = new ArrayDeque<>();
        parserRequests.put(cell, requestsQueue);
    }
    requestsQueue.add(parserFututre);
    return parserFututre;
}

From source file:org.glowroot.central.util.MoreFutures.java

public static ListenableFuture<?> rollupAsync(Collection<ListenableFuture<ResultSet>> futures,
        Executor asyncExecutor, DoRollup function) {
    return transformAsync(Futures.allAsList(futures), asyncExecutor,
            new AsyncFunction<List<ResultSet>, /*@Nullable*/ Object>() {
                @Override/* ww w.  j av  a 2  s. c o  m*/
                @SuppressWarnings("unchecked")
                public ListenableFuture</*@Nullable*/ Object> apply(List<ResultSet> list) throws Exception {
                    List<Row> rows = new ArrayList<>();
                    for (ResultSet results : list) {
                        rows.addAll(results.all());
                    }
                    if (rows.isEmpty()) {
                        return Futures.immediateFuture(null);
                    }
                    return (ListenableFuture</*@Nullable*/ Object>) function.execute(rows);
                }
            });
}

From source file:org.apache.rave.opensocial.service.impl.DefaultAppDataService.java

/**
 * Retrieves app data for the specified user list and group.
 *
 * @param userIds A set of UserIds/*from   w  ww .  ja v  a2  s  .co m*/
 * @param groupId The group
 * @param appId   The application ID
 * @param fields  The fields to filter the data by - empty set implies no filter
 * @param token   The security token
 * @return The data fetched
 */
@Override
public Future<DataCollection> getPersonData(Set<UserId> userIds, GroupId groupId, String appId,
        Set<String> fields, SecurityToken token) throws ProtocolException {
    //make sure the request conforms to the OpenSocial visibility rules
    List<String> personIds = validateReadRequest(userIds, groupId, appId, token);

    //fetch their appdata, convert it to a DataCollection and return it
    List<ApplicationData> applicationData = applicationDataRepository.getApplicationData(personIds, appId);
    DataCollection dataCollection = convertAppDataMapToDataCollection(personIds, applicationData, fields);
    return Futures.immediateFuture(dataCollection);
}

From source file:com.facebook.buck.distributed.MultiSourceContentsProvider.java

private ListenableFuture<Boolean> postLocalFsMaterializationHelper(boolean success,
        BuildJobStateFileHashEntry entry, Path targetAbsPath) {
    if (success) {
        fileMaterializationStatsTracker.recordLocalFileMaterialized();
        LOG.info("Materialized source file using Local Source File Cache: [%s]", targetAbsPath);
        return Futures.immediateFuture(true);
    }/*from   www  .jav a2s  .  c  om*/

    Stopwatch remoteMaterializationStopwatch = Stopwatch.createStarted();
    return Futures.transformAsync(serverContentsProvider.materializeFileContentsAsync(entry, targetAbsPath),
            (remoteSuccess) -> postRemoteMaterializationHelper(remoteSuccess, entry, targetAbsPath,
                    remoteMaterializationStopwatch.elapsed(TimeUnit.MILLISECONDS)),
            executorService);
}

From source file:org.dcache.poolmanager.PoolManagerHandlerSubscriber.java

@PostConstruct
public synchronized void start() {
    current = transformAsync(startGate,/*from   w  w  w  .  j a v  a 2 s  .  c  o m*/
            ignored -> CellStub.transform(query(new PoolMgrGetHandler()), PoolMgrGetHandler::getHandler));

    Futures.addCallback(current, new FutureCallback<SerializablePoolManagerHandler>() {
        @Override
        public void onSuccess(SerializablePoolManagerHandler handler) {
            synchronized (PoolManagerHandlerSubscriber.this) {
                try {
                    current = Futures.immediateFuture(handler);
                    if (!isStopped) {
                        ListenableFuture<SerializablePoolManagerHandler> next = CellStub.transform(
                                query(new PoolMgrGetUpdatedHandler(handler.getVersion())),
                                PoolMgrGetHandler::getHandler);
                        Futures.addCallback(next, this);
                    }
                } catch (Throwable t) {
                    current = Futures.immediateFailedFuture(t);
                    LOGGER.error(
                            "Failure in pool manager handler subscriber. Please report to support@dcache.org.",
                            t);
                    throw t;
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            synchronized (PoolManagerHandlerSubscriber.this) {
                current = Futures.immediateFailedFuture(t);
            }
        }
    });
}

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

@Override
public Future<Long> increment(Object key, long delta, Long initialValue) {
    return Futures.immediateFuture(memcacheService.increment(key, delta, initialValue));
}

From source file:com.facebook.buck.remoteexecution.util.OutOfProcessIsolatedExecutionClients.java

private OutOfProcessIsolatedExecutionClients(final Protocol protocol, BuckEventBus eventBus)
        throws IOException {
    this.workDir = new NamedTemporaryDirectory("__work__");
    this.storage = new LocalContentAddressedStorage(workDir.getPath().resolve("__cache__"), protocol);
    this.protocol = protocol;
    this.executionService = (actionDigest, ruleName) -> {
        Action action = storage.materializeAction(actionDigest);

        Path buildDir = workDir.getPath().resolve(action.getInputRootDigest().getHash());
        try (Closeable ignored = () -> MostFiles.deleteRecursively(buildDir)) {
            Command command;/*from w  w w .j  a  v a  2  s  .  c o  m*/
            try (Scope ignored2 = LeafEvents.scope(eventBus, "materializing_inputs")) {
                command = storage.materializeInputs(buildDir, action.getInputRootDigest(),
                        Optional.of(action.getCommandDigest())).get();
            }

            ActionRunner.ActionResult actionResult = new ActionRunner(protocol, eventBus)
                    .runAction(command.getCommand(), command.getEnvironment(), command.getOutputDirectories()
                            .stream().map(Paths::get).collect(ImmutableSet.toImmutableSet()), buildDir);
            try (Scope ignored2 = LeafEvents.scope(eventBus, "uploading_results")) {
                Futures.getUnchecked(storage.addMissing(actionResult.requiredData));
            }
            return Futures.immediateFuture(new ExecutionResult() {
                @Override
                public ImmutableList<OutputDirectory> getOutputDirectories() {
                    return actionResult.outputDirectories;
                }

                @Override
                public ImmutableList<OutputFile> getOutputFiles() {
                    return actionResult.outputFiles;
                }

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

                @Override
                public Optional<String> getStdout() {
                    return Optional.of(actionResult.stdout);
                }

                @Override
                public Optional<String> getStderr() {
                    return Optional.of(actionResult.stderr);
                }

                @Override
                public RemoteExecutionMetadata getMetadata() {
                    return RemoteExecutionMetadata.getDefaultInstance();
                }

                @Override
                public Digest getActionResultDigest() {
                    return protocol.newDigest("", 0);
                }
            });
        }
    };
}

From source file:org.apache.qpid.server.logging.logback.AbstractLogger.java

@StateTransition(currentState = { State.ERRORED, State.UNINITIALIZED,
        State.STOPPED }, desiredState = State.ACTIVE)
private ListenableFuture<Void> doActivate() {
    setState(State.ACTIVE);
    return Futures.immediateFuture(null);
}

From source file:org.apache.shindig.social.websockbackend.spi.WsNativeProcessMiningSPI.java

@Override
public Future<Void> addProcessCycle(String docId, String docType, String start, String end,
        List<String> userList, SecurityToken token) throws ProtocolException {
    /*//from  w ww .  j  a v  a 2 s.c o  m
     * // check linking person parameter if (token == null || token.getViewerId() == null ||
     * token.getViewerId().isEmpty()) { throw new
     * ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
     * "viewer ID from security token is required"); }
     *
     * // create query final WebsockQuery query = new WebsockQuery(EQueryType.PROCEDURE_CALL);
     * query.setPayload(ShindigNativeQueries.ADD_PROCESS_CYCLE_QUERY);
     *
     * // set parameters for method query.setParameter(ShindigNativeQueries.PROCESS_CYCLE_DOC_ID,
     * docId); query.setParameter(key, docType);
     *
     * // execute final IQueryCallback result = this.fQueryHandler.sendQuery(query);
     *
     * try { result.get(); } catch(final Exception e) { e.printStackTrace();
     * this.fLogger.log(Level.SEVERE, "server error", e); throw new
     * ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "failed to execute query",
     * e); }
     */

    return Futures.immediateFuture(null);
}