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:com.google.gapid.models.ApiState.java

public ListenableFuture<Path.StateTreeNode> getResolvedSelectedPath() {
    Path.Any path = selection.get();
    if (path == null || !isLoaded()) {
        return Futures.immediateFuture(Path.StateTreeNode.getDefaultInstance());
    } else if (path.getPathCase() == Path.Any.PathCase.STATE_TREE_NODE) {
        return Futures.immediateFuture(path.getStateTreeNode());
    }//from ww  w .  j  a va  2  s  . c  o  m

    return Futures.transform(client.get(Paths.stateTree(((RootNode) getData()).tree, path)),
            value -> value.getPath().getStateTreeNode());
}

From source file:io.v.x.jni.test.fortune.FortuneServerImpl.java

@Override
public ListenableFuture<MultipleGetOut> multipleGet(VContext context, ServerCall call) {
    if (lastAddedFortune == null) {
        return Futures.immediateFailedFuture(new NoFortunesException(context));
    }//from  w w  w .  j  av a 2 s  .  c  o  m
    MultipleGetOut ret = new MultipleGetOut();
    ret.fortune = lastAddedFortune;
    ret.another = lastAddedFortune;
    return Futures.immediateFuture(ret);
}

From source file:edu.ucsf.orng.shindig.service.JsonLDHandler.java

/**
 * Returns a list of people that correspond to the passed in person ids.
 * //from  www .jav  a2s  .com
 * @param userIds
 *            A set of users
 * @param groupId
 *            The group
 * @param collectionOptions
 *            How to filter, sort and paginate the collection being fetched
 * @param fields
 *            The profile details to fetch. Empty set implies all
 * @param token
 *            The gadget token @return a list of people.
 * @return Future that returns a RestfulCollection of Person
 */
private Future<JSONObject> getJSONItems(Set<String> urls, boolean nocache, String output, Set<String> fields,
        String containerSessionId, GroupId groupId, CollectionOptions collectionOptions, SecurityToken token)
        throws ProtocolException {
    try {
        Model model = null;
        Set<String> uris = Sets.newLinkedHashSet();
        for (String url : urls) {
            RdfItem item = rdfService.getRDF(url, nocache, "full".equalsIgnoreCase(output), fields,
                    containerSessionId, token);
            model = model == null ? item.getModel() : model.add(item.getModel());
            uris.add(item.getRequestedUri());
        }
        JSONObject jsonld = jsonldService.getJSONObject(model);
        // add the URI's
        JSONObject retval = new JSONObject().put("base", jsonldService.getBase()).put("uris", uris)
                .put("jsonld", jsonld);
        return Futures.immediateFuture(retval);
    } catch (Exception e) {
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
    }
}

From source file:org.opendaylight.controller.sample.kitchen.impl.KitchenServiceImpl.java

private Future<RpcResult<Void>> makeToast(Class<? extends ToastType> toastType, int toastDoneness) {

    if (toasterOutOfBread) {
        log.info("We're out of toast but we can make eggs");
        return Futures.immediateFuture(RpcResultBuilder.<Void>success().withWarning(ErrorType.APPLICATION,
                "partial-operation", "Toaster is out of bread but we can make you eggs").build());
    }/*w  w  w . ja  v  a  2s.c o  m*/

    // Access the ToasterService to make the toast.

    MakeToastInput toastInput = new MakeToastInputBuilder().setToasterDoneness((long) toastDoneness)
            .setToasterToastType(toastType).build();

    return toaster.makeToast(toastInput);
}

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

@SuppressWarnings("unchecked")
@Override//from  www  .j  a v a 2  s .co m
public Future<RestfulCollection<Group>> getGroups(UserId userId, CollectionOptions options, Set<String> fields,
        SecurityToken token) throws ProtocolException {
    final List<Group> groupList = new ArrayList<Group>();
    final WebsockQuery wsQuery = new WebsockQuery(EQueryType.PROCEDURE_CALL);

    if (options != null) {
        CollOptsConverter.convert(options, wsQuery);
    }

    // set parameters
    wsQuery.setPayload(WsCypherGroupSPI.GROUPS_QUERY_NAME);
    wsQuery.setParameter("id", userId.getUserId(token));

    // execute
    final IQueryCallback callback = this.fQueryHandler.sendQuery(wsQuery);
    TableResult result = null;

    try {
        result = (TableResult) callback.get();
    } catch (final Exception e) {
        e.printStackTrace();
        this.fLogger.log(Level.SEVERE, "server error", e);
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not retrieve result",
                e);
    }

    // wrap results
    Map<String, Object> gMap = null;
    for (final List<Object> gList : result.getResults()) {
        gMap = (Map<String, Object>) gList.get(0);
        groupList.add(new GroupDTO(gMap));
    }

    final RestfulCollection<Group> rColl = new RestfulCollection<Group>(groupList);
    rColl.setStartIndex(result.getFirst());
    rColl.setTotalResults(result.getTotal());
    rColl.setItemsPerPage(result.getMax());
    return Futures.immediateFuture(rColl);
}

