Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

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

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:com.facebook.buck.util.MoreFutures.java

/**
 * Create a convenience method for checking whether a future completed successfully because this
 * does not appear to be possible to do in a more direct way:
 * https://groups.google.com/forum/?fromgroups=#!topic/guava-discuss/rofEhagKnOc.
 *
 * @return true if the specified future has been resolved without throwing an exception or being
 *     cancelled.//  www. j  a va 2s.  c  o m
 */
public static <T> boolean isSuccess(ListenableFuture<T> future) {
    if (future.isDone()) {
        try {
            future.get();
            return true;
        } catch (ExecutionException e) {
            // The computation threw an exception, so it did not complete successfully.
            return false;
        } catch (CancellationException e) {
            // The computation was cancelled, so it did not complete successfully.
            return false;
        } catch (InterruptedException e) {
            throw new RuntimeException("Should not be possible to interrupt a resolved future.", e);
        }
    } else {
        return false;
    }
}

From source file:org.opendaylight.infrautils.utils.concurrent.ListenableFutures.java

public static <V, E extends Exception> V checkedGet(ListenableFuture<V> future,
        Function<? super Exception, E> mapper) throws E {
    try {//from w  ww  . java2  s .c o  m
        return future.get();
        // as in com.google.common.util.concurrent.AbstractCheckedFuture.checkedGet:
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw mapper.apply(e);
    } catch (CancellationException e) {
        throw mapper.apply(e);
    } catch (ExecutionException e) {
        throw mapper.apply(e);
    }
}

From source file:c5db.tablet.tabletCreationBehaviors.TabletLeaderBehaviorHelper.java

static void sendRequest(CommandRpcRequest<ModuleSubCommand> commandCommandRpcRequest,
        ModuleInformationProvider moduleInformationProvider) throws ExecutionException, InterruptedException {

    Request<CommandRpcRequest<?>, CommandReply> request = new Request<CommandRpcRequest<?>, CommandReply>() {
        @Override// w ww  .j ava 2  s  .  c  om
        public Session getSession() {
            return null;
        }

        @Override
        public CommandRpcRequest<ModuleSubCommand> getRequest() {
            return commandCommandRpcRequest;
        }

        @Override
        public void reply(CommandReply i) {

        }
    };
    ListenableFuture<C5Module> f = moduleInformationProvider.getModule(ModuleType.ControlRpc);
    ControlModule controlService;
    controlService = (ControlModule) f.get();
    controlService.doMessage(request);
}

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

/**
 * Tests if a client supports the "watch-project" command or not.
 *//* www .  j  av a2 s  .  c om*/
public static boolean checkWatchProjectCapability(WatchmanClient client) {
    ListenableFuture<Map<String, Object>> future = client.version(Collections.<String>emptyList(),
            Collections.singletonList("cmd-watch-project"));
    try {
        Map<String, Object> response = future.get();
        return response.containsKey("capabilities");
    } catch (InterruptedException e) {
        return false;
    } catch (ExecutionException e) {
        return false;
    }
}

From source file:google.registry.tools.BigqueryCommandUtilities.java

/**
 * Handler that takes a DestinationTable future and waits on its completion, printing generic
 * success/failure messages and wrapping any exception thrown in a TableCreationException.
 *///from w  w  w .java2s  . co m
static void handleTableCreation(String tableDescription, ListenableFuture<DestinationTable> tableFuture)
        throws TableCreationException {
    System.err.printf("Creating %s...\n", tableDescription);
    try {
        DestinationTable table = tableFuture.get();
        System.err.printf(" - Success: created %s.\n", table.getStringReference());
    } catch (Exception e) {
        Throwable error = e;
        if (e instanceof ExecutionException) {
            error = e.getCause();
        }
        String errorMessage = String.format("Failed to create %s: %s", tableDescription, error.getMessage());
        System.err.printf(" - %s\n", errorMessage);
        throw new TableCreationException(errorMessage, error);
    }
}

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

/**
 * Returns the failure for a {@link ListenableFuture}.
 * @param future Must have completed unsuccessfully.
 *//*from   w w w .  ja  v  a  2s.c o m*/