From source file:us.physion.ovation.ui.browser.TrashTopComponent.java

private ListenableFuture<Void> populateTrash() {
    final DataContext c = Lookup.getDefault().lookup(ConnectionProvider.class).getDefaultContext();

    if (c == null) {
        //adding this node just to have a RefreshableNode as root
        explorerManager.setRootContext(new TrashRootNode(Children.LEAF));

        log.warn("Null DataContext");
        Toolkit.getDefaultToolkit().beep();
        return Futures.immediateFuture(null);
    }//from w ww  .  j  a va 2 s.  c om

    final SettableFuture<Void> result = SettableFuture.create();
    new SwingWorker<Iterable<OvationEntity>, Void>() {
        @Override
        protected Iterable<OvationEntity> doInBackground() throws Exception {
            return c.getTrashRoots();
        }

        @Override
        protected void done() {
            if (isCancelled()) {
                result.set(null);
                return;
            }
            try {
                Iterable<OvationEntity> roots = get();

                explorerManager.setRootContext(new TrashRootNode(new TopTrashChildren(roots)));

                result.set(null);
            } catch (InterruptedException ex) {
                log.warn("Cannot load trash roots", ex);
                result.setException(ex);
            } catch (ExecutionException ex) {
                log.warn("Cannot load trash roots", ex);
                result.setException(ex);
            }
        }
    }.execute();

    return result;
}

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

/**
 * Returns a set of activities for the passed in user and group that corresponds to a list of activityIds.
 * <p/>//from  ww  w .ja  v a 2 s  .c  om
 * Specified by: getActivityEntries(...) in ActivityStreamService
 * <p/>
 * Parameters:
 * userId The set of ids of the people to fetch activities for.
 * groupId Indicates whether to fetch activities for a group.
 * appId The app id.
 * fields The fields to return. Empty set implies all
 * options The sorting/filtering/pagination options
 * activityIds The set of activity ids to fetch.
 * token A valid SecurityToken
 * Returns:
 * a response item with the list of activities.
 * Throws:
 * ProtocolException - if any.
 */
@Override
public Future<RestfulCollection<ActivityEntry>> getActivityEntries(UserId userId, GroupId groupId, String appId,
        Set<String> fields, CollectionOptions options, Set<String> activityIds, SecurityToken token)
        throws ProtocolException {
    List<ActivityEntry> entries = Lists.newLinkedList();
    Map<String, Person> peopleById = Maps.newHashMap();

    for (String id : activityIds) {
        entries.add(getActivity(fields, userId.getUserId(token), peopleById, id));
    }

    return Futures.immediateFuture(new RestfulCollection<ActivityEntry>(entries));
}

From source file:org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHARemoteReplicationNodeImpl.java

@StateTransition(currentState = { State.ACTIVE, State.UNAVAILABLE }, desiredState = State.DELETED)
private ListenableFuture<Void> doDelete() {
    String nodeName = getName();//w  w  w  .j  a v  a 2s .co  m

    getEventLogger().message(_virtualHostNodeLogSubject, HighAvailabilityMessages.DELETED());

    boolean deletionAllowed;
    try {
        deletionAllowed = _replicatedEnvironmentFacade.removeNodeFromGroup(nodeName);
    } catch (ServerScopedRuntimeException e) {
        throw e;
    } catch (RuntimeException e) {
        throw new IllegalStateTransitionException("Unexpected exception on node '" + nodeName + "' deletion",
                e);
    }

    if (deletionAllowed) {
        setState(State.DELETED);
        deleted();
    } else {
        throw new IllegalStateTransitionException(
                "Node '" + nodeName + "' cannot be deleted when role is a master");
    }

    return Futures.immediateFuture(null);
}

From source file:org.apache.shindig.social.websockbackend.service.ExtPersonHandler.java

/**
 * Modified to enable friend requests requests. Allowed end-points /people/{userId}+/{groupId}
 * /people/{userId}/{groupId}/{optionalPersonId}+
 *
 * examples: /people/john.doe/@all /people/john.doe/@friends /people/john.doe/@self
 *//*  www . jav  a  2  s.  c  om*/
@Operation(httpMethods = "GET")
public Future<?> get(SocialRequestItem request) throws ProtocolException {
    final GroupId groupId = request.getGroup();
    final Set<String> optionalPersonId = ImmutableSet.copyOf(request.getListParameter("personId"));
    final Set<String> fields = request.getFields();
    final Set<UserId> userIds = request.getUsers();

    // Preconditions
    HandlerPreconditions.requireNotEmpty(userIds, "No userId specified");
    if (userIds.size() > 1 && !optionalPersonId.isEmpty()) {
        throw new IllegalArgumentException("Cannot fetch personIds for multiple userIds");
    }

    final CollectionOptions options = new CollectionOptions(request);

    if (userIds.size() == 1) {
        if (optionalPersonId.isEmpty()) {
            if (groupId.getType() == GroupId.Type.self) {
                // If a filter is set then we have to call getPeople(),
                // otherwise use the simpler getPerson()
                if (options.getFilter() != null) {
                    Person p = null;
                    RestfulCollection<Person> people = null;
                    try {
                        people = this.fPersonSPI
                                .getPeople(userIds, groupId, options, fields, request.getToken()).get();
                    } catch (final Exception e) {
                        throw new RuntimeException(e);
                    }

                    if (people.getList() != null && people.getList().size() > 0) {
                        p = people.getList().get(0);
                    }

                    return Futures.immediateFuture(p);
                } else {
                    return this.fPersonSPI.getPerson(userIds.iterator().next(), fields, request.getToken());
                }
            } else if (Constants.FRIEND_REQUESTS.equals(groupId.getObjectId())) {
                return this.fFriendSPI.getRequests(userIds.iterator().next(), options, fields,
                        request.getToken());
            } else {
                return this.fPersonSPI.getPeople(userIds, groupId, options, fields, request.getToken());
            }
        } else if (optionalPersonId.size() == 1) {
            // TODO: Add some crazy concept to handle the userId?
            final Set<UserId> optionalUserIds = ImmutableSet
                    .of(new UserId(UserId.Type.userId, optionalPersonId.iterator().next()));

            Person p = null;
            RestfulCollection<Person> people = null;

            try {
                people = this.fPersonSPI.getPeople(optionalUserIds, new GroupId(GroupId.Type.self, null),
                        options, fields, request.getToken()).get();
            } catch (final Exception e) {
                throw new RuntimeException(e);
            }

            if (people.getList() != null && people.getList().size() > 0) {
                p = people.getList().get(0);
            }

            return Futures.immediateFuture(p);
        } else {
            final ImmutableSet.Builder<UserId> personIds = ImmutableSet.builder();
            for (final String pid : optionalPersonId) {
                personIds.add(new UserId(UserId.Type.userId, pid));
            }
            // Every other case is a collection response of optional person
            // IDs
            return this.fPersonSPI.getPeople(personIds.build(), new GroupId(GroupId.Type.self, null), options,
                    fields, request.getToken());
        }
    }

    // Every other case is a collection response.
    return this.fPersonSPI.getPeople(userIds, groupId, options, fields, request.getToken());
}

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

/**
 * @param executorService where to perform the resource processing. Should really be a "real"
 *                        executor (not a directExecutor).
 * @return a {@link ListenableFuture} containing the result of the processing. The future will be
 *         cancelled if the {@link ResourcePool#close()} method is called.
 *///from  w  w  w  .  ja  v a2s.  co m
public synchronized <T> ListenableFuture<T> scheduleOperationWithResource(ThrowingFunction<R, T> withResource,
        final ListeningExecutorService executorService) {
    Preconditions.checkState(!closing.get());

    final ListenableFuture<T> futureWork = Futures.transformAsync(initialSchedule(),
            new AsyncFunction<Void, T>() {
                @Override
                public ListenableFuture<T> apply(Void input) throws Exception {
                    Either<R, ListenableFuture<Void>> resourceRequest = requestResource();
                    if (resourceRequest.isLeft()) {
                        R resource = resourceRequest.getLeft();
                        boolean resourceIsDefunct = false;
                        try {
                            return Futures.immediateFuture(withResource.apply(resource));
                        } catch (Exception e) {
                            resourceIsDefunct = (resourceUsageErrorPolicy == ResourceUsageErrorPolicy.RETIRE);
                            throw e;
                        } finally {
                            returnResource(resource, resourceIsDefunct);
                        }
                    } else {
                        return Futures.transformAsync(resourceRequest.getRight(), this, executorService);
                    }
                }
            }, executorService);

    pendingWork.add(futureWork);
    futureWork.addListener(() -> {
        synchronized (ResourcePool.this) {
            pendingWork.remove(futureWork);
        }
    }, executorService);

    // If someone else calls cancel on `futureWork` it makes it impossible to wait for that future
    // to finish using the resource, which then makes shutdown code exit too early.
    return Futures.nonCancellationPropagating(futureWork);
}