public static Throwable getFailure(ListenableFuture<?> future) {
    Preconditions.checkArgument(future.isDone());
    Preconditions.checkArgument(!isSuccess(future));
    try {
        future.get();
        throw new IllegalStateException("get() should have thrown an exception");
    } catch (ExecutionException e) {
        return e.getCause();
    } catch (CancellationException | InterruptedException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.google.devtools.kythe.analyzers.jvm.ClassFileIndexer.java

private static void analyzeCompilation(CompilationUnit compilationUnit, FileDataProvider fileDataProvider,
        KytheClassVisitor classVisitor) throws AnalysisException {
    ImmutableList<VName> enclosingJars = createJarIndex(compilationUnit);
    for (CompilationUnit.FileInput file : compilationUnit.getRequiredInputList()) {
        FileInfo info = file.getInfo();//from  w ww .  j  a v  a  2  s .  c  om
        if (info.getPath().endsWith(CLASS_FILE_EXT)) {
            classVisitor = classVisitor.withEnclosingJarFile(getEnclosingJar(enclosingJars, file));
            try {
                ListenableFuture<byte[]> contents = fileDataProvider.startLookup(info);
                classVisitor.visitClassFile(contents.get());
            } catch (ExecutionException | InterruptedException e) {
                throw new AnalysisException("error retrieving file contents for " + info, e);
            }
        }
    }
}

From source file:org.jclouds.concurrent.FutureIterables.java

private static <T> Iterable<T> unwrap(Iterable<ListenableFuture<? extends T>> values) {
    return transform(values, new Function<ListenableFuture<? extends T>, T>() {
        @Override//from w w w.  j  a v a2  s . com
        public T apply(ListenableFuture<? extends T> from) {
            try {
                return from.get();
            } catch (InterruptedException e) {
                propagate(e);
            } catch (ExecutionException e) {
                propagate(e);
            }
            return null;
        }

        @Override
        public String toString() {
            return "callGetOnFuture()";
        }
    });
}

From source file:org.opendaylight.controller.sal.restconf.broker.tools.RemoteStreamTools.java

public static Map<String, EventStreamInfo> createEventStream(RestconfClientContext restconfClientContext,
        String desiredStreamName) {
    ListenableFuture<Set<EventStreamInfo>> availableEventStreams = restconfClientContext
            .getAvailableEventStreams();
    final Map<String, EventStreamInfo> desiredEventStream = new HashMap<String, EventStreamInfo>();

    try {//from  w w  w.j a va2 s  .c  o  m
        Iterator<EventStreamInfo> it = availableEventStreams.get().iterator();
        while (it.hasNext()) {
            if (it.next().getIdentifier().equals(desiredStreamName)) {
                desiredEventStream.put(desiredStreamName, it.next());
            }
        }
    } catch (InterruptedException e) {
        logger.trace("Resolving of event stream interrupted due to  {}", e);
    } catch (ExecutionException e) {
        logger.trace("Resolving of event stream failed due to {}", e);
    }
    return desiredEventStream;
}

From source file:com.google.idea.blaze.base.lang.buildfile.sync.BuildLangSyncPlugin.java

@Nullable
private static BuildLanguageSpec parseLanguageSpec(Project project, WorkspaceRoot workspace,
        BlazeContext context) {/*from ww  w  .  j a  va  2 s .  c  o  m*/
    try {
        // it's wasteful converting to a string and back, but uses existing code,
        // and has a very minor cost (this is only run once per workspace)
        ListenableFuture<byte[]> future = BlazeInfo.getInstance().runBlazeInfoGetBytes(context,
                Blaze.getBuildSystem(project), workspace, ImmutableList.of(), BlazeInfo.BUILD_LANGUAGE);

        return BuildLanguageSpec.fromProto(Build.BuildLanguage.parseFrom(future.get()));

    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return null;
    } catch (ExecutionException | InvalidProtocolBufferException | NullPointerException e) {
        if (!ApplicationManager.getApplication().isUnitTestMode()) {
            LOG.error(e);
        }
        return null;
    } catch (Throwable e) {
        LOG.error(e);
        return null;
    }
